Django形式:按下提交按钮时会发生什么

时间:2016-06-21 23:27:32

标签: python django

我目前正在处理Django的文档,我不完全理解在表单中按下提交按钮时会发生什么。

https://docs.djangoproject.com/en/1.9/topics/forms/

在各种示例中,目标URL似乎由HRML文件确定,并且在此示例中,提交按钮将转发到/ your-name /:

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

我觉得令人困惑的是,在视图中同时会使用HttpResponseRedirect转发到/ thanks /。两者都是必要的,它们有不同的用途吗?是不是有办法从视图而不是html文件处理所有内容?

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

0 个答案:

没有答案
相关问题