如何在Django博客同一页面用DetailView和UpdateView实现评论编辑
问题:无法在详情页实现用户评论编辑功能
折腾好几天了,参考了不少教程,现在离目标很近,但就是实现不了用户编辑自己评论的功能。以下是现有实现代码:
模型代码
class Suggestion(models.Model): id = models.UUIDField(default=uuid.uuid4,primary_key=True,unique=True) created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='suggestion_created_by') last_update = models.DateTimeField(editable=False,null=True) suggestion_creation_date = models.DateTimeField(editable=False,null=True) suggestion_name = models.CharField(max_length=255,null=True) suggestion_status = HTMLField(blank=True,null=True) suggestion = HTMLField(blank=True,null=True) unique_identifier = models.CharField(max_length=64,null=True,blank=True) class Meta: ordering = ["suggestion_name"] def __str__(self): return self.suggestion_name def get_absolute_url(self): return reverse("Suggestions:suggestion_detail",kwargs={'pk':self.pk}) class SuggestionComment(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) comment = models.CharField(max_length=255,blank=True) created_on = models.DateTimeField(default=timezone.now) suggestion = models.ForeignKey('Suggestion',on_delete=models.CASCADE,related_name='suggestion_comments') upvotes = models.ManyToManyField(User,blank=True,related_name='suggestion_comment_upvotes') def get_absolute_url(self): return reverse("Suggestions:suggestion-detail", kwargs={"pk": self.suggestion.pk})
模板代码
DetailView模板
<!DOCTYPE html> {% extends "base21.html" %} <title>{% block title %} LevelSet Suggestion By Name Detail {% endblock %}</title> {% block body_block %} <div class="box12"> <h1 class="title">{{ suggestion_detail.suggestion_name }}</h1> <div class="spacer281"> {{ suggestion_detail.suggestion|safe }} </div> {% if suggestion_detail.suggestion_status != None %} <div class="spacer280"> <h2>Status - </h2> </div> <div class="spacer76"> {{ suggestion_detail.suggestion_status|safe }} </div> {% endif %} <div class="spacer285"> {% include 'suggestion_comments.html' %} </div> </div> </div> {% endblock %}
评论包含模板 suggestion_comments.html
<form method='POST' class="comment-form"> {% csrf_token %} <div class="spacer284"> {{ form.comment }} </div> <button class="button7" type="submit">Submit</button> </form> <div class="spacer286"> {% if suggestion_comments %} <h2>Comments</h2> {% for comment in object.suggestion_comments.all %} <div class="spacer291"> <p><a href="{% url 'Main:associate_directory_associate_detail' pk=comment.author.id %}">{{ comment.author }}</a> {{ comment.created_on }}</p> <p class="spacer290">{{ comment.comment }}</p> <div class="spacer289"> <div class="upvote-comment-count">{{ comment.total_comment_upvotes }}</div> <button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' comment.id %}">Like</button> <button type="button" class="button2" data-href="">Reply</button> {% if comment.author == request.user %} <button type="button" class="button4" id="{{ comment.id }}" pk="{{ object.pk }}" href="{% url 'Suggestions:suggestion_comment_edit' comment.id %}">Edit</button> <div class="spacer159" id="hide_payment" style="display:none;"> <form method='POST'> {% csrf_token %} <div class="spacer284"> {{ form.comment }} </div> <button class="button7" type="submit">Submit</button> </form> </div> <button type="button" class="button3" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button> {% endif %} </div> </div> {% endfor %} {% else %} <h2>No Comments Yet</h2> {% endif %} </div>
视图代码
SuggestionDetailView
class SuggestionDetailView(LoginRequiredMixin,DetailView): model = Suggestion context_object_name = 'suggestion_detail' template_name = 'suggestion_detail.html' def get_context_data(self, **kwargs): context = super(SuggestionDetailView, self).get_context_data(**kwargs) form = SuggestionCommentForm() suggestion_comments = SuggestionComment.objects.filter(suggestion_id=self.object.pk).order_by('-created_on').all() context['form'] = form context['suggestion_comments'] = suggestion_comments return context def post(self, request, *args, **kwargs): form = SuggestionCommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.author = request.user new_comment.suggestion = self.get_object() new_comment.save() self.object = self.get_object() context = self.get_context_data(object=self.object) html = render_to_string('suggestion_comments.html', context, request=self.request) return JsonResponse({'form': html}) else: form_errors = form.errors.as_json() response = HttpResponse(form_errors, status=400) response['content_type'] = 'application/json' return response
评论编辑函数视图
def suggestion_comment_edit_view(request, id): comment = get_object_or_404(SuggestionComment, pk=id) if request.method == "POST": form = SuggestionEditCommentForm(request.POST, instance=comment) if form.is_valid(): comment = form.save(commit=False) comment.save() return HttpResponseRedirect(reverse('Suggestions:suggestion_detail', kwargs={'pk': comment.suggestion.pk})) else: form = SuggestionEditCommentForm(instance=comment) return render(request, 'suggestion_comments.html', {'form': form, 'object': comment.suggestion})
AJAX代码
$(document).on("click",'.button4',function(e){ e.preventDefault(); var comment_id = $(this).attr('id'); var $editBtn = $(this); var $editForm = $editBtn.next('#hide_payment'); $.ajax({ url: '/LevelSet/Suggestions/suggestion_comment_edit/'+comment_id+'/', type: 'get', success: function (data) { // 提取返回的表单部分替换现有空白表单 var formHtml = $(data).find('#hide_payment form').html(); $editForm.find('form').html(formHtml); $editForm.show(); } }); });
URL配置
path("suggestion_comment_edit/<int:id>/",views.suggestion_comment_edit_view, name='suggestion_comment_edit'),
当前现状与需求
博客详情页及顶部评论提交功能正常,但点击编辑按钮后页面内表单显示空白;直接访问编辑URL可正常显示编辑界面并更新评论。希望通过DetailView和UpdateView在同一页面实现用户评论编辑功能。
内容的提问来源于stack exchange,提问作者Steve Smith
相关产品推荐
相关产品推荐

