我读到,在成功处理 post 数据后,您应该使用 HttpResponseRedirect 重定向到另一个页面。我正在构建一个用于学习目的的 URL 缩短器,views.py 中的代码如下所示:(不工作)
def makeurl(request):
# get url from form
post_url = request.POST['url']
# shorten the url and have the short code returned
shortened_url = shorten_url(post_url)
return HttpResponseRedirect('create')
def create(request):
return render(request, 'shorturl/create.html',
{'shortened_url': shortened_url})
当我提交表单以缩短输入 URL 时,将调用“makeurl”,计算并返回缩短的 URL (shortened_utl)。然后我调用“创建”,这将呈现需要向用户显示“shortened_url”的页面。
问题是,如果我要使用 HttpResponseRedirect,我无法将“shortened_url”变量传递到要呈现的“创建” View 。任何人都可以建议我吗?我是 django 的新手,干杯
最佳答案
您至少可以通过三种方式使用重定向轻松传递参数:
- 作为命名参数段
- 作为查询字符串参数
- 作为 session 变量
假设您的“创建” View 采用名为“shortened_url”的参数。使用方法 1 的 URL 如下所示:
# urls.py
url(r'create/(?P<shortened_url>.)/$', create, name='create',)
# views.py
def create(request, shortened_url):
# do whatever
在您处理表单帖子的 View 中,您将执行以下操作:
from django.core.urlresolvers import reverse
def makeurl(request):
. . .
return HttpResponseRedirect(reverse('create', args=(),
kwargs={'shortened_url': shortened_url}))
如果是方法 2,则根本不需要 url 模式中的命名参数,而是只需反转 url 模式并添加查询字符串参数即可:
def makeurl(request):
. . .
url = reverse('create')
url += '?shortened_url={}' + shortened_url
return HttpResponseRedirect(url)
如果是方法 3,则不需要命名参数或查询字符串值:
def makeurl(request):
. . .
request.session['shortened_url'] = shortened_url
return HttpResponseRedirect(reverse('create'))
def create(request):
shortened_url = request.session.get('shortened_url')
. . .
# delete the session value
try:
del session['shortened_url']
except KeyError:
pass
# do whatever
关于python - Django - 无法在 HttpResponseRedirect 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26197545/