关键字
- 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
<div class="panel panel-warning">
<div class="panel-heading">操作记录</div>
<div class="panel-body">
{#操作记录输入框#}
<form action="{{ post.get_absolute_url }}" method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="提交"></p>
</form>
{#操作记录显示框#}
<div class="profile-user-info profile-user-info-striped">
{% for comment in comments %}
<div class="profile-info-row">
<div class="profile-info-name">{{ comment.created|timesince }} 前 by {{ comment.author }}</div>
<div class="profile-info-value">
<span>{{ comment.body|linebreaks }}</span>
</div>
</div>
{% endfor %}
</div>
</div>
</div>