Django Add Record

Django Add Record

Adding Records

So far we have created a Members table in our database, and we have inserted five records by writing code in the Python shell.

We have also made a template that allows us to display the content of the table in a web page.

Now we want to be able to create new members from a web page.


Start by adding a link in the members template:


The result will look like this:

New Template

Add a new template in the templates folder, named add.html:


The template contains an empty HTML form with two input fields and a submit button.

Note: Django requires this line in the form:
{% csrf_token %}
to handle Cross Site Request Forgeries in forms where the method is POST.


Next, add a view in the members/ file, name the new view add:



Add a path() function in the members/ file, that points the url to the right location:


In the browser, click the “Add member” link and the result should look like this:

More URLs

Did you notice the action attribute in the HTML form? The action attribute specifies where to send the form data, in this case the form data will be sent to addrecord/, so we must add a path() function in the members/ file that points to the right view:


Code for Adding Records

So far we have made the user interface, and we point the URL to the view called addrecord, but we have not made the view yet.

Make sure you add the addrecord view in the in the members/ file:


Changes that are made in the file:

Line 1: import HttpResponseRedirect
Line 3: import revers

The addrecord view does the following:

  • Gets the first name and last name with the request.POST statement.
  • Adds a new record in the members table.
  • Redirects the user back to the index view.

Try to add a new record and see how it works:

If you press the submit button, the members table should have been updated: