Created
June 26, 2023 07:25
-
-
Save danjac/8f46364b6a0abed10ee33c2b3e9516be to your computer and use it in GitHub Desktop.
Tidier form validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example from Django docs https://docs.djangoproject.com/en/4.2/topics/forms/ | |
def get_name(request): | |
# if this is a POST request we need to process the form data | |
if request.method == "POST": | |
# create a form instance and populate it with data from the request: | |
form = NameForm(request.POST) | |
# check whether it's valid: | |
if form.is_valid(): | |
# process the data in form.cleaned_data as required | |
# ... | |
# redirect to a new URL: | |
return HttpResponseRedirect("/thanks/") | |
# if a GET (or any other method) we'll create a blank form | |
else: | |
form = NameForm() | |
return render(request, "name.html", {"form": form}) | |
# a bit tidier | |
def get_name_improved(request): | |
# initialize form: make sure to explicity pass in request.POST to invalidate | |
# any missing params | |
form = NameForm(request.POST) if request.method == "POST" else NameForm() | |
# this will always be False if form is unbound (POST is None) so we can call it safely here | |
if form.is_valid(): | |
return HttpResponseRedirect("/thanks/") | |
return render(request, "name.html", {"form": form}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment