Django表单不会渲染(无反向匹配)

时间:2017-09-14 15:44:31

标签: django django-forms

我试图用Django 1.10创建一个表单来创建一个Task对象的注释。 当我想打开表单时,没有字段,当我尝试提交时,我收到了这个错误:

  

NoReverseMatch at / tasks / 29 / comment /   反转' create_comment'有参数'('',)'未找到。尝试了1种模式:[u' tasks /(?P [0-9] +)/ comment / $']

如何在我的模板上呈现我的表单,并返回到我的"详细信息"提交后查看?

forms.py

class CreateCommentForm(forms.Form):
    commentary = forms.CharField(label='Commentary', widget=forms.Textarea, required=True)

models.py

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    commentary = models.TextField(blank=True, max_length=5000)
    created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.commentary 

views.py

class CommentCreateView(SuperuserRequiredMixin, FormView):
    template_name = 'tasks/create_comment_modal.html'
    form_class = CreateCommentForm

def form_valid(self, form):
    user = self.request.user
    task = Task.objects.get(id=self.kwargs['pk'])
    commentary = form.cleaned_data['commentary']
    comment = Comment(user=user, task=task, commentary=commentary)
    comment.save()
    return HttpResponseRedirect(reverse('tasks:detail', kwargs={'pk': task.id}))

urls.py

url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/comment/$', views.CommentCreateView.as_view(), name='create_comment'),

create_comment_modal.html

{% load widget_tweaks %}
<form role="form" id="comment-create-form" name="comment-create-form" method="post" action="{% url 'tasks:create_comment' task.id %}">
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Add comment in task #{{ task.id }} - {{ task.title }}</h4>
</div>
<div class="modal-body">
    {% csrf_token %}
    <div class="row">
        <div class="col-lg-12">
            <div class="form-group">
                <label class="control-label" for="{{ form.commentary.id_for_label }}">Commentary</label>
                {% render_field form.commentary class+="form-control" %}
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12">
            <div id="current_user">
                Comment by : {{ user.first_name }} {{ user.last_name }}
            </div>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
    <button type="submit" class="btn btn-primary" value="deploy">Submit</button>
</div>
</form>

1 个答案:

答案 0 :(得分:0)

表单中的{% url 'tasks:create_comment' task.id %}看起来很可疑。

您是否在task

中将CommentCreateView添加到您的上下文中

将以下行添加到CommentCreateView

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context.update({'task': Task.objects.get(id=self.kwargs['pk'])})
    return context