7 Django Forms
7 Django Forms
Django provides a Form class which is used to create HTML forms. It describes a form and how it works and
appears.
It is similar to the ModelForm class that creates a form by using the Model, but it does not require the
Model.
Each field of the form class map to the HTML form <input> element and each one is a class itself, it
manages form data and performs validation while submitting the form.
A StudentForm is created that contains two fields of CharField type. Charfield is a class and used to create
an HTML text input component in the form.
The label is used to set HTML label of the component and max_length sets length of an input value.
Note: Django Form does not include <form> tags, or a submit button. We'll have to provide
those ourselves in the template.
Commonly used fields and their details are given in the below table.
Let's see a complete example to create an HTML form with the help of Django Form class.
Suppose we want to create a form to get Student information, use the following code.
Now, we need to instantiate the form in views.py file. See, the below code.
// views.py
def index(request):
student = StudentForm()
return render(request,"index.html",{'form':student})
Passing the context of form into index template that looks like this:
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</body>
</html>
Run Server and access the form at browser by localhost:8000/index, and it will produce the following output.
There are other output options though for the <label>/<input> pairs:
Note: that we'll have to provide the surrounding <table> or <ul> elements yourself.
← Prev Next →
Feedback
React Native Python Design Python Pillow Python Turtle Keras tutorial
tutorial Patterns tutorial tutorial Keras
React Native Python Design Python Pillow Python Turtle
Patterns
Preparation