【问题标题】:Making a custom template for CreateView and UpdateView with placeholders and error validation使用占位符和错误验证为 CreateView 和 UpdateView 制作自定义模板
【发布时间】:2022-01-14 05:10:53
【问题描述】:

我在学习 Django 时正在制作一个通用博客。

我有一个ArticleCreateViewArticleUpdateView,我正在尝试制作一个两个视图都可以共享的自定义模板。 据我了解,CreateViewUpdateView 默认使用相同的模板 (article_form.html),这是我正在尝试修改的模板。

我的 models.py 中有以下内容:

class Article(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    # def __str__ ...
    # def get_absolute_url ...

在我看来.py:

class ArticleCreateView(CreateView):
    model = Article
    fields = ['title', 'body']      
    template_name = 'article_form.html'


class ArticleCreateView(CreateView):
    model = Article
    fields = ['title', 'body']
    template_name = 'article_form.html'

在我的模板 article_form.html 中包含以下内容:

<form method='post'>
  {{ form.as_p }}
  <button>
    Publish
  </button>
</form>

我想让它更花哨,加上大量的 CSS,一个简化的版本是:

<form method='post'>
  {% csrf_token %}
  <fieldset class="fieldset-class">
    {{ form.title.errors }}
    <input
      class="form-class"
      type="text"
      placeholder="Article Title"
      name="{{ form.title.name }}"
      value="{{ form.title.value }}"
    />
  </fieldset>
  <fieldset class="form-group">
    {{ form.body.errors }}
    <textarea
      class="form-control"
      rows="8"
      placeholder="Article Body"
      name="{{ form.body.name }}"
    >{{ form.body.value }}</textarea>
  </fieldset>
</form>

我想要的是一个表格:

  • 在空字段中有占位符(而不是标签)
  • 具有基于模型的错误验证(max_length 受到尊重,两个字段均为 required,无需我指定)
  • 提交时不会删除输入的值

上面的 html 做了以下事情:

  • 使用空字段提交会引发错误,并且任何输入的值都将被保留(好)
  • 空字段有 None 而不是占位符(问题)

将上述 html 中的 object.titleobject.body 替换为 form.title.valueform.body.value 执行以下操作:

  • 使用空字段提交会引发错误,但也会删除输入的值(问题)
  • 空字段有正确的占位符(好)

我已阅读文档的 Built-in template tags and filtersRendering fields manuallyRendering form error messagesLooping over the form’s fieldsAttributes of BoundField,在 SO 和 GitHub 上查找了类似的代码,阅读了 {{ form.as_p }} 呈现的源代码,但我发现尽管有一个所谓的常见用例,但没有简单的解决方案。

我唯一能想到的就是将{% if %} 语句推到任何地方以在placeholdervalue 之间进行选择,或者获取一些第三方库,如crispy-forms,但感觉更像是一个pythonic 解决方案应该存在。

【问题讨论】:

    标签: django django-views django-templates django-generic-views


    【解决方案1】:

    和往常一样,我在 SO 上发布问题后立即找到了答案。

    内置模板过滤器default_if_none解决了这个问题:

        <input
          class="form-class"
          type="text"
          placeholder="Article Title"
          name="{{ form.title.name }}"
          value="{{ form.title.value|default_if_none:'' }}"
        />
    

    【讨论】:

    • 我只能在 2 天内接受我的回答,但认为问题已解决。
    猜你喜欢
    • 2013-04-07
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2012-02-17
    • 2020-07-25
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多