Django A form is a set of advanced HTML Forms , have access to python Create and use Python Mode support HTML All the functions of the form . This article focuses on how to create basic forms using various form fields and attributes . stay Django Creating a form in is exactly like creating a model , You need to specify which fields and types exist in the form . for example , To enter the registration form , Name may be required (CharField)、 Volume number (IntegerField) etc. .
Use Django Form create form
Use examples to illustrate Django Forms . Consider a person named geeksforgeeks Project , It has a name called geeks Applications for .
In your geek application, create a named forms.py The new document of , You will make all the forms in it . To create a Django Forms , You need to use Django Form Class. Let's demonstrate . In your forms.py Enter the following ,
from django import forms
# create form
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())
Let's explain what happened , The left side indicates the name of the field , On the right side , You define the various functions of the input fields accordingly . The syntax of a field is expressed as grammar :
Field_name = forms.FieldType(attributes)
Now you will render the form into a view , Move to views.py And create a home_view, As shown below .
from django.shortcuts import render
from .forms import InputForm
# Create your view here .
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "home.html", context)
In the view , Just in forms.py Create an instance of the form class created above in . Now let's edit the template > home.html
<form action = "" method = "post">
{% csrf_token %}
{{form }}
<input type="submit" value=Submit">
</form>
All set to check if the form is working properly let's access http://localhost:8000/
The form works normally , But the visual effect is disappointing ,Django Provides some predefined ways to display forms in a convenient way . In the template , The following will modify the input as ,
- {{ form.as_table }} Will present them as wrapped in <tr> Table cells in labels
- {{ form.as_p }} Will present them in <p> In the label
- {{ form.as_ul }} Will present them in <li> In the label
You can also use {{ form.field_name }} Modify these settings and display the fields as needed , But if some fields are empty and therefore require special care , This may change the normal verification process .