IntegrityError 在 /listing/1/ NOT NULL 约束失败:auctions_comments.user_id。我正在尝试保存评论并需要帮助解决此错误

IntegrityError at /listing/1/ NOT NULL constraint failed: auctions_comments.user_id. I am trying to save comments and need help resolving this error

我正在尝试制作一个保存评论的电子商务网站(CS50 项目 2)。评论以前是保存的,但后来我将 ForeignKeys 添加到我的评论模型中,以 link 将其添加到列表和用户模型中。现在,每当我尝试保存评论时,都会发生此错误。

IntegrityError at /listing/1/
NOT NULL constraint failed: auctions_comments.user_id
Request Method: POST
Request URL:    http://127.0.0.1:8000/listing/1/
Django Version: 3.2.5
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: auctions_comments.user_id

并且这行代码高亮显示comment.save()

这是我的 models.py:

class User(AbstractUser):
    pass

class Listings(models.Model):
    CATEGORY = [
    ("Miscellaneous", "Miscellaneous"),
    ("Movies and Television", "Movies and Television"),
    ("Sports", "Sports"),
    ("Arts and Crafts", "Arts and Crafts"),
    ("Clothing", "Clothing"),
    ("Books", "Books"),
]
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=500)
    bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
    image = models.URLField(null=True, blank=True)
    category = models.CharField(max_length=64, choices=CATEGORY, default=None)

class Comments(models.Model):
    listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    comment = models.CharField(max_length=500)

views.py

@login_required(login_url='login')
def listing(request, id):
    listing = Listings.objects.get(id=id)
    comment_obj = Comments.objects.filter(listing=listing)
    form = CommentForm()
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.listing = listing
            comment.save()
        else:
            return render(request, "auctions/listing.html",{
               "auction_listing": listing,
               "form": form,
               "comments": comment_obj
               })
    return render(request, "auctions/listing.html",{
        "auction_listing": listing,
        "form": form,
        "comments": comment_obj
    })

html

{% block body %}
    <img src ="{{ auction_listing.image }}" style = "height: 10%; width: 10%;">
    <h4 class = "text">{{ auction_listing.title }}</h4>
    <h6>Description: {{ auction_listing.description }}</h6>
    <h6>Category: {{ auction_listing.category }}</h6> 
    <h6>Price: ${{ auction_listing.bid }}</h6>

    <form action = "{% url 'listing' auction_listing.id %}" method = "POST">
        {% csrf_token %}
        {{ form }}
        <input type = "submit" value = "Save">
    </form>

    {% for comment in comments %}
        <h6> {{ comment.comment }} </h6>
    {% endfor %}

    <button type = "button">Add to Watchlist</button>
{% endblock %}

我认为问题出在 views.py 中的 comment.save() 和 html 中的表格,其中显示“{% url 'listing' auction_listing.id %}",但我不知道如何解决。

感谢大家的帮助!

forms.py

class ListingsForm(forms.ModelForm):
    class Meta:
        model = Listings
        fields = ['title', 'description', 'bid', 'image', 'category']

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comments
        fields = ['comment']

我假设用户用于 post 评论的表单没有让他们指定他们的 listing ID 或 user ID。如果是这种情况,那么 Comments 中的 listinguser 都将为空,这就是导致错误的原因,因为外键不允许为空。您必须在视图中手动填写这些缺失的数据。看起来您已经计算出列表值并将其添加到表单实例中。你只需要为用户做同样的事情。 request 参数有一个 user 字段,您可以使用它来计算 user ID。

if form.is_valid():
            comment = form.save(commit=False)
            comment.listing = listing
            comment.user = request.user
            comment.save()