在django ModelForm CharField之后如何添加“Star *”? [英] How add a 'Star *' after a django ModelForm CharField?

查看:133
本文介绍了在django ModelForm CharField之后如何添加“Star *”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的django ModelForm中有一些必要的字段。如何在必填字段之后添加一个红星(*)?

解决方案

我要假设你想要自动发生,所以这里有几种不同的方法之一:

  {%for form in form%} 
< label for ={{field.auto_id}}> {{field.label_tag}}
{%if field.field.required%}
< span class =required> * < /跨度>
{%endif%}
< / label>
{%endfor%}

然后您可以使用CSS为星号设置风格。



或者,如果需要,可以使用CSS添加星号:

  < style type =text / css> 
span.required:after {content:'*'; }
< / style>
{%表单中的字段%}
< label for ={{field.auto_id}}>
{%if field.field.required%}
< span class =required> {{field.label_tag}}< / span>
{%else%}
{{field.label_tag}}
{%endif%}
< / label>
{%endfor%}

如果你想做,这可能是一个更好的选择但是,如果您不会单独访问这些字段(例如使用{{form.as_p}})),那么你可以使用所需的字段来执行其他操作。



可以向ModelForm添加一个属性:

  class FooForm(forms.ModelForm):
required_css_class ='required'

这将定义所需的所有字段具有必需类(因此,您可以使用上面提到的CSS代码添加了一个星号(或者你想要做的任何事情)。


i have some necessary fields in my django ModelForm. How can i add a red star (*) after the required fields ?

解决方案

I'm going to assume you want this to happen automatically, so here's one of a few different ways:

{% for field in form %}
    <label for="{{ field.auto_id }}">{{ field.label_tag }}
    {% if field.field.required %}
        <span class="required">*</span>
    {% endif %}
    </label>
{% endfor %}

Then you can style the asterisk using CSS.

Or, you can add the asterisk using CSS instead if you want:

<style type="text/css">
    span.required:after { content: '*'; }
</style>
{% for field in form %}
    <label for="{{ field.auto_id }}">
    {% if field.field.required %}
        <span class="required">{{ field.label_tag }}</span>
    {% else %}
        {{ field.label_tag }}
    {% endif %}
    </label>
{% endfor %}

This one is probably a better option if you want to do other things with the required field as well.

However, if you will not be accessing the fields individually (such as using {{ form.as_p }}), then you can add a property to your ModelForm:

class FooForm(forms.ModelForm):
    required_css_class = 'required'

That will define all fields that are required as having the 'required' class (and thus, you can use the CSS code I mentioned above to add an asterisk (or whatever else you want to do with it).

这篇关于在django ModelForm CharField之后如何添加“Star *”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆