Creating Forms in Django
Introduction
Forms are a crucial part of web applications. They allow users to submit data that can be processed and stored by the application. In Django, forms are easy to create and validate using Django's built-in form handling system.
Step 1: Setting Up Your Django Project
First, make sure you have Django installed. If not, you can install it using pip:
Next, create a new Django project and a new app within that project:
Step 2: Creating a Simple Form
Create a new file forms.py
in your app directory (myapp/forms.py
) and define a form:
from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea)
This form has three fields: name, email, and message. The message field uses a textarea widget.
Step 3: Creating a View
Next, you'll need a view to handle the form. Open views.py
in your app directory and add the following code:
from django.shortcuts import render from .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process the form data return render(request, 'thanks.html') else: form = ContactForm() return render(request, 'contact.html', {'form': form})
Step 4: Creating Templates
Create two new HTML files in a templates
directory within your app: templates/contact.html
and templates/thanks.html
.
contact.html
:
<!DOCTYPE html> <html> <head> <title>Contact Form</title> </head> <body> <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </body> </html>
thanks.html
:
<!DOCTYPE html> <html> <head> <title>Thank You</title> </head> <body> <h1>Thank You!</h1> <p>Your message has been sent.</p> </body> </html>
Step 5: Updating URLs
Finally, update your app's urls.py
to include a path for the contact view. Create a new file urls.py
in your app directory and add the following code:
from django.urls import path from . import views urlpatterns = [ path('contact/', views.contact, name='contact'), ]
Don't forget to include your app's URLs in the project's main urls.py
:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')), ]
Conclusion
That's it! You've created a simple contact form in Django. You can now extend this form to include more fields, validation, and processing logic as needed.