3👍
Check you code and ask yourself what happens if you have a POST request and the form doesn’t validate – you’ll find out that in this case you have no explicit return path, so the function implicitely returns None
.
The fix is dead simple : deindent the last two line of your function, so you when the form doesn’t validate you return the rendered template too:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = RegistrationForm()
# MAKE SURE WE ALWAYS RETURN A RESPONSE:
# we end up here when it's a GET request
# AND when it's a POST request and the form
# did not validate
args = {'form': form}
return render(request, 'users/reg_form.html', args)
1👍
You have to return response from the inner else
block:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
# here
...
- [Django]-Request.data in DRF v/s serializers.data in DRF
- [Django]-How to restrict access for staff users to see only their information in Django admin page?
1👍
Make sure you return something if the form is not valid and your form.is_valid()
fails.
Example:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/') # or render(...)/whatever you need to redirect to
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)
Hope this helps!
- [Django]-Getting the right dependency in Heroku
- [Django]-Django: Using 2 different AdminSite instances with different models registered
- [Django]-Edit the opposite side of a many to many relationship with django generic form
0👍
You are missing the else code. Your if statement says: If the form is valid, save the form. But what if the form is not valid, What if the username is all special characters(ex: !@#$%%%^^) or what if the username is only 1 Character long ex: (username:A). Or what if the password is only 3 characters long (ex: pas) In all these scenarios, the user should get the blank form back. You should also consider using class based views for registration This link will help
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
**if form.is_valid():**
# What if the form is not valid you haven't accounted for that
form.save()
return redirect('/')
else:
# Adding a else solves this problem. The user gets a blank form back
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)**
- [Django]-What's the best way to handle different forms from a single page in Django?
- [Django]-Django handle newlines in textarea
- [Django]-Django and Apache Issue