简体   繁体   English

在Django中将参数从template1传递到Template2

[英]Passing parameters from template1 to Template2 in Django

I'm developping a website with django, and i have a question about how my architecutre should be done, because i don't feel like i'm doing this the right way. 我正在用django开发一个网站,但我对应该如何进行建筑设计有疑问,因为我觉得我做的不正确。

I have an API in my Views.py that returns a JSON. 我的Views.py中有一个返回JSON的API。 and i have two templates which i use to request my Views.py ( with AJAX ). 我有两个模板,可用于请求Views.py(带有AJAX)。

While both works fine, what i want to do is to pass from template1 to template2 while saving the parameters used in template1 to use it in template2 虽然两者都工作正常,但我要从模板1传递到模板2,同时保存在模板1中使用的参数以在模板2中使用它

I have done a little drawing to explain a bit more what i'm doing 我做了一些绘图,以解释更多我在做什么 在此处输入图片说明

What i'm doing now and what i think is not good is that i do a redirect from template1 to template2 with the query string i want to use in template2 without passing from the server. 我现在在做什么,我认为不好的是,我使用要在template2中使用的查询字符串从template1重定向到template2,而没有从服务器传递过来。 Do you think i should use the session to save the parameters ? 您认为我应该使用会话来保存参数吗? what's the best way practice to do this ? 最佳实践做法是什么?

if that's not clear, what i want is to be able to share url of my template and then be able to initialize the composents of my template ( like Select and inputs) . 如果不清楚,我想要的是能够共享模板的url,然后能够初始化模板的组件(例如Select和input)。

If you want to share url between users it is rather not possible to use Sessions to keep those informations - users that are out of your session won't be able to get the information. 如果您要在用户之间共享url,则无法使用会话保留这些信息-不在会话中的用户将无法获取该信息。 In this case passing arguments by GET request (directly in url) is reasonable and not bad idea since data is visible to the end user finally - in inputs values. 在这种情况下,通过GET请求传递参数(直接在url中)是合理的,而且不是一个坏主意,因为最终用户最终可以看到数据-输入值中。

If you need to keep it in one session (so not to be able to send the URL to your friend just to use it in your context) why not to just pass the arguments as context parameters when rendering the template? 如果您需要将其保存在一个会话中(这样就不能将URL发送给您的朋友,而只是在您的上下文中使用它)为什么在渲染模板时不只是将参数作为上下文参数传递呢?

    #views.py
    return render(request, 'template2.html', {'args' : args})

    #template2.html
    {% for arg in args %}
    ...

If it is not possible (when you are not rendering the template form view that have access to data) the Session usage seems to be only way. 如果不可能(当您不呈现可访问数据的模板表单视图时),则使用Session似乎是唯一的方法。 Then you can consider to use Django messages frameswork rather than vanilla Sessions mechanism. 然后,您可以考虑使用Django消息框架,而不是普通的Sessions机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM