Django编辑评论

时间:2018-04-19 17:26:37

标签: python django

所以我想编辑现有评论,但它给了我这个错误

  

ValueError at / episode / Dragon-Ball-Super / edit / 11   视图home.views.edit_comment没有返回HttpResponse对象。它改为返回None。

edit_comment

def edit_comment(request, slug, id):
    anime = get_object_or_404(Anime, slug=slug)
    comment = get_object_or_404(Comment, id=id)
    form = CommentForm(request.POST, instance=comment.user)
    if request.method == 'POST' or 'NONE':
        if form.is_valid():
            form.save()
            return redirect('anime_title', slug=slug)
        else:
            form = CommentForm()
            context = {'form': form}
            return render(request, 'home/edit-comment.html', context)

urls.py

urlpatterns = [
path('', views.index, name='index'),
re_path(r'^episode/(?P<slug>[\w-]+)/$', views.anime_title, name='anime_title'),
re_path(r'^episode/(?P<slug>[\w-]+)/comment/$', views.add_comment, name='add_comment'),
re_path(r'^episode/(?P<slug>[\w-]+)/edit/(?P<id>\d+)/?', views.edit_comment, name='edit_comment'),

现有评论下的

链接

{% if comment.user == request.user.userprofile %}
    <h6 class="small comment-meta">
     <a href="{% url 'edit_comment' slug=anime.slug id=comment.id %}">Edit</a>
                    Delete</h6>
{% endif %}

models.py

class Comment(models.Model):
    anime = models.ForeignKey(Anime, on_delete=models.CASCADE)
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

编辑comment.html

    {% extends 'base/base.html' %}
    {% block head %}
        <title>Edit Comment</title>
    {% endblock %}
    {% block content %}
        <h2>Edit Comment</h2>
        <form method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
    {% endblock %}

1 个答案:

答案 0 :(得分:1)

您只处理POST请求。 GET请求将在您加载表单时第一次放置。

def edit_comment(request, slug, id):
    anime = get_object_or_404(Anime, slug=slug)
    comment = get_object_or_404(Comment, id=id)
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST, instance=comment.user)
        if form.is_valid():
            form.save()
            return redirect('anime_title', slug=slug)
    return render(request, 'home/edit-comment.html', {'form':form})