问题
Please, I am a newbie, if I didn't ask my question well, let me know.
I am working on a To-Do List app.
Anytime, I add a new task and time to the form on my web app and submit, I get the following error:
ValueError at / The view To_do_list_app.views.home didn't return an HttpResponse object. It returned None instead.
Below is my views.py file
from django.http import HttpResponse
from django.shortcuts import render,redirect
from .forms import ListForm
from .models import List
def home(request):
if request.method == "POST":
form = ListForm(request.POST or None )
if form.is_valid():
form.save()
act = List.objects.all
context = {
"act":act
}
return render(request,"home.html",context)
else:
act = List.objects.all
context = {
"act":act
}
return render(request,"home.html",context)
Here is also my forms.py file
from django import forms
from .models import List
class ListForm(forms.ModelForm):
class Meta:
model = List
fields = "__all__"
here is my models.py file
from django.db import models
class List(models.Model):
activity = models.CharField(max_length=200,primary_key=True)
completed = models.BooleanField(default=False)
time = models.DateTimeField()
def __str__(self):
return self.activity
This is the home.html script(only the form html tag)
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input class="form-control mr-sm-2" type="text" placeholder="Add New
Task" name="activity">
<input type = "datetime-local" name = "time" >
<button class = "btn btn-primary my-2 my-sm-0" type="submit">Add New Task</button>
</form>
回答1:
I've fully integrated your code to my environment, carefully went trough your code and tested a few things. If you change the code of your views.py to the following, I think it will fix your problem:
from django.shortcuts import render
from .forms import ListForm
from .models import List
def index(request):
act = ''
if request.method == "POST":
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
act = List.objects.all
return render(request, 'myApp/home.html', {"act": act})
else:
act = List.objects.all
return render(request, 'myApp/home.html', {"act": act})
resume: ( You had to make a global variable in the index-method ( or home method ) and set it to an empty string. Also you don't really need to use the context variable, you also can do it in the inline way, it will cost you less code. And last but not least you had to outdent the last return one time because that is the real return of the method. Otherwise the method only gives an if-structure with a return.. )
来源:https://stackoverflow.com/questions/53632129/django-valueerror-at-the-view-to-do-list-app-views-home-didnt-return-an-http