How to differentiate an HTTP Request submitted from a HTML form and a HTTP Request submitted from a client in django?

匆匆过客 提交于 2019-12-11 17:28:59

问题


I have a model in django that is as below:

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

I have a form as below:

class StudentForm(ModelForm):

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

my template is as below:

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

I have a view as below:

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}) 

The problem with this method is that if sb submits the form without filling the nationality field, the result would be 'get from client request' that is wrong because the validation error should happen because the request is from submitting a form not direct client get request. What I can do is that I add a hidden field to my form as below:

<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>

and change my view as below:

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})

However, there should be another method to do this. There should be something in HTTP to tell us the request is fresh get request from client or it is from form submission. I am looking for this.


回答1:


request.GET is a dictionary. request.GET.get('nationality') is falsy if the dictionary doesn't have the key 'nationality' but also if its value is the empty string (?nationality=). So you should just check the presence of the key, that way you know the form was submitted:

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


来源:https://stackoverflow.com/questions/58091630/how-to-differentiate-an-http-request-submitted-from-a-html-form-and-a-http-reque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!