【问题标题】:Styling forms and django form values样式化表单和 django 表单值
【发布时间】:2010-10-12 04:02:26
【问题描述】:

我正在尝试使用 CSS 设置表单样式。首先,除了官方文档之外,我还没有看到完整的示例,因此我将不胜感激任何博客条目或文章。

现在在我的表单上,一个典型的 Charfield 被翻译成这样的 html:

<input type="text" name="artists" id="id_artists" />

如果我的表单在某些字段上包含错误,则之前的 Charfield 会记住该值并继续:

<input type="text" name="artists" value="Pink Floyd" id="id_artists"  />

如何在 django 表单中获取此值 (value="Pink Floyd")?假设我的字段是{{form.artists}},我可以使用{{form.artists}} 作为字段,{{form.artists.label}} 作为标签,{{form.artists.errors}}{{form.artists.help_text}},但是这个值呢?

提前致谢!

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    专门创建输入字段,而不是依赖 django 自动创建。

    类似:

    <input type="text" name="artists" id="id_artists" value="{{form.artists.title}}" />
    

    应该工作

    【讨论】:

    • 嗨,Steerpike,这可以完成这项工作,但是我仍然需要获取该值,以便在表单上的其他字段出现错误时提供它 - 否则它会被空白。跨度>
    【解决方案2】:

    您可以从data 属性中获取该字段的当前值:

    {{ form.artists.data }}
    

    我看不到提到这一点的 Django 文档,但它确实有效...

    【讨论】:

      【解决方案3】:

      您还可以向表单类添加额外的验证来处理表单数据。来自djangobook.com

      from django import forms
      
      class ContactForm(forms.Form):
          subject = forms.CharField(max_length=100)
          email = forms.EmailField(required=False)
          message = forms.CharField(widget=forms.Textarea)
      
          def clean_message(self):
              message = self.cleaned_data['message']
              num_words = len(message.split())
              if num_words < 4:
                  raise forms.ValidationError("Not enough words!")
              return message
      

      clean_message 方法中,您可以使用self.cleaned_data 字典访问给定字段。该字典可用于任何经过验证的表格。

      请务必返回字段,在本例中为 message,否则返回 None

      【讨论】:

        猜你喜欢
        • 2020-11-28
        • 2018-09-03
        • 2014-08-26
        • 2012-06-24
        • 2020-02-17
        • 2011-08-15
        • 2016-03-25
        • 2023-04-10
        • 2011-05-05
        相关资源
        最近更新 更多