Python DJANGO - 使用数据从 POST 重定向到不同的页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36578239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:03:19  来源:igfitidea点击:

DJANGO - Redirect to different page from POST with data

pythondjangoredirectpostrequest

提问by Jeeves

I am trying to have a simple form that once filled, will direct to a different webpage or remain on the same page if invalid. The page should have a text box and submit form and once a user enters anything it should direct you to a separate page.

我试图有一个简单的表格,一旦填写,将定向到不同的网页或如果无效则保留在同一页面上。该页面应该有一个文本框并提交表单,一旦用户输入任何内容,它就会将您定向到一个单独的页面。

My directory structure is as follows:

我的目录结构如下:

appName/
       app/
          forms.py
          urls.py
          views.py
          templates/
               app/
                 goodbye.html
                 name.html
                 library.html
                 thanks.html
       appName/
           settings.py
           urls.py

My app/urls.pyis as follows:

我的app/urls.py如下:

from django.conf.urls import url
from . import views

app_name = 'app'

urlpatterns = [
        url(r'^$', views.index2, name = 'index'),
        url(r'^hello/$', views.hello, name = 'hello'),
        url(r'^goodbye/$', views.goodbye, name = 'goodbye'),
        #url(r'^library$', views.library, name = 'library'),
        url(r'^library/$', views.library, name = 'library'),
        url(r'^library/(?P<book_id>[0-9]+)/$', views.book, name = 'book'),
        url(r'^getname/$', views.get_name, name = 'get_name'),
        url(r'^your-name/$',views.get_name, name='get_name'),
        url(r'^thanks/$',views.say_thanks,name='thanks'),
        #url(r'^thanks/(?P<name_id>[a-zA-Z]+)/$', views.say_thanks,name='thanks'),
        ]

My forms.pyis :

我的forms.py是:

from django import forms

从 Django 导入表单

class NameForm(forms.Form):
    your_name = forms.CharField(label = 'Your name', max_length=100)

My app/views.pyis:

我的应用程序/views.py是:

from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from django.http import HttpResponseRedirect

#forms
from .forms import NameForm

# Create your views here.
def index2(request):
    return HttpResponse("hello world")

def hello(request):
    text = """<h1>Welcome to my app! </h1>"""
    return HttpResponse(text)

def goodbye(request):
    template = loader.get_template("app/goodbye.html")
    context = {
        'output' : 'This is output from goodby views.py request handler'
        }

    return HttpResponse(template.render(context,request))

def library(request):
    template = loader.get_template("app/library.html")
    context = {
        'output' : 'Welcome to the libary!!'
        }
    return HttpResponse(template.render(context, request))

def book(request, book_id):
    return HttpResponse("You're looking at book %s. " % book_id)

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
            locationGo = "/thanks/"
            template = loader.get_template("app/thanks.html")

            return HttpResponse(template.render({'name':'name'},request))
    else:
            form = NameForm()
            template = loader.get_template("app/name.html")
            context = {'form': form}
            return HttpResponse(template.render(context, request))

def say_thanks(request):
    template = loader.get_template("app/thanks.html")
    return HttpResponse(template.render({'name': 'name'},request))

My templates include:

我的模板包括:

name.html:

名称.html

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

goodbye.html

再见.html

<h1>Goodbye to Template Romance</h1>

<a href="{% url 'app:index' %}">Go Back</a>

thanks.html

谢谢.html

Thanks {{name}}!

What I would likeis for:

我会的是:

  1. A user to visit to : website.com/getname/ to show the name.html file (which it does)

  2. If a user hits submit to stay on the same page (website.com/getname/) (which it doesn't - it gives: ValueError at /getname/ ->The view app.views.get_name didn't return an HttpResponse object. It returned None instead.

  3. If a user enters in the submit field, to be redirected to website.com/thanks/ (which it sort of does. It currently loads the thanks.html template, but the URL stays on website.com/getname/)

  1. 要访问的用户:website.com/getname/ 以显示 name.html 文件(它确实如此)

  2. 如果用户点击提交以保持在同一页面(website.com/getname/)(它没有 - 它给出: /getname/ 处的 ValueError ->视图 app.views.get_name 没有返回 HttpResponse 对象. 它返回 None 。

  3. 如果用户在提交字段中输入,则将被重定向到 website.com/thanks/(确实如此。它当前加载了Thanks.html 模板,但 URL 保留在 website.com/getname/ 上)

Inside the get_name(request): function, the POST and GET if...else doesn't seem to be firing based on the Submit button, and it doesn't seem to be loading the correct page, OR change the current URL address once it gets processed. I have tried using HttpRedirect() which works, however, I would also like to pass the forms data (which is another issue).

在 get_name(request): 函数中,POST 和 GET if...else 似乎没有根据 Submit 按钮触发,并且它似乎没有加载正确的页面,或者更改当前的 URL 地址一旦它被处理。我曾尝试使用 HttpRedirect() 工作,但是,我也想传递表单数据(这是另一个问题)。

Any suggestions would be a big help!

任何建议都会有很大帮助!

回答by Alasdair

Your first problem is that you are not returning a response when the request method is post and the form is invalid. You can fix that by changing the indentation of your view, so that you always return a response at the end of your view.

您的第一个问题是当请求方法为 post 并且表单无效时,您没有返回响应。您可以通过更改视图的缩进来解决该问题,以便始终在视图结束时返回响应。

def get_name(request):

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        ...
    else:
        form = NameForm()
    template = loader.get_template("app/name.html")
    context = {'form': form}
    return HttpResponse(template.render(context, request))

If you want to redirect to the /thanks/view, then you can use the redirect shortcut.

如果要重定向到/thanks/视图,则可以使用重定向快捷方式。

    if form.is_valid():
        return redirect('thanks')

Note that it isn't possible to redirect and pass the form data (see this questionfor an explanation). You should do any processing you want with the data beforeredirecting. You could use the messages frameworkto create a message 'Thanks <name>'before redirecting.

请注意,无法重定向和传递表单数据(有关解释,请参阅此问题)。重定向之前,您应该对数据进行任何您想要的处理。您可以使用消息框架'Thanks <name>'在重定向之前创建消息。

This works because you have name='thanks'in your url pattern.

这是有效的,因为您name='thanks'的网址模式中有。

You can simplify your views by using the rendershortcut. Instead of

您可以使用render快捷方式简化视图。代替

template = loader.get_template("app/name.html")
context = {'form': form}
return HttpResponse(template.render(context, request))

you can simply do:

你可以简单地做:

return render(request, "app/name.html", context)

Remember to add the imports for the shortcuts:

请记住为快捷方式添加导入:

from django.shortcuts import redirect, render