django forms set class
In Django, a form is a way to collect user input and validate it before saving it to the database. To create a form in Django, you can use the forms
module provided by Django.
To define a form, you need to create a class that inherits from the forms.Form
class. This class will represent the form and define its fields and validation rules.
Here are the steps to create a Django form class:
- Import the
forms
module:
from django import forms
- Define a class for your form and inherit from
forms.Form
:
class MyForm(forms.Form):
pass
- Add fields to your form by defining class attributes:
class MyForm(forms.Form):
field1 = forms.CharField(max_length=100)
field2 = forms.EmailField()
- Customize the form fields by providing additional arguments to the field constructors. For example, you can specify the maximum length, required status, default value, or widget for a field:
class MyForm(forms.Form):
field1 = forms.CharField(max_length=100, required=False, initial='Hello')
field2 = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Enter your email'}))
- Add validation methods to the form class. These methods should start with
clean_
followed by the field name. For example, if you have a field namedemail
, you can add a validation method calledclean_email
:
class MyForm(forms.Form):
field1 = forms.CharField(max_length=100)
field2 = forms.EmailField()
def clean_field1(self):
# Add custom validation logic here
data = self.cleaned_data['field1']
# Perform validation and raise forms.ValidationError if invalid
return data
- Use the form in your views by creating an instance of the form class and passing it to the template context. In your template, you can render the form using the
{{ form }}
template variable:
def my_view(request):
form = MyForm()
return render(request, 'my_template.html', {'form': form})
- In your template, you can access the form fields and their associated attributes using dot notation. For example, to render the
field1
input field, you can use{{ form.field1 }}
:
<form method="post" action="{% url 'my_view' %}">
{% csrf_token %}
{{ form.field1 }}
{{ form.field2 }}
<input type="submit" value="Submit">
</form>
These are the basic steps to create a Django form using the forms
module. You can further customize your form by adding validation logic, error messages, and handling form submissions in your views.