Introduction
In this context, the final goal is using a ModelForm for submitting user input in Django application. Actually, there is another article exist in the previous one. That previous article is also focusing on how to perform a user input form submit in Django application. The first one exist in article ‘How to Send Input Text from Django Template File to Function exist in Django View using GET method in Django Application‘ and the next one is exist in ‘How to Send Input Text from Django Template File to Function exist in Django View using POST method in Django Application‘. So, before going on to the detail for submitting user input through a ModelForm, below are descriptions for the Django project and also the Django application :
First of all, the structure of the Django project :
C:\project>dir Volume in drive C is Windows-SSD Volume Serial Number is CA30-19A4 Directory of C:\project 09/06/2022 07:13 AM <DIR> . 09/06/2022 10:42 AM <DIR> .. 09/06/2022 08:19 PM <DIR> apps 08/24/2022 09:30 AM 159,744 db.sqlite3 08/20/2022 05:17 PM 683 manage.py 08/20/2022 05:18 PM <DIR> project 09/06/2022 07:14 AM 126 requirements.txt 3 File(s) 160,553 bytes 4 Dir(s) 65,556,508,672 bytes free C:\project>
Just get into the project apps folder inside the project folder. On the other hand, below is the content of the apps folder :
(env) C:\project\apps>dir Volume in drive C is Windows-SSD Volume Serial Number is CA30-19A4 Directory of C:\project\apps 09/06/2022 08:19 PM <DIR> . 09/06/2022 07:13 AM <DIR> .. 08/24/2022 10:02 AM 215 admin.py 08/24/2022 08:43 AM 146 apps.py 09/17/2022 02:18 PM 454 forms.py 08/26/2022 02:19 PM <DIR> migrations 08/26/2022 02:05 PM 1,548 models.py 09/06/2022 07:01 PM <DIR> templates 08/24/2022 08:43 AM 63 tests.py 09/06/2022 08:03 AM 118 urls.py 09/08/2022 06:43 AM 871 views.py 08/24/2022 08:43 AM 0 __init__.py 09/08/2022 06:43 AM <DIR> __pycache__ 7 File(s) 2,961 bytes 6 Dir(s) 66,276,225,024 bytes free (env) C:\project\apps>
How to Use ModelForm to Create a Form for submitting User Input in Django Application
Using the above structure of the Django project and application, below are the steps for submitting form containing user input. Furthermore, the form will be generated by a ModelForm. So, below are the steps for accomplishing the purpose :
-
First of all, just create a file with the name of ‘forms.py’. That file will available in the ‘apps’ folder or the folder which represent the Django application folder.
-
Next, fill the ‘forms.py’ file with the following content :
class StaffForm(ModelForm): class Meta: model = Staff fields = '__all__'
In the above content of the ‘forms.py’, there is a specific declaration of a class with the name of StaffForm. It use a model with the name of ‘Staff’. Below is the content of the Staff class which exist in the ‘models.py’ file :
class Staff(models.Model): id_unique = models.AutoField(primary_key=True) user_staff = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True, default=None) name = models.CharField(max_length=255, default="") unit = models.ForeignKey(Unit, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return '%s' %(self.name)
-
After defining the model form exist in ‘forms.py’, just define the Django template file for preparing the user input form. Actually, just edit the file with the name of ‘add_staff.html’ in this context. The placement of the ‘add_staff.html’ is in a folder with the name of ‘templates’ which exist inside the apps folder. Below is the content of the ‘add_staff.html’ file :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" action="{% url 'save_staff' %}"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"></input> </form> </body> </html>
The most important thing is the ‘{{ form }}’ part. It is a block tag form for rendering the ModelForm of ‘StaffForm’.
-
For the most important exist in this step, it is defining the ‘views.py’ file. It is a file for defining how to render the form and how to process the form further. Below is the actual content of the ‘views.py’ file :
def add_staff(request): form = StaffForm context = {'form':form} return render(request,"add_staff.html", context) def save_staff(request): if request.POST: staff = Staff() if(request.POST.get('user')!= ''): user_staff = User.objects.get(pk=request.POST.get('user')) print(user_staff) staff.user_staff = user_staff staff.name = request.POST.get('name') if(request.POST.get('unit')!= ''): unit = Unit.objects.get(pk=request.POST.get('unit')) staff.unit = unit staff.save()
-
Last but not least, just define the URL for representing each process. The first one is for loading the form where the process handling exist in a function with the name of ‘add_staff’. The next one is the function for processing the entry or the input from user where it is passed through a model form using a POST method request. Below is the definition of each of the process in the ‘urls.py’ file as follows :
from django.urls import path from apps import views urlpatterns = [ path('', views.index, name="index"), path('list_staff/', views.list_staff, name="list_staff"), path('add_staff/', views.add_staff, name="add_staff"), path('save_staff/', views.save_staff, name="save_staff"), ]
-
After preparing all the necessary steps for define the model form, just run the Django application. Access the URL of ‘add_staff/’ to start render the input form generated from ModelForm of ‘StaffForm’. For the full example of the local URL as an example is ‘localhost:8000/add_staff/’. The following image display will appear upon accessing the URl of that Django application :
-
Continue on the previous step, just insert it accordingly as in the following appearance :
-
Finally, just click the submit button in the that page above. Actually, in order to prove that the process is a success, the process will direct it to another page which is listing the result of the input. Below is the appearance of the result after clicking the Submit button :
As for the function defining to render the list_staff.html page, below is the function exist in the ‘views.py’ file :
def list_staff(request): staff = Staff.objects.all() print(staff) context = {'staffs':staff} return render(request,"list_staff.html", context)
One thought on “How to Use ModelForm to Create a Form for submitting User Input in Django Application”