Django Tutorial
Django Create A Complete Project
Django Template
Django Database Query
Django Form
Django Authentication and Permission Management
Django unittest
Django Advanced
In this Django Form System tutorial, we'll cover the basics of Django forms, including how to create, validate, and render forms.
Django provides a powerful form system that allows you to define and manage HTML forms easily. To create a simple form, create a new file called forms.py
in your Django app folder and add the following code:
from django import forms class ContactForm(forms.Form): name = forms.CharField(label='Name', max_length=100) email = forms.EmailField(label='Email') message = forms.CharField(label='Message', widget=forms.Textarea)
In this example, we've created a ContactForm
class that inherits from django.forms.Form
. We defined three fields: name
, email
, and message
, each with different form field classes.
Now, let's use the ContactForm
in a view. In your app's views.py
file, add the following code:
from django.shortcuts import render from .forms import ContactForm def contact(request): form = ContactForm() return render(request, 'contact.html', {'form': form})
In this example, we imported the ContactForm
class and created an instance of the form in our view function. We then passed the form instance to our template context.
Next, let's create a template to render the form. In your project's templates
folder, create a new file called contact.html
and add the following code:
{% extends 'base.html' %} {% block content %} <h2>Contact Us</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Send Message</button> </form> {% endblock %}
In this example, we used the {{ form.as_p }}
template tag to render the form as a series of paragraphs, with each field enclosed in a <p>
element. You can also use {{ form.as_table }}
to render the form as a table, or {{ form.as_ul }}
to render it as a list.
Finally, let's handle form submission and validation. Update your views.py
file with the following code:
from django.shortcuts import render, redirect from .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process the data in form.cleaned_data as required # ... return redirect('success') else: form = ContactForm() return render(request, 'contact.html', {'form': form})
In this example, we added a check for the request method. If it's a POST
request, we create an instance of ContactForm
with the submitted data. Then, we call the is_valid()
method to validate the form data. If the form is valid, we can process the form data and redirect to a success page.
This tutorial covered the basics of the Django Form System, including creating, validating, and rendering forms. You can extend this functionality by adding custom form fields, validation rules, and widgets as needed.
Django form class and instance usage:
# forms.py in your app from django import forms class MyForm(forms.Form): name = forms.CharField() email = forms.EmailField()
Django form handling and submission:
# views.py in your app from django.shortcuts import render from .forms import MyForm def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): # Process form data else: form = MyForm() return render(request, 'template.html', {'form': form})
Django form widgets and customization:
# forms.py in your app from django import forms class MyForm(forms.Form): my_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter data'}))
ModelForm in Django forms system:
# forms.py in your app from django import forms from .models import MyModel class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['name', 'email']
Working with form instances in Django:
# views.py in your app from django.shortcuts import render from .forms import MyForm def my_view(request): form_instance = MyForm(initial={'name': 'John'}) return render(request, 'template.html', {'form_instance': form_instance})
Django form templates and rendering:
<!-- template.html in your app's templates directory --> <form method="post" action="{% url 'submit_form' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form>
Handling file uploads with Django forms:
# forms.py in your app from django import forms class FileUploadForm(forms.Form): file = forms.FileField()
Django form instance creation and modification:
# views.py in your app from django.shortcuts import render from .forms import MyForm def my_view(request): if some_condition: form_instance = MyForm() else: form_instance = MyForm(initial={'name': 'John'}) return render(request, 'template.html', {'form_instance': form_instance})