我試圖用Django 1.10創建一個窗體來創建一個任務對象的評論。 當我想打開窗體,沒有現場,當我嘗試提交,我得到這個錯誤:Django窗體將不呈現(不反向匹配)
NoReverseMatch在/任務/ 29 /評論/ 反向與參數「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">×</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>
嘗試:高清get_success_url(個體經營):回反向( '任務:細節',kwargs = { 'PK':self.task.id})在CommentCreateView –