【问题标题】:ID Attribute Error Django Admin in Change Form更改表单中的 ID 属性错误 Django Admin
【发布时间】:2017-05-03 09:07:07
【问题描述】:

我想将 Nation 模型 ID 传递给 Django 管理员 change_form,以便在编辑时显示一两个按钮。我尝试将 id 传递给 render_change_form 函数并在模板中完成,但出现以下错误。

'NationAdmin' object has no attribute 'nation_id'

N:B 这在编辑时工作正常,但当我想通过 Django 管理仪表板添加新模型对象时会抛出此错误。

NationAdmin 下的方法

  #this method is to get the id
   def change_view(self, request, nation_id=None, form_url='', extra_context=None):
        self.nation_id = nation_id
        return self.changeform_view(request, nation_id, form_url, extra_context)

 #for form
 def render_change_form(self, request, context, *args, **kwargs):
        if self.nation_id: #django is telling me this line is causing error
             nation= self.get_object(request, self.nation_id)
             context.update({'nation':nation})
        return super(NationAdmin, self).render_change_form(request, context, *args, **kwargs)

Change_form.html

   {% if not nation.is_moderated and not nation.is_rejected %} 
      <a href="{% url 'activate_moderation' nation.id %}"> <input type="button" value="{% trans 'Approve' %}" name="_approvebutton" /></a>
  {% endif %}

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

    您可以使用original。无需设置nation_id

     def render_change_form(self, request, context, *args, **kwargs):
            if context.get('original'): #
                 obj = context['original']
                 #this will be the object you are trying to update
            return super(NationAdmin, self).render_change_form(request, context, *args, **kwargs)
    

    【讨论】:

    • 好吧.. 'original' 是从哪里来的?模型管理中的关键字?
    • 它是在 admin 中使用的关键字,它将是您要更改的对象。如果是添加新对象,它将是无。这就是为什么我提出 if 条件
    • 好吧,让我试试。谢谢!
    • 试过了。我的模板出现反向匹配错误。所以我把它改成这样: def render_change_form(self, request, obj, context, *args, **kwargs): if context.get('original'): obj=context['original'] return super(NationAdmin, self ).render_change_form(request, obj, context, *args, **kwargs) 并且得到了 TypeError: render_change_form() got multiple values for keyword argument 'obj' 你认为缺少什么?
    • 它不依赖于上述答案。它将是 "{% url 'activate_moderation' nation.id %}" 。你需要解决这个问题
    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 2012-07-08
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2020-05-13
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多