Created
June 26, 2023 07:34
-
-
Save danjac/d0cab660c8d3b6d1d3fe66a399ec392f to your computer and use it in GitHub Desktop.
Form handler function
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
# https://docs.djangoproject.com/en/4.2/topics/forms/ | |
# original example | |
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}) | |
# helper function | |
def handle_form(form_class, request, **form_kwargs): | |
"""Handles form processing, returns form instance and bool if valid or not. | |
Any other arguments you want to pass into a form for both GET and POST can be included | |
in form_kwargs, e.g. "instance". | |
""" | |
if request.method == "POST": # could maybe also check PUT if your requirements need it | |
form = form_class(data=request.POST, files=request.FILES, **form_kwargs) | |
return form, form.is_valid() | |
return form_class(**form_kwargs), False | |
# rewriting original view | |
def get_name_improved(request): | |
form, is_valid = handle_form(NameForm, request) | |
if is_valid: | |
# process the data in form.cleaned_data as required | |
# ... | |
# redirect to a new URL: | |
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