在Django中如何传递额外的参数作为url? [英] How to pass extra arguments to views function as a url in Django?

查看:151
本文介绍了在Django中如何传递额外的参数作为url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我想使用render_to_response函数传入html模板的数据。所以通常我会做一些像:

I have some data I'd like to pass into an html template using the render_to_response function. So generally I will do something like:

return render_to_response('template.html', {'arg1':arg1,'arg2': arg2}, context_instance=RequestContext(request))

然而,我想创建一个链接导致这个页面,而不是直接去它。参数是用于生成图形的数据列表,不是像年份或数字或单个单词那样小,所以我不希望它们以URL的形式显示在URL中:

However, I want to create a link that leads to this page instead of just going directly to it. The arguments are lists of data used for generating graphs, not small like years or numbers or single words, so I don't want them to be displayed in the URL in the name pattern like this:

urlpatterns = patterns('',
    url(r'^archive/(\d{4})/$', archive
)  

有没有办法可以将额外的参数传递给views函数并生成一个url链接没有在url中显示额外的参数?

Is there a way I can pass in the extra arguments to the views function and generate a url link without displaying the extra arguments in the url?

我已经知道你可以传递这样的额外的参数

I already know that you can pass in extra arguments like this

urlpatterns = patterns('blog.views',
    (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
)

但这不是我想要什么,因为我不想要参数硬编码 - 他们不保持不变,是其他代码生成的数据。

But that is not what I want since I don't want the arguments hardcoded- they do not stay constant and is data generated by other code.

总结:
我怎么能创建一个render_to_response的链接但是只有在你点击它之后?

Summary: How can I create a link that does render_to_response but only after you click it?

推荐答案

两个选项:

如果您不希望URL中的任何数据,您可以发送POST请求并使用 request.POST 访问它, a href =https://docs.djangoproject.com/en/dev/ref/request-response/ =nofollow>相关文档 POST请求的缺点是浏览器将发出警告您刷新页面,很难链接到。

  1. If you don't want any data in the URL you can send a POST request and access it using request.POST, see the relevant docs. The downside of POST requests is that the browser will warn you on refreshing the page, and it's difficult to link to.

更好的方法是创建一个包含所有需要的数据的模型。 / p>

A better approach would be to create a model that holds all of the data you need.

例如:

class Data(models.Model):
    data1 = models.IntegerField()
    data2 = models.IntegerField()
    data3 = models.IntegerField()

然后有一个视图可以接收POST请求中的所有数据,并生成一个看起来像 /数据视图/ 1 。这样一来,您可以使用一个网址来获取您的数据模型中的数据,但没有URL中的数据编码。

Then have one view that takes all of the data from a POST request, and generates a URL that looks like /dataview/1. That way you have a URL that can be used to get the data from your Data model, but doesn't have the data encoded in the URL.

这篇关于在Django中如何传递额外的参数作为url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆