Hello World, Welcome to projectsplaza.com. Today we will learn how to save form data in the database in django. We will use the SQL database. I am assuming that you have installed Django in your system, If not then please refer to this tutorial. We will create a simple contact form in which the user will fill his basic information like full name, email, and message.
I have divided this tutorial into the following parts.
- Create a contact model
- Create contact form template
- Submit form and save data in the database
Create a contact model
In this step, we will create a contact model in which we will save data.
- Open the models.py in your app
- Add the following Contact class in this file.
class Contact(models.Model): full_name=models.CharField(max_length=100) email=models.CharField(max_length=200) message=models.TextField() def __str__(self): return self.full_name
- Run the following commands to apply migrations
- py manage.py makemigrations
- py manage.py migrate
Create contact form template
Create templates folder in your app directory and create contact.html file in this templates folder. Add the following code in this file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Contact Form</title> </head> <body> <h3>Contact Form</h3> <hr/> <form method="post" action="/contact-form"> {% if messages %} {% for msg in messages %} <p>{{msg}}</p> {% endfor %} {% endif %} {% csrf_token %} <table border="1" cellpadding="5"> <tr> <th>Full Name</th> <td><input type="text" name="full_name" /></td> </tr> <tr> <th>Email</th> <td><input type="email" name="email" /></td> </tr> <tr> <th>Message</th> <td> <textarea name="message"></textarea> </td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </table> </form> </body> </html>
Submit form and save data in the database
Add the following code in views.py file.
def contact(request): if request.method=='POST': full_name=request.POST['full_name'] email=request.POST['email'] message=request.POST['message'] contact=Contact.objects.create(full_name=full_name,email=email,message=message) messages.success(request,'Data has been submitted') return render(request,'contact.html')
The above code will verify the request method and save the data in Contact Model.
Please add the following code in your-app/urls.py
path(‘contact’,views.contact_form,name=’contact-form’)
Start the server and run your project. You will see the following screen.