开发者

How to pass extra arguments to views function as a url in Django?

开发者 https://www.devze.com 2023-03-16 05:42 出处:网络
I have some data I\'d like to pass int开发者_StackOverflowo an html template using the render_to_response function.So generally I will do something like:

I have some data I'd like to pass int开发者_StackOverflowo 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))

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
)  

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.

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


Two options:

  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.

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

For example:

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号