# NOT NULL constraint failed: auctions\_comment.auction\_id

**URL:** <https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285>\
**Category:** Forms & APIs\
**Created:** [February 21, 2022, 7:43pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285 "2022-02-21T19:43:01Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [February 21, 2022, 7:43pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/1 "2022-02-21T19:43:01Z")

</div>

I’m having this error in my code and I have used adjusted my code using [NOT NULL constraint failed](https://forum.djangoproject.com/t/not-null-constraint-failed/9460) and other online resource but the problem persist.

Could you please tell me what I am doing wrong

MODELS.PY

```auto
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

```auto
class CommentForm(forms.ModelForm):

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

```

VIEWS.PY

```auto
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

Local vars

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

…

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

Local vars

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

Local vars

- `C:\Users\USER\Downloads\commerce\commerce\auctions\views.py` , line 139, in listing\_detail

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 22, 2022, 5:43pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/2 "2022-02-22T17:43:48Z")

</div>

> [@Theresa-o](#):
>
> ```auto
> new_comment.detail = detail
> 
> ```

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

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [February 23, 2022, 10:23am UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/3 "2022-02-23T10:23:52Z")

</div>

> [@Theresa-o](#):
>
> ```auto
> 
> ```

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

```auto
                <h2>Comments...</h2>

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

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 23, 2022, 1:17pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/4 "2022-02-23T13:17:15Z")

</div>

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](https://docs.djangoproject.com/en/4.0/topics/forms/#the-view) in the [Working with forms](https://docs.djangoproject.com/en/4.0/topics/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).

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [February 23, 2022, 3:25pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/5 "2022-02-23T15:25:38Z")

</div>

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)
```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 23, 2022, 3:46pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/6 "2022-02-23T15:46:30Z")

</div>

In your template you have:

> [@Theresa-o](#):
>
> `{% for comment in auction.comments.all %}`

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

I only see:

> [@Theresa-o](#):
>
> ```auto
> context = {'detail': detail,
> 'bid_count': bid_count, 
> 'bid_form': bid_form, 
> 'comment_form': comment_form}
> 
> return render(request, 'auctions/details.html', context)
> 
> ```

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [February 23, 2022, 4:05pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/7 "2022-02-23T16:05:51Z")

</div>

> [@Theresa-o](#):
>
> auction.comments.all

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

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 23, 2022, 4:13pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/8 "2022-02-23T16:13:30Z")

</div>

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

For example, your template has:

> [@Theresa-o](#):
>
> `{% for comment in auction.comments.all %}`

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.

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [February 23, 2022, 4:17pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/9 "2022-02-23T16:17:04Z")

</div>

This is my complete template

```auto
{% 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 %}

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 23, 2022, 4:19pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/10 "2022-02-23T16:19:12Z")

</div>

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`.

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [February 23, 2022, 4:22pm UTC](https://forum.djangoproject.com/t/not-null-constraint-failed-auctions-comment-auction-id/12285/11 "2022-02-23T16:22:02Z")

</div>

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.
