Skip to content

Instantly share code, notes, and snippets.

@danjac
Created June 26, 2023 07:25
Show Gist options
  • Save danjac/8f46364b6a0abed10ee33c2b3e9516be to your computer and use it in GitHub Desktop.
Save danjac/8f46364b6a0abed10ee33c2b3e9516be to your computer and use it in GitHub Desktop.
Tidier form validation
# 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