Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Render Django Form Fields Manually
Next article icon

Prerequisites:Django Installation |Introduction to Django
Django works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. 
Suppose there is a form that takesUsername,gender, andtext as input from the user, the task is to validate the data and save it.
In django this can be done, as follows:
 

Python
fromdjango.dbimportmodels# model named PostclassPost(models.Model):Male='M'FeMale='F'GENDER_CHOICES=((Male,'Male'),(FeMale,'Female'),)# define a username field with bound  max length it can haveusername=models.CharField(max_length=20,blank=False,null=False)# This is used to write a posttext=models.TextField(blank=False,null=False)# Values for gender are restricted by giving choicesgender=models.CharField(max_length=6,choices=GENDER_CHOICES,default=Male)time=models.DateTimeField(auto_now_add=True)

After creating the data models, the changes need to be reflected in the database to do this run the following command:
 

python manage.py makemigrations


Doing this compiles the models and if it didn't find any errors then, it creates a file in the migration folder. Later run the command given below to finally reflect the changes saved onto the migration file onto the database.
 

python manage.py migrate


Now a form can be created. Suppose that the username length should not be less than 5 and post length should be greater than 10. Then we define the ClassPostForm with the required validation rules as follows: 
 

Python
fromdjango.formsimportModelFormfromdjangoimportformsfromformValidationApp.modelsimport*# define the class of a formclassPostForm(ModelForm):classMeta:# write the name of models for which the form is mademodel=Post# Custom fieldsfields=["username","gender","text"]# this function will be used for the validationdefclean(self):# data from the form is fetched using super functionsuper(PostForm,self).clean()# extract the username and text field from the datausername=self.cleaned_data.get('username')text=self.cleaned_data.get('text')# conditions to be met for the username lengthiflen(username)<5:self._errors['username']=self.error_class(['Minimum 5 characters required'])iflen(text)<10:self._errors['text']=self.error_class(['Post Should Contain a minimum of 10 characters'])# return any errors if foundreturnself.cleaned_data

Till now, the data models and the Form class are defined. Now the focus will be on how these modules, defined above, are actually used.
First, run on localhost through this command 
 

python manage.py runserver


Openhttp://localhost:8000/ in the browser, then it's going to search in theurls.py file, looking for ' ' path
urls.py file is as given below: 
 

Python
fromdjango.contribimportadminfromdjango.urlsimportpath,includefromdjango.conf.urlsimporturlfromdjango.shortcutsimportHttpResponsefrom.importviewsurlpatterns=[path('',views.home,name='index'),]

Basically, this associates the ' ' url with a functionhome which is defined inviews.py file.
views.py file
 

Python
from.modelsimportPostfrom.formsimportPostFormfrom.importviewsfromdjango.shortcutsimportHttpResponse,render,redirectdefhome(request):# check if the request is postifrequest.method=='POST':# Pass the form data to the form classdetails=PostForm(request.POST)# In the 'form' class the clean function# is defined, if all the data is correct# as per the clean function, it returns trueifdetails.is_valid():# Temporarily make an object to be add some# logic into the data if there is such a need# before writing to the databasepost=details.save(commit=False)# Finally write the changes into databasepost.save()# redirect it to some another page indicating data# was inserted successfullyreturnHttpResponse("data submitted successfully")else:# Redirect back to the same page if the data# was invalidreturnrender(request,"home.html",{'form':details})else:# If the request is a GET request then,# create an empty form object and# render it into the pageform=PostForm(None)returnrender(request,'home.html',{'form':form})

home.html template file 
 

html
{% load bootstrap3 %}{% bootstrap_messages %}<!DOCTYPE html><htmllang="en"><head><title>Basic Form</title><metacharset="utf-8"/><metaname="viewport"content="width=device-width, initial-scale=1, shrink-to-fit=no"><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></head><bodystyle="padding-top: 60px;background-color: #f5f7f8 !important;"><divclass="container"><divclass="row"><divclass="col-md-4 col-md-offset-4"><h2>Form</h2><formaction=""method="post"><inputtype='hidden'/>             {%csrf_token %}                {% bootstrap_form form %}<!-This is the form variable which we are passing from the functionof home in views.py file. That's the beauty of Django wedon't need to write much codes in this it'll automatically passall the form details in here-><divclass="form-group"><buttontype="submit"class="btn btn-default ">                  Submit</button></div></form></div></div></div></body></html>

Openinghttp://localhost:8000/ in the browser shows the following,
 


If a form with a username of length less than 5 is submitted, it gives an error at the time of submission and similarly for the Post Text filled as well. The following image shows how the form behaves on submitting invalid form data.
 


 


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp