Home > OS >  django-HttpResponse returned None
django-HttpResponse returned None

Time:06-12

I am getting an error while I run my project:

ValueError: The view ... didn't return an HttpResponse object. It returned None instead.

I have seen other questions like this, but their answers don't seem to work. For my other projects the same code worked.

I searched on the net for days but I haven't had any luck.

views.py -

from .models import create_message
from .forms import MessageForm
from django.http import HttpResponseRedirect

def create_message(request):
    submitted = False
    if request.method == "POST":
        form = MessageForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/create_message?submitted=True')
        else:
            form = MessageForm
            if 'submitted' in request.GET:
                submitted = True            
        return render(request, 'send/create_message.html', {'form': form, 'submitted': submitted})

forms.py -

from django.forms import ModelForm
from .models import create_message

class MessageForm(ModelForm):
    class Meta:
        model = create_message
        fields = ('message', 'app_name', 'time')
        labels = {
            'message': 'Message',
            'app_name': 'App',
            'time': 'Time',
                 }
        widgets = { 
            'message': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Message'}),
            'app_name': forms.Select(attrs={'class':'form-select', 'placeholder': 'App'}),
            'time': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Hours : Minutes : Seconds  /  Hours : Minutes : 00(ZERO ZERO)'}),
                  }

models.py -

from django.db import models

class create_message(models.Model):
    message = models.TextField(blank=False, null=False)
    time = models.TimeField(blank=False, null=False)

    def __str__(self):
        return self.time

create_message.html

{% extends 'send/base.html' %}

{% block content %}
    {% if submitted %}
        Submitted
    {% else %}
        <form action="" method=POST>

            {% csrf_token %}

            {{ form.as_p }}

            <input type="submit" value="Submit" >
            
        </form>
    {% endif %}
        

{% endblock %}

I am just starting out so there might be a few mistakes... Thanks in advance for any help :)

CodePudding user response:

Quick clarification: are you attempting to make a GET request or POST request when you receive this error?

It seems that the create_message function only handles POST requests and isn't returning a response for GET requests

depending on your intended behaviour you can consider unindenting this statement:

        return render(request, 'send/create_message.html', {'form': form, 'submitted': submitted})

or adding another top level else if branch to handle the case for a GET request

You can see this question for a related example

  • Related