Home > Net >  View didn't return HTTPResponse object
View didn't return HTTPResponse object

Time:11-25

I was trying to create a blog app by following an online Django tutorial and while I was testing the sign-up page, I ran into a Value Error saying that the view did not return a HTTP response object. i tried everything but i could not find the answer as i am not a Django expert

in the users app's views.py file was the code that threw the error

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages


def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account Created for {username}')
            return redirect('blog-home')
    else:
        form = UserCreationForm()
        return render(request, 'users/register.html', {'form': form})

and this is the register template

{% extends "myblog/base.html" %}
{% block content %}
   <div >
        <form method="POST">
            {% csrf_token %}
            <fieldset >
                    <legend >
                        Join Today!
                    </legend>
                    {{ form.as_p }}
            </fieldset>
            <div >
                <button  type="submit">
                    Sign Up!
                </button>
            </div>
        </form>
        <div >
            <small >
                Already Have an account?
                <a href="#" >Sign In!</a>
            </small>
        </div>
   </div>
{% endblock content%}

And this is the file structure of the project File Structure

CodePudding user response:

If we have a POST request, and the form is not valid, you do not return anything. Unindent the render call, so:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account Created for {username}')
            return redirect('blog-home')
    else:
        form = UserCreationForm()
    return render(request, 'users/register.html', {'form': form})

CodePudding user response:

return something for the function register also , you are returning only in if else conditions

CodePudding user response:

You can write function like this ...

def register(request):
    form = UserCreationForm()
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account Created for {username}')
            return redirect('blog-home')
        else:
            form.errors
    context = {'form': form}
    return render(request, 'users/register.html', context)
  • Related