Django input_formats删除help_text?我只想改变DateField的显示方式 [英] Django input_formats removes help_text? I want only to change the way one DateField is displayed

查看:123
本文介绍了Django input_formats删除help_text?我只想改变DateField的显示方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,在我的 AbonnentForm上设置 input_formats (ModelForm) forms.py 中,模型的 help_text 不会显示在HTML中

My problem is that when setting an input_formats on my AbonnentForm(ModelForm) in forms.py, the model's help_text is not displayed in the HTML form.

我只想改变DateField的显示方式。

I want only to change the way one DateField is displayed.

我做错了什么?

这是我的models.py(缩写)
from django.db import模型

This is my models.py (shortened) from django.db import models

def get_letzte_ausgabe_default():
    return date(date.today().year, 12, 1) if date.today() > date(2017, 12, 26) else date(date.today().year + 1, 12, 1)

class Abonnent(models.Model):
    erste_ausgabe = models.DateField(default=get_letzte_ausgabe_default(),
                                     verbose_name="Erste Ausgabe",
                                     help_text="Eingabe im Format MM/JJJJ. Zum Beispiel: 01/2018)

这是我的forms.py(完整)

This is my forms.py (complete)

from django.forms import ModelForm, DateField, DateInput
from .models import Abonnent


class AbonnentForm(ModelForm):
    # WHEN I ADD THE FOLLOWING LINE, THE HELP_TEXT IS NOT DISPLAYED UNDER THE HTML-FORM
    erste_ausgabe = DateField(input_formats=['%m %Y'],
                              widget=DateInput(format='%m %Y'))
    class Meta:
        model = Abonnent
        fields = '__all__'

这是我的模板(缩写)

<div class="col-sm {% if form.letzte_ausgabe.errors %} has-danger {% endif %}">
  <label class="col-form-label" for="{{ form.letzte_ausgabe.id_for_label }}">{{ form.letzte_ausgabe.label }}</label>
  <input id="{{ form.letzte_ausgabe.id_for_label }}" class="form-control" type="text" value="{{ form.letzte_ausgabe.value }}" name="{{ form.letzte_ausgabe.html_name }}" placeholder="MM/JJJJ" aria-describedby="{{ form.letzte_ausgabe.id_for_label }}Help">
  {% if form.letzte_ausgabe.help_text %}<small id="{{ form.letzte_ausgabe.id_for_label }}Help" class="form-text text-muted">{{ form.letzte_ausgabe.help_text }}</small>{% endif %}
</div>


推荐答案

您可以尝试更改 __ init __ 方法中的input_formats 小部件

You could try changing the input_formats and widget inside the __init__ method.

class AbonnentForm(ModelForm):
    # ...

    def __init__(self, *args, **kwargs):
        super(AbonnentForm, self).__init__(*args, **kwargs)
        self.fields['erste_ausgabe'].input_formats=['%m %Y']
        self.fields['erste_ausgabe'].widget=DateInput(format='%m %Y')

必须在Nik的答案中复制模型中的 help_text

This avoids having to duplicate the help_text in the model form as in Nik's answer.

这篇关于Django input_formats删除help_text?我只想改变DateField的显示方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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