Forms: Validation
Description
from django import forms
from .models import Note
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['title', 'content']
class Meta
-
model = Note
: Tells Django that this form is associated with the Note model; -
fields = ['title', 'content']
: Specifies exactly which fields from the model we want to include in our form.
def index(request):
if request.method == 'POST':
form = NoteForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'notes.html')
Handling Form Submission (POST method)
-
Checks if the current request method is POST. If it is, it means the user submitted a form;
-
Creates a NoteForm instance with the data from the POST request (
request.POST
); -
Checks if the form is valid using
form.is_valid()
. If the form is valid, it saves the data to the database usingform.save()
.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Awesome!
Completion rate improved to 4
Forms: Validation
Veeg om het menu te tonen
Description
from django import forms
from .models import Note
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['title', 'content']
class Meta
-
model = Note
: Tells Django that this form is associated with the Note model; -
fields = ['title', 'content']
: Specifies exactly which fields from the model we want to include in our form.
def index(request):
if request.method == 'POST':
form = NoteForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'notes.html')
Handling Form Submission (POST method)
-
Checks if the current request method is POST. If it is, it means the user submitted a form;
-
Creates a NoteForm instance with the data from the POST request (
request.POST
); -
Checks if the form is valid using
form.is_valid()
. If the form is valid, it saves the data to the database usingform.save()
.
Bedankt voor je feedback!