[Django]-How to solve the did not return httpresonse error with django?

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 
    ...

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!

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)**

Leave a comment