【问题标题】:Django access field's value dynamically by keyword argument to pass to templateDjango 通过关键字参数动态访问字段的值以传递给模板
【发布时间】:2011-06-30 12:48:41
【问题描述】:

我想为模型中的单个字段创建一个编辑表单,其中 textarea 预填充了该字段的当前值。但是,确切的字段名称不是硬连线的,我希望它由 url 指定。

我的模型称为主题。两个示例字段是备注和目标。我可以硬连线字段值,如下所示:

urls.py

(r'^/(?P<topicshortname>\d+)/(?P<whichcolumn>[^/]+)/edit/$', 'mysyte.myapp.views.edit_topic_text'),

views.py

def edit_topic_text(topicshortname, whichcolumn):
    thetopic = Topic.objects.get(topic__shortname__iexact = topicshortname)
    content =  Topic.objects.get(topic__shortname__iexact = topicshortname).objective
    return render_to_response('topic_text_edit.html', locals())

topic_text_edit.html

<form method="post" action="../save/">
    <textarea name="content" rows="20" cols="60">{{ content }}</textarea>
    <br>
    <input type="submit" value="Save"/>
</form>

我也可以使用{{ thetopic.objective }} 在模板中进行硬连线,但如果我访问http://mysite.com/topic/Notes/edit/,这两者都会在表单中预先填充目标值,而不是注释值。

我可以使用 'whichcolumn' url 参数来指定对象中要更新的字段吗?

【问题讨论】:

    标签: django django-views field


    【解决方案1】:

    您可以使用getattr 按名称获取属性的值。以您为例:

    def edit_topic_text(topicshortname, whichcolumn):
        thetopic = Topic.objects.get(topic__shortname__iexact = topicshortname)
        content =  getattr(thetopic, whichcolumn)
        return render_to_response('topic_text_edit.html', locals())
    

    但是,您还应该了解此操作的安全隐患。用户将能够通过更改 url 来编辑他们喜欢的模型上的任何字段。 您应该在对该数据执行任何其他操作之前检查 whichcolumn 的值,或者使用更具体的正则表达式限制 urlconf 中的可能性,例如:

    (r'^/(?P<topicshortname>\d+)/(?P<whichcolumn>(Notes|Objectives))/edit/$', 'mysyte.myapp.views.edit_topic_text'),
    

    您还提到了“Notes”和“Objectives”字段,但正在访问“objective”字段,因此您可能需要将whichcolumn的值映射到您感兴趣的字段名称,例如:

    (r'^/(?P<topicshortname>\d+)/Objectives/edit/$', 'mysyte.myapp.views.edit_topic_text', {'whichcolumn': 'objective'}),
    (r'^/(?P<topicshortname>\d+)/Notes/edit/$', 'mysyte.myapp.views.edit_topic_text', {'whichcolumn': 'note'}),
    

    您应该注意的另一件事是,您通过两次调用 Topic.objects.get(...) 来访问数据库两次。你应该重用主题的价值。

    【讨论】:

    • 这对于预填充文本区域非常有效。谢谢你。我已经阅读并试图捏造 getattr(),但没有制定出正确的语法。不幸的是,我的保存 url 仍然不起作用 - 我正在努力将 getattr() 放入保存函数中,因为它仍然被硬连线为 thetopic.objective = content。感谢您的安全建议,我会实施的。评论还提到了两次访问数据库,谢谢。 “目标”(复数)是我帖子中的错字。
    • 更新:通过setattr(object, field, value) 完成,感谢stackoverflow.com/questions/763558/django-object-get-set-field
    【解决方案2】:

    你应该把Notes和Objectives这两个概念分别放在两个不同的类中,然后在你的Topic主类中作为参考使用

    检索对象类型并填充正确的对象类型会更容易

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 2016-09-03
      • 2011-08-08
      • 1970-01-01
      • 2011-06-17
      • 2020-12-22
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多