简体   繁体   English

如何在Django的ModelForm中为模板设置自定义属性?

[英]How to set a custom attribute to a model which can be used in the template with ModelForm in Django?

Is it possible to write some attributes to a model field which can be used later to differentiate the different fields in the template? 是否可以将某些属性写入模型字段,以便稍后用于区分模板中的不同字段?

model.py 模型

from django.db import models

class Person(models.Model):
    first_name = models.CharField("i am the Label", max_length=30)
    last_name = models.CharField("i am other Label", max_length=30, customattr="Custom")

forms.py 表格

class PersonForm(ModelForm):
    class Meta:
        Person

template.html template.html

<form action="" method="post">{% csrf_token %}
     {% for field in form %}
         {% ifequal field.customattr 'Custom' %} # HOW COULD THIS WORK?
            <p>Hello world.</p>
            {{ field }}
         {% else %}
            <p>This is not Custom</p>
            {{ field }}
         {% endifequal %}
     {% endfor %}
 <input type="submit" value="Submit" />
 </form>

Any hints? 有什么提示吗?

Not really possible; 不太可能; field in your template code is a form field, not a model field. field在你的模板代码是一个表单域,而不是一个模型字段。 I would shift the presentation logic from the model into the template, and do something like this: 我将表示逻辑从模型转移到模板,并执行以下操作:

<form action="" method="post">{% csrf_token %}
     {% for field in form %}
         {% if field.name == 'last_name' or field.name == 'another_field' %}
            <p>Hello world.</p>
            {{ field }}
         {% else %}
            <p>This is not Custom</p>
            {{ field }}
         {% endif %}
     {% endfor %}
 <input type="submit" value="Submit" />
 </form>

(the == operator was added in Django 1.2) (在Django 1.2中添加了==运算符

I don't understand why yo would like to do this. 我不明白您为什么要这样做。 If you would like to define custom html to your ModelForm field you can override it like this: 如果您想在ModelForm字段中定义自定义html,则可以这样重写它:

class PersonForm(ModelForm):
    class Meta:
        Person
    first_name = forms.CharField(
        required = True,
        widget   = forms.TextInput(attrs={'style':'width:100px;'},
    )

Like this you can tell Django how you would like to render your html. 这样,您可以告诉Django您希望如何呈现html。 You can find more detail in the doc https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets 您可以在文档https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets中找到更多详细信息

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

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