【问题标题】:Django URL/Views extra parametersDjango URL/Views 额外参数
【发布时间】:2013-11-22 22:35:31
【问题描述】:

在 Django1.6 中,有没有办法在不解析 URL 的情况下将动态参数传递给我的视图或 URL?

理想情况下,我想要一个看起来像这样的 urls.py:

url(r'^dash/$',
    dash_view.account_modify,
    {'account': **dynamic_account_identifier_here**}
    name='dash_account_modiy')

在views.py中:

def account_modify(request, account, 
                   template_name='profile.html, 
                   change_form=AccountModifyForm):
    ...

:参数帐户:
来自模型:

class Dash(models.Model):
    name = models.Charfield()
    account = models.IntegerField()
    ....

基本上,我真的很想避免将帐户标识符作为字符串一部分的 urls.py,例如:

url(r'^dash/(?P<account>\w+)/$',
    dash_view.account_modify,
    name='dash_account_modiy')

关于如何将这些值从模板传递到处理视图以在 AccountModifyForm 中使用的任何建议(需要“帐户”参数)?

【问题讨论】:

    标签: django django-views django-urls


    【解决方案1】:
    url(r'^dash/$',
        dash_view.account_modify,
        {'account': **dynamic_account_identifier_here**}
        name='dash_account_modify')
    

    你不能在那里动态评估任何东西,因为字典只评估一次,当 URL conf 加载时。

    如果您想将信息从一个视图传递到另一个视图,您的三个选项是:

    • 在 URL 中,您似乎不想这样做
    • 作为 GET 或 POST 数据
    • 将其存储在一个视图中的会话中,并从下一个视图中的会话中检索它

    【讨论】:

    • 是的......刚刚想通了......仍然感谢您的指针。有一点时间。
    • 很高兴你明白了:)
    【解决方案2】:

    如果有人关心...想通了...

    在模板中:

    {% for dash in dashes %}
         blah blah blah
         <form action="..." method="POST">
             <input type="hidden" name="id" value="{{ dash.account }}">
             {{ form.as_ul }}
             <input type="submit" value="Do stuff">
         </form>
    {% endfor %}
    

    在视图中:

    if request.method == 'POST'
        account = request.POST['id']
        # be sure to include checks for the validity of the POST information
        # e.g. confirm that the account does indeed belong to whats-his-face
        form = AccountModifyForm(request.POST, account,
                                 user=request.user)
        ....
    

    【讨论】:

    • 请注意,用户可以修改隐藏字段的值并编辑任何帐户,这在某些情况下可能是一个安全问题。
    猜你喜欢
    • 2019-05-19
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多