Django类视图

关键字

  • response
  • self
  • request
  • object


# model.py
class HostComment(models.Model):
    host = models.ForeignKey(Host, related_name='hostcomments')
    body = models.CharField(max_length=100, verbose_name='操作记录')
    created = models.DateTimeField(auto_now_add=True)
    author = models.CharField(max_length=20, default='admin')

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return 'Comment {} {} on {}'.format(self.host, self.body, self.created)



# views.py
class HostDetailView(DetailView):
    model = Host
    template_name = 'app/host_detail.html'
    context_object_name = 'post'

    def post(self, request, *args, **kwargs):
        response = super(HostDetailView, self).get(request, *args, **kwargs)
        comment_form = HostCommentForm(data=self.request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.host = self.object
            new_comment.author = self.request.user
            new_comment.save()
        return response


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        comment_form = HostCommentForm()
        comments = self.object.hostcomments.all()
        context['comments'] = comments
        context['comment_form'] = comment_form
        return context


# temples

      
操作记录
{#操作记录输入框#}
{{ comment_form.as_p }} {% csrf_token %}

{#操作记录显示框#}
Django类视图_第1张图片
image.png

你可能感兴趣的:(Django类视图)