Django CreateView表单未插入

时间:2018-11-15 20:52:42

标签: django forms django-class-based-views

我对此很陌生,但是我想做的是让我的表单在另一视图中显示(作为模板的一部分注入)。在开发人员工具中,我看到了包含页面的HTML(polls / _poll_form.html),但看不到表单。如果有人能指出我正确的方向,我将不胜感激。

models.py

class Poll(models.Model):
    poll_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, unique=True)
    topic = models.ForeignKey(
        Topic,
        related_name = 'polls',
        on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    last_updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
            'polls:single',
            kwargs={'pk':self.pk}
        )

    class Meta:
        db_table = 'polls'
        ordering = ['last_updated_at']

views.py

  class CreatePoll(LoginRequiredMixin, generic.CreateView):
        template_name = 'polls/_poll_form.html'
        model = Poll

_poll_form.html(注入的模板)

<div class="container poll-form-header">
    <p class="text-center">Get Started</p>
</div>
<form class="create-poll-form" action="{% url 'topics:single' pk=topic.topic_id %}" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" class="btn btn-dark float-right">
</form>

topic_detail.html

{% extends "topics/topic_base.html" %}

{%block topics_content %}
  <div class="col-md-12 list-group polls-list">
      <div class="container new-poll-button">
        <a class = "btn btn-dark float-right mt-2" data-toggle="collapse" href="#poll-form" role="button" aria-expanded="false">Create Poll</a>
      </div>
      <div class="collapse mt-2 new-poll-form" id="poll-form">
        <div class="card card-body">
          {% include "polls/_poll_form.html" %}
        </div>
      </div>
    {% if topic.polls.count == 0 %}
      <br>
      <div class="container no-polls-message">
        <p>There are no polls for this topic.  Create the first!</p>
      </div>
    {% else %}
      {% for poll in topic.polls.all %}
        {% include "polls/_poll.html" %}
      {% endfor %}
    {% endif %}
  </div>
{% endblock %}

2 个答案:

答案 0 :(得分:0)

这似乎是一个相当普遍的困惑,但是我真的不明白它是如何产生的。

仅在另一个模板中包含一个模板并不意味着将执行提及该模板的视图。视图渲染模板,模板不调用视图。仅由请求该视图处理的URL的用户调用视图。在您的情况下,该URL指向一个完全不同的URL,而从不创建该表单的URL。

您需要在URL实际调用的视图的上下文中包括表单。可以通过get_context_data方法显式地执行此操作,或者-如果表单需要在多个页面上显示,请创建一个custom template tag来插入呈现的模板,包括表单。

答案 1 :(得分:-1)

在您的应用程序中创建一个forms.py。

写这样的东西:

from .models import Poll

class PollForm(forms.ModelForm):

  class Meta:
        model = Poll
        fields = ('name', 'topic',)

然后在views.py中导入PollForm并将其传递给模板

from polls.forms import PollForm

 class CreatePoll(LoginRequiredMixin, generic.CreateView):
        template_name = 'polls/_poll_form.html'
        model = Poll
        form_class = PollForm