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.


Template

Start by adding a link in the members template:

members/templates/index.html:

The result will look like this:


New Template

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

members/templates/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.


View

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

members/views.py:


URLs

Add a path() function in the members/urls.py file, that points the url 127.0.0.1:8000/members/add/ to the right location:

members/urls.py:

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/urls.py file that points to the right view:

members/urls.py:


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/views.py file:

members/views.py:

Changes that are made in the views.py 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:


ArmenianEnglish