两个基于同一路线的分类视图

时间:2016-06-03 01:32:36

标签: python django django-views

我使用通用的DetailView来显示我的模型Ticket的详细信息。 有一个boostrap模式可以在模板中为此故障单创建评论。

如何使用CreateView在模态中显示表单?

是否可以使用某种类型的继承将DetailView与CreateView结合使用以使用boostrap模式?

  

view.py

class TicketDetail(DetailView):
    model = Ticket
    template_name = 'ticket_detail.html'
    context_object_name = 'ticket'
    slug_field = 'slug'

class TicketCommentCreate(CreateView):
    template_name = 'ticket_detail.html'
    form_class = CommentForm
    success_url = '/painel/tickets'
  

urls.py

url(r'^painel/tickets/(?P<slug>[-\w]+)/$',views.TicketDetail.as_view(), name='ticket_detail'), 
  

ticket_detail.html

<div class="modal fade" id="commentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Criar Comentário</h4>
                </div>
                <div class="modal-body">
                    {% load crispy_forms_tags %}
                    {% crispy form %}
                </div>
            </div>
        </div>
    </div>

1 个答案:

答案 0 :(得分:0)

我找到了解决方法:Using FormMixin with DetailView

class TicketDisplay(LoginRequiredMixin, DetailView):
    model = Ticket
    template_name = 'ticket_detail.html'
    context_object_name = 'ticket'
    slug_field = 'slug'

    def get_context_data(self, **kwargs):
        context = super(TicketDisplay, self).get_context_data(**kwargs)
        context['form_add_comment'] = CommentForm()
        return context

class TicketCommentCreate(LoginRequiredMixin, FormView):
    form_class = CommentForm
    template_name = 'ticket_detail.html'

    def get_success_url(self):
        return reverse('ticket_detail', kwargs={'slug' : self.kwargs['slug']} )

    def form_valid(self, form):
        slug = self.kwargs.get('slug', None)
        ticket = get_object_or_404(Ticket, slug=slug)
        comment = form.save(commit=False)
        comment.author_login = ticket.author
        comment.ticket = ticket
        comment.save()
        ticket.save() #Update Date
        return HttpResponseRedirect(self.get_success_url())


class TicketDetail(LoginRequiredMixin, View):

    def get(self, request, *args, **kwargs):
        view = TicketDisplay.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = TicketCommentCreate.as_view()
        return view(request, *args, **kwargs)