NOT NULL constraint failed: auctions_comment.auction_id

I’m having this error in my code and I have used adjusted my code using NOT NULL constraint failed and other online resource but the problem persist.

Could you please tell me what I am doing wrong

MODELS.PY

class Auction(models.Model):
    ABSTRACT = 'AB'
    MODERN = 'MN'
    ILLUSTRATION = 'IN'

    select_category = [
        ('ABSTRACT', 'Abstract'),
        ('MODERN', 'Modern'),
        ('ILLUSTRATION', 'Illustration')
    ]

    title = models.CharField(max_length=25)
    description = models.TextField()
    current_bid = models.IntegerField(null=False, blank=False)
    image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True)
    category = models.CharField(
        choices=select_category,
        max_length=12,
        default=MODERN,
        null=True, blank=True
    )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created_at']


class Comment(models.Model):
    auction = models.ForeignKey(Auction, related_name='comments', on_delete=models.CASCADE)
    name = models.CharField(max_length=25)
    description = models.TextField(max_length=150)
    created_at = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return '%s, - %s' % {self.aunction.title, self.name}

    class Meta:
        ordering = ['-created_at']

FORMS.PY

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ['name', 'description']

VIEWS.PY

def listing_detail(request, listing_id):
    try:
        detail = get_object_or_404(Auction, pk=listing_id)
    except Auction.DoesNotExist:
        messages.add_message(request, messages.ERROR, "This is not available") 
        return HttpResponseRedirect(reverse("index"))

    bid_count = Bids.objects.filter(auction=listing_id).count()
    bid_form= BidForm()     

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

        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.detail = detail
            new_comment.save()

        else:
            comment_form = CommentForm()
    else:
        comment_form = CommentForm()
    context = {'detail': detail,
                'bid_count': bid_count, 
                'bid_form': bid_form, 
                'comment_form': comment_form}

    return render(request, 'auctions/details.html', context)

TRACEBACK

IntegrityError at /detail/15/

NOT NULL constraint failed: auctions_comment.auction_id

|Request Method:|POST|

|Django Version:|4.0.2|
|Exception Type:|IntegrityError|
|Exception Value:|NOT NULL constraint failed: auctions_comment.auction_id|
|Exception Location:|C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py, line 416, in execute|
|Python Executable:|C:\Users\USER\AppData\Local\Programs\Python\Python310\python.exe|
|Python Version:|3.10.0|
|Python Path:|[‘C:\Users\USER\Downloads\commerce\commerce’, ‘C:\Users\USER\AppData\Local\Programs\Python\Python310\python310.zip’, ‘C:\Users\USER\AppData\Local\Programs\Python\Python310\DLLs’, ‘C:\Users\USER\AppData\Local\Programs\Python\Python310\lib’, ‘C:\Users\USER\AppData\Local\Programs\Python\Python310’, ‘C:\Users\USER\AppData\Roaming\Python\Python310\site-packages’, ‘C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages’]|
|Server time:|Mon, 21 Feb 2022 17:45:29 +0000|

  • C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py , line 85, in _execute

    1. return self.cursor.execute(sql, params)

Local vars

  • C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py , line 416, in execute

    1. return Database.Cursor.execute(self, query, params)

Local vars

  • The above exception (NOT NULL constraint failed: auctions_comment.auction_id) was the direct cause of the following exception:

  • C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py , line 47, in inner

    1. response = get_response(request)

Local vars

  • C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py , line 181, in _get_response

    1. response = wrapped_callback(request, *callback_args, **callback_kwargs)

Local vars

  • C:\Users\USER\Downloads\commerce\commerce\auctions\views.py , line 139, in listing_detail

    1. new_comment.save()

You do not have an attribute named detail in your Comment object. The attribute name that I think you intended to use is auction.

1 Like

Thank you Ken so much, that cleared the error but my comments are not showing when it saves.

I also included in the html but its not showing

                <h2>Comments...</h2>

                {% for comment in auction.comments.all %}
                    <article>
                        <strong> {{comment.name}} </strong><br>{{ comment.description }}
                    </article>
                {% endfor %}

Your successful submission is not resulting in a redirect to cause the database to be read when rendering the new page.

Review the section the view in the Working with forms docs to see what I mean. You want a successful post to result in a redirect somewhere (and yes, that could be to the same page you’re on).

I had redirected but didn’t update the post to show that but I am redirecting (the redirecting is working) but the comment is still not showing in the details page.

        new_comment.save()

        return redirect('listing_detail', listing_id=listing_id)

In your template you have:

Where are you passing an element named auction in your context to the template?

I only see:

From the tutorial I watched, the auction (in auction.comments.all) is in reference to the model
auction = models.ForeignKey(Auction, related_name='comments', on_delete=models.CASCADE)
using the related name (comments) to get the users comments.

Are we supposed to include this in the context

You’re not showing the complete template, so I can’t accurately answer your question.

For example, your template has:

which means that comment at this point is a variable being assigned in the template - it doesn’t come from the context.

I can’t tell from what you’ve posted whether auction is a variable being supplied from the context or being assigned within the template.

It does need to be one or the other - the choice between them depends upon what the rest of the template looks like.

This is my complete template

{% extends "auctions/layout.html" %}

{% block body %}
                <h2>Comments...</h2>

                {% for comment in auction.comments.all %}

                    <article>

                        <strong>{{comment.name }}</strong><br>{{ comment.description }}

                    </article>

                {% endfor %}

                <hr>

                <div class="font-weight-bold text-center">

                    <a href="#"></a><h2>Add a comment </h2>

                </div>

                <hr>

                <form action="{% url 'listing_detail' detail.id %}" method="post">

                    {% csrf_token %}

                    {{ comment_form.as_p }}

                    <input type="submit" class="btn btn-primary mt-3" value="Add Comment">

                </form>

            </div>

{% endblock %}

Ok, so no, you’re not defining a variable named auction within the template, which means you need to pass an instance of an Auction object to the template in the context with the name auction.

Edit: Or, if the instance that you want to use is the one you’re passing into the template with the name detail in your context, you can change your template to refer to detail instead of auction.

1 Like

That was it. Ok, my goodness, thank you * 52. Also, thank you for your detailed comments in the previous post I mentioned, I learnt new things via your explanation.