如何在django中区分从HTML表单提交的HTTP请求和从客户端提交的HTTP请求?

时间:2019-09-25 05:22:12

标签: django forms http get request

我在Django中有一个模型,如下所示:

class Student(Model):
    nationality = CharField(max_length=200)

我的表格如下:

class StudentForm(ModelForm):

    class Meta:
        model = Student
        fields = ('nationality', )

我的模板如下:

<form method="GET" novalidate id="my_form">
      {{ student_form.as_p }}
</form>
<button type="submit" form="my_form" name="my_form">Submit</button>

我的看法如下:

def home(request):
    if request.POST:
        return HttpResponse('This should never happen')
    else:
        if request.GET.get('nationality'):
            student_form = StudentForm(request.GET)
            if student_form.is_valid():
                return HttpResponse('get from form submission')
        else:
            student_form = StudentForm()
            print('get from client request')
            return render(request, my_template, {'student_form': student_form}) 

此方法的问题在于,如果sb提交表单时未填写国籍字段,结果将是“从客户请求中获取”,这是错误的,因为验证错误应该发生,因为该请求是由于提交的表单不直接客户得到请求。 我可以做的是向表单中添加一个隐藏字段,如下所示:

<form method="GET" novalidate id="my_form">
      {{ student_form.as_p }}
      <input type="hidden" id="hidden" name="hidden" value="hidden">
</form>
<button type="submit" form="my_form" name="my_form">Submit</button>

并按如下所示更改我的看法:

def home(request):
    if request.POST:
        return HttpResponse('This should never happen')
    else:
        if request.GET.get('hidden'):
            student_form = StudentForm(request.GET)
            if student_form.is_valid():
                return HttpResponse('get from form submission')
        else:
            student_form = StudentForm()
            print('get from client request')
            return render(request, my_template, {'student_form': student_form})

但是,应该有另一种方法可以做到这一点。 HTTP中应该有一些内容可以告诉我们请求是来自客户端的新请求,还是来自表单提交的请求。我正在寻找这个。

1 个答案:

答案 0 :(得分:0)

request.GET是字典。如果字典没有键request.GET.get('nationality'),但是字典的值是空字符串('nationality'),则?nationality=是虚假的。因此,您应该只检查密钥的存在,那样您就知道表单已提交:

if 'nationality' in request.GET:
    # initialise form with `request.GET`
else:
    # initial unbound form