Home > front end >  IntegrityError at /listing/1/ NOT NULL constraint failed: auctions_comments.user_id. I am trying to
IntegrityError at /listing/1/ NOT NULL constraint failed: auctions_comments.user_id. I am trying to

Time:05-23

I am trying to make an e-commerce site (CS50 Project 2) that saves comments. The comments were previously saving, but then I added ForeignKeys to my comment model to link it to the Listings and User models. Now whenever I try to save a comment this error occurs.

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

And this line of code is highlighted comment.save().

This is my 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 %}

I think the problem is with the comment.save() in the views.py and the form in the html where it says "{% url 'listing' auction_listing.id %}", but I don't know how to fix it.

Thank you for all the help!

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']

CodePudding user response:

I'm assuming that the form the user is using to post a comment doesn't have them specify their listing ID or user ID. If this is the case, then both listing and user in the Comments would be null which is what gives the error since foreign keys aren't allowed to be null. You'd have to manually fill in this missing data in your view. It looks like you already have the listing value figured out and you add it to the form instance. You just have to do the same thing for the user. The request argument has a user field that you can use to figure out the user ID.

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