【问题标题】:Django passing data from one app to another?Django将数据从一个应用程序传递到另一个应用程序?
【发布时间】:2017-04-30 15:15:56
【问题描述】:

我使用django-allauth 进行身份验证。我有一个包含许多链接的仪表板。

user.html

`{% include 'sidebar.html' %}
 <h1>Profile View</h1>
 <p>{{ profile.username }}</p>`

change_password.html

`{% include 'sidebar.html' %}
 <h2>Change Password</h2>
 <p>{{ profile.username }}</p>`

sidebar.html

`<a href="{% url 'profile_view' slug=profile.username %}">Profile View</a>
 <a href="{% url 'change_password' %}">Change Password</a>`

views.py

class ProfileView(DetailView):
    template_name = "user.html"
    queryset = User.objects.all()
    context_object_name = 'profile'
    slug_field = "username"

更改密码视图来自 django-allauth。如何将ProfileView 中的用户名传递到更改密码视图,以便我可以显示在change_password.html 页面中。

主要问题 由于我在两个视图中都包含sidebar.html,因此它在ProfileView 中运行良好,但是当我导航到change_password 视图时,我收到以下错误

未找到带有关键字参数“{'slug': ''}' 的“profile_view”的反向操作。尝试了 1 种模式:['(?P[-\w.@+-]+)/$']

错误未显示在ProfileView 中,因为profile.username 返回一个值,但是当我导航到change_password 视图时,我收到上述错误,因为profile 上下文对象仅在该特定视图中传递。我想在整个项目中使用那个 context_object。

有简单的方法吗?除了构建 JSON API?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    我刚刚快速浏览了 allauth 应用程序提供的模板标签。我没有对此进行测试(我也没有使用该项目),但这看起来就像您正在寻找的那样。

    在您的模板中,任何模板...

    {% load account %} {# this should be near the top with any other load tags #}
    
    {# this can be anywhere in the template. I'm not positive what it returns but it looks like it is the username. #}
    <p>
        {% user_display user %}
    </p>
    

    我找到了答案here

    【讨论】:

    • 不!那不是我要找的……还有其他方法吗?可以从头开始写东西
    • 嘿@Rahul,我不确定 django-allauth 在做什么,但通常用户信息可通过{{ user }}{{ request.user }} 提供给每个视图。这些都行吗?如果没有,那么 django-allauth 正在对那里的中间件做一些事情。在这种情况下,您可以编写一个自定义模板标签来从 allauth 获取用户名。见这里:docs.djangoproject.com/en/1.11/howto/custom-template-tags
    • 如果您愿意,请告诉我。
    【解决方案2】:

    我搞定了,谢谢@teewuane

    sidebar.html

    &lt;a href="{% url 'profile_view' slug=profile.username %}"&gt;Profile View&lt;/a&gt;

    替换为

    &lt;a href="{% url 'profile_view' slug=request.user.username %}"&gt;Profile View&lt;/a&gt;

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多