在 Django 中赋值之前引用的局部变量 'comment_form'

local variable 'comment_form' referenced before assignment in django

我创建了一个用户可以登录的应用程序和 post 他想要的内容:现在我决定为每个 post 用户在应用程序中所做的添加评论部分,我遵循了中的教程djangocentral 网站,但在我将他们所做的一切添加到我的应用程序后它无法正常工作,当我单击 [阅读更多] 它在浏览器中抛出一个错误:局部变量 'comment_form' 在赋值之前引用,如果我删除了: 'comment_form' 在我的 viewPhoto 视图的上下文中,它在 viewPhoto 模板中不显示任何内容。我该怎么做?

型号:

class Comment(models.Model):
    post = models.ForeignKey(Photo, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80) 
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)  

admin.py:

from django.contrib import admin
from .models import Photo, Category, Comment

# Register your models here.
admin.site.register(Category)
admin.site.register(Photo)
@admin.register(Comment)

class CommentAdmin(admin.ModelAdmin):
    list_display = ('name', 'body', 'post', 'created_on', 'active')
    list_filter = ('active', 'created_on')
    search_fields = ('name', 'email', 'body')
    actions = ['approve_cooments']


    def approve_comment(self, request, queryset):
        queryset.update(active=True)

form.py:

from dataclasses import fields
from pyexpat import model
from .models import Comment
from django import forms


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body',)

view.py:

def viewPhoto(request, pk):
    post = get_object_or_404(Photo, id=pk)
    photo = Photo.objects.get(id=pk)

    template_name = 'photo.html'
    comment = post.comments.filter(active=True)
    new_comment = None


    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():

            new_comment = comment_form.save(commit=False)

            new_comment.post = post

            new_comment.save()
        else:
            comment_form = CommentForm()
    return render(request, 'photo.html', {'photo': photo, 'post': post, 
    'comment':comment, 
    'new_comment': new_comment,
    'comment_form': comment_form})

查看照片模板:

<body class="m-5">
<div class="container">
     <div class="row justify-content-center">
          <div class="col">
               <div style="height: 90vh;">
                  <img style="max-width: 100%; max-height: 100%" src="{{ post.image.url }}" alt="">

                  <p>{{post.description}}</p>
                  <p>{{post.user.username.upper}}</p>
                  <p>{{post.date_added}}</p>

               </div>

          </div>
     </div>
</div>
 <div class="container">
      {% for comment in comments %}
      <p>{{ comment.name }}</p>
      <br>
      <p>{{ comment.created_on }}</p>
      <br>
      <p>{{ comment.body }}</p>
      {% endfor %}
 </div>


<div class="container">
     {% if new_comments %}
     <p>wait your comments is ready</p>

     <form method="POST"> 
          {% csrf_token %}             
          {{ comment_form.as_p }}
          <button type="submit">submit</button>
     </form>
     {% endif %}
</div>

else 应该绑定 if request.method == 'POST' 检查,而不是 if comment_form.is_valid() 检查,所以:

from django.shortcuts import redirect

def viewPhoto(request, pk):
    post = get_object_or_404(Photo, id=pk)
    photo = Photo.objects.get(id=pk)

    template_name = 'photo.html'
    comment = post.comments.filter(active=True)
    new_comment = None


    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            comment_form.instance.post = post
            comment_form.save()
            return redirect('<em>name-of-some-view</em>')
    <strong>else</strong>:
        comment_form = CommentForm()
    return render(request, 'photo.html', {'photo': photo, 'post': post, 
    'comment':comment, 
    'new_comment': new_comment,
    'comment_form': comment_form})

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.