django:如何在forms.py中使用materializecss添加一个select字段

时间:2017-05-25 06:13:27

标签: django django-models django-forms materialize

我有一个forms.py我希望能够在HTML中看到select标签我收到错误

forms.py

    class ArticleForm(ModelForm):

        class Meta:

            STATUS_CHOICES = (
                ('d', 'Draft'),
                ('p', 'Published'),
            )
            model = Article
            fields = (
                'title', 'description', 
                'article_header_image', 'status',
                )

models.py

class Article(TimeStampedModel):
    """
    Article model.
    """
    STATUS_CHOICES = (
        ('d', 'Draft'),
        ('p', 'Published'),
    )
    title = models.CharField('title', max_length=150)
    description = models.TextField('content')
    status = models.CharField('article status', max_length=1,
                              choices=STATUS_CHOICES, blank=True, null=True, default='p')
    article_header_image = models.ImageField(
            upload_to="artice__header_image/%Y/%m/%d"
            )

create.html上

  <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <input class="btn" type="submit" value="Create" />
  </form>

我没有看到HTML上的select标签

html来源

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Django Class Based Views Rock</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/materialize/0.98.2/css/materialize.min.css">
    <style>
      .title {
        text-align: center;
        font-weight: 200;
      }
    </style>
  </head>
  <body>

      <div class="container">

  <h3 class="title">Create New Article</h3>
  <form method="post" enctype="multipart/form-data">
      <input type='hidden' name='csrfmiddlewaretoken' value='V6IJWF7lceEbe8pT4yN7GaCqgHnbZsbgpFWTcH9dwxzpNZzX2GFKILzpMyvs5Fls' />
      <p><label for="id_title">Title:</label> <input id="id_title" maxlength="150" name="title" type="text" required /></p>
<p><label for="id_description">Content:</label> <textarea cols="40" id="id_description" name="description" rows="10" required>
</textarea></p>
<p><label for="id_article_header_image">Article header image:</label> <input id="id_article_header_image" name="article_header_image" type="file" required /></p>
<p><label for="id_status">Article status:</label> <select id="id_status" name="status">
<option value="">---------</option>
<option value="d">Draft</option>
<option value="p" selected="selected">Published</option>
</select></p>
      <input class="btn" type="submit" value="Create" />
  </form>

      </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js" />
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

如果要显示Materializecss select,则需要使用.input-field class form

包装它

您有两种选择。

  1. 使用{{form.status}}包裹.input-field div class

    使用单独的表单标记
    <div class="input-field">
      {{ form.status }}
    </div>
    
  2. 或使用django-materializecss-form