example of django template for forms
<!-- forms.py -->
# Define a form using Django's forms module
from django import forms
class MyForm(forms.Form):
name = forms.CharField(label='Your Name', max_length=100)
email = forms.EmailField(label='Your Email')
message = forms.CharField(label='Your Message', widget=forms.Textarea)
<!-- views.py -->
# Import necessary modules
from django.shortcuts import render
from .forms import MyForm
# Define a view function to handle the form
def my_view(request):
# Check if the form has been submitted
if request.method == 'POST':
# Bind the form with the submitted data
form = MyForm(request.POST)
# Validate the form
if form.is_valid():
# Process the valid form data (in this example, just print it)
print(form.cleaned_data)
else:
# If the form has not been submitted, create a new form instance
form = MyForm()
# Render the template with the form
return render(request, 'my_template.html', {'form': form})
<!-- my_template.html -->
<!-- Display the form in the HTML template -->
<form method="post" action="{% url 'my_view' %}">
{% csrf_token %}
<!-- Display form fields -->
{{ form.as_p }}
<!-- Add a submit button -->
<button type="submit">Submit</button>
</form>
Explanation:
1. In forms.py
, a form class MyForm
is defined using Django's forms module. It includes fields for name, email, and a message.
2. In views.py
, a view function my_view
is defined. This function handles both GET and POST requests. When the form is submitted, it binds the form with the submitted data, validates it, and processes the valid data.
3. The template my_template.html
renders the form using the form
variable passed from the view. The method
attribute of the form specifies that the data should be sent using the POST method. The action
attribute specifies the URL to which the form data should be submitted.
4. {% csrf_token %}
is included for security reasons to prevent Cross-Site Request Forgery attacks.
5. {{ form.as_p }}
renders the form fields as paragraphs. This is just one way to render form fields; you can use other methods like {{ form.as_table }}
or {{ form.as_ul }}
depending on your preference.
6. The submit button allows users to submit the form.
7. The my_view
function is mapped to a URL using Django's URL patterns. Make sure to set up your project URLs accordingly.