In Part 1, you created a basic Django app with views, models, templates, and admin. In this post, you’ll learn how to handle user input by creating forms and saving data to your database using Django’s built-in form features.
What You’ll Learn
- Create a Django Form class
- Render the form in a template
- Handle form submission (POST)
- Validate user input
- Save form data to the database
Step 1: Update Your Model
Let’s use the same Post
model from Part 1. If not already created:
1 2 3 4 5 6 7 8 |
from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.title |
Step 2: Create a Django Form
In myapp/forms.py
, create this form:
1 2 3 4 5 6 7 |
from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] |
Step 3: Add View for the Form
In myapp/views.py
:
1 2 3 4 5 6 7 8 9 10 11 12 |
from django.shortcuts import render, redirect from .forms import PostForm def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = PostForm() return render(request, 'myapp/create_post.html', {'form': form}) |
Step 4: Add URL Route
In myapp/urls.py
:
1 2 3 4 5 6 |
from . import views urlpatterns = [ path('', views.home, name='home'), path('create/', views.create_post, name='create_post'), ] |
Step 5: Create the HTML Form Template
In templates/myapp/create_post.html
:
1 2 3 4 5 6 7 |
<h1>Create New Post</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> |
Step 6: Link to Create Post Page
In your home.html
, add a link:
1 |
<a href="{% url 'create_post' %}">Create a New Post</a> |
Conclusion
You’ve successfully created a dynamic form in Django that accepts user input, validates it, and saves it to the database. This is the foundation for building blogs, comment systems, contact forms, and more.
In Part 3, we’ll cover user authentication so you can add login, logout, and user registration features!