【问题标题】:Django - add text beetween modelform fieldsDjango - 在模型表单字段之间添加文本
【发布时间】:2017-07-30 04:41:11
【问题描述】:

如何在表单字段之间添加一些 html 文本?这是我的forms.py:

class SiteAddFormFull(forms.ModelForm):

    url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    class Meta:
        model = Site
        fields = ('url', 'name', 'description', 'keywords', 'group', 'category',
              'subcategory', 'category1', 'subcategory1', 'email')

    def clean(self):
        cleaned_data = super().clean()
        subcategory = cleaned_data['subcategory']
        subcategory1 = cleaned_data['subcategory1']
        if subcategory1 and (subcategory == subcategory1):
            raise forms.ValidationError("Subcategories can't be the same.")

我的html文件的一部分:

<form method="post" action="" class="form-horizontal">
    {% csrf_token %}
    {% bootstrap_form form_extended layout='horizontal'%}
    {% bootstrap_button "Zatwierdź" size='large' button_type="submit" button_class="btn-primary" %}
</form>

我想在“组”字段后添加描述。比如:

  • 您可以将网站添加到 2 个类别
  • 您可以将网站添加到 2 个子类别

只是普通的 html 文本。我怎样才能做到这一点?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    如果您想添加自定义 HTML 标签,请执行以下操作:

    class Meta:
        model = Site
        fields = ('url', 'name', 'description', 'keywords', 'group', 'category', 'subcategory', 'category1', 'subcategory1', 'email')
        help_texts = {
            'field_name': '<span class="my-class">Some useful help text.</span>',
        }
    

    更多关于here

    【讨论】:

      【解决方案2】:

      您可以在模型的组字段中添加help_text 属性:

      class Site(models.Model):
          group = models.<FieldType>(..., help_text="You can add site to 2 categories")
      

      【讨论】:

      • 是否可以格式化(添加html标签)到help_text?
      • 如果你将它们包装在mark_safe() 中是可能的。不过我没试过。
      【解决方案3】:

      好的。我是这样做的:

      group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'),
                                                       ('premium', 'premium')), default='podstawowy',
                               help_text="<div id='group'><ul><li>You can add site to 2 <b>categories</b></li></ul></div>")
      

      这里还有一个问题。如果会有3、4、5行html代码,这里我的代码就会乱七八糟。我应该怎么写?是否可以从外部文件中包含一些 html 文本。也许还有其他解决方案?

      【讨论】:

      • 从我的角度来看,如果它只是 3 或 4 或 5 行代码并且不会在其他地方重用,那么没有必要将它们写在单独的模块中。只需像您一样将它们写在help_text 中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 2011-06-11
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多