Django – Adding a Form to Your Django Site

django-forms

In your Django website you have models. These models represent tables in your database. So, what would you do if you wanted to record new model data into your DB? How would you get user input? Of course, using forms.

There is an impractical way to do this but let’s skip that and show the better method of adding a form to your Django site.

First, create “forms.py” file in your project if you don’t already have it. I had to create this file myself since my Django project template (created by PyCharm) didn’t have it by default.

Your forms.py file will simply be something like this:

Here we have to import our Item class since we are referring to it from our form class. Our form class “AddItemForm” inherits from “forms.ModelForm” class. By inheriting from this class, we can easily tell Django which model’s data we will be submitting using this form. Of course, for Django to know the model class we are preparing the form for, we need to use “Meta” class and specify which model this form will be for and which fields will be input through the form fields. See how I define the “Meta” class above.

Once we are done with forms.py, we can modify our urls.py and views.py.

URLS.py

In your urls.py you need to specify a url pattern that resolves to a view which loads your form. It could be something like this:

VIEWS.py

In views.py you need to add a new view “def” for “view_add_item” like below:

See add_item.html here? That is our template file which will be rendered once a request to “mysite.com/add_item” is received. Here we are passing the context {‘Form’: form} to add_item.html template. Which means add_item.html template has a reference for “Form” and it will be replaced by this instance of “form”.

add_item.html could look like this:

Details of this template is not the subject of this post but I can say add_item.html extends base.html. This is subject of another post about template inheritance. Here Form.as_p means display this form’s fields as paragraphs, each field and label in its own line.

Hope this helps.
Good Luck,
Serdar