如何 return HttpResponse 对象而不是 None

How to return an HttpResponse object instead of None

你能帮我解决这个问题吗?我是一个初学者,正在尝试学习 django..即使我尝试了很多其他方法,但还是行不通。我希望你能帮助我

models.py

from django.db import models
from django.db.models.fields import CharField , IntegerField, EmailField


class Member(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=50) 
    email = models.EmailField()
    age = models.IntegerField()
    password =  models.CharField(max_length=100,null=True)


    def __str__(self):
        return self.first_name + " " + self.last_name

form.py

from django.db.models import fields
from django.forms import ModelForm
from django import forms
from .models import Member



class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = ["first_name", "last_name", "age", "email", "password"]

views.py

from django.shortcuts import  render
from .models import Member
from .form import MemberForm
# Create your views here.




def join(request):
    if request.method == "POST":
        form = MemberForm(request.POST or None)
        if form.is_valid():
            form.save()
            return render(request, "HTML/join.html",{})

    else:
        form = MemberForm()
        return render(request, "HTML/join.html",{})

错误

The view myapp.views.join didn't return an HttpResponse object. It returned None instead.

如果表格无效,您的观点必须return回复:

def join(request):
    if request.method == "POST":
        form = MemberForm(data=request.POST)
        if form.is_valid():
            form.save()
            return render(request, "HTML/join.html",{})
        else:
            return HttpResponse(status=400) # Replace with what makes sense to you
    else:
        form = MemberForm()
        return render(request, "HTML/base.html", {})

在你的网址中写下类似:

urlpatterns = [
    path('', join)
]

另请注意,您应该在 rendercontext 参数中传递表单,例如:render(request, "HTML/base.html", {'form': form}).

https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/ 正如您在文档中看到的那样,渲染函数的第三个参数是上下文。您将参数作为 {} 传递,空白字典。 你必须做这样的事情。

from django.shortcuts import  render
from .models import Member
from .form import MemberForm
# Create your views here.




def join(request):
    if request.method == "POST":
        form = MemberForm(request.POST or None)
        if form.is_valid():
            form.save()
            return render(request, "HTML/join.html",{})

    else:
        form = MemberForm()
        return render(request, "HTML/base.html",{'form':form})

在您的模板中

<form  method="post">
     {% csrf_token %}
     {{ form }}
     <input type="submit" value="Submit">
</form>