01 Build a form
Start with the Note model from the ORM tutorial. Create core/forms.py. Explicitly list the fields visitors may edit so future model fields are not automatically exposed.
from django import forms
from .models import Note
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ["title", "body"]02 Handle GET and POST
Add this view to core/views.py. This example limits note creation to signed-in users. Invalid submissions are rendered again with their errors. Successful submissions redirect to avoid saving twice on refresh.
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from .forms import NoteForm
@login_required
def note_create(request):
form = NoteForm(request.POST if request.method == "POST" else None)
if request.method == "POST" and form.is_valid():
form.save()
return redirect("home")
return render(request, "core/note_form.html", {"form": form})03 Render the form
Save this as core/templates/core/note_form.html. Include the CSRF token in forms that change data. Django will render field validation errors alongside the relevant inputs.
{% extends "core/base.html" %}
{% block content %}
<h1>New note</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save note</button>
</form>
{% endblock %}04 Add the route and try it
Import note_create into config/urls.py and add the route below to urlpatterns. Sign in through the admin first, then visit /notes/new/. Submit an empty title to see validation, and a valid title to create a note.
path("notes/new/", note_create, name="note_create"),Read the official Django documentation for details and more examples.