Django 值错误"The view capstone.views.home didn't return an HttpResponse object. It returned None inst



我将用户放入表单中的数据保存到Django中的数据库中。当我提交表单时,值实际上会保存到数据库中。但我总是犯这个错误。不知道怎么修?

views.py

def home(request):
if request.method == "GET":
form_for_post = {'form': PostForm()}
return render(request, "capstone/home2.html", form_for_post)
else: 
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
city = form.cleaned_data['city']
place = Location.objects.create(username=request.user, city=city,)
place.save()
else:
return render(request, "capstone/home2.html")

型号.py

class User(AbstractUser):
pass
class Location(models.Model):
city = models.CharField(max_length=500) 
username = models.ForeignKey('User', on_delete=models.CASCADE, 
related_name='author', null=True, blank=True)

forms.py:

class PostForm(forms.Form):
city = forms.CharField(max_length=500)

html格式的表单:

<form method="POST">
{% csrf_token %}
<label for="city">City:</label><br>
<input type="text" id="city" name="city"><br>
<input type="submit" value="Submit">
</form> 

默认情况下,如果发出请求,它将是一个get请求,因此不需要添加if request.method == 'GET'所以你喜欢这个

def home(request):
form_for_post = {'form': PostForm()}
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
city = form.cleaned_data['city']
place = Location.objects.create(username=request.user, city=city,)
place.save()
return render(request,"your_page_after_form_successfully_submited")
return render(request, "capstone/home2.html",form_for_post)
def home(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
city = form.cleaned_data['city']
place = Location.objects.create(username=request.user, city=city,)
place.save()
else:
return render(request, "capstone/home2.html",form)
form_for_post = {'form': PostForm()}
return render(request, "capstone/home2.html", form_for_post)

试试这个

相关内容

最新更新