**My models**
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(default='write description')
price = models.DecimalField(decimal_places=2, max_digits=10000)
def __str__(self):
return self.title
class Comment(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.TextField(default='Write ur comments')
def __str__(self):
return self.comment
**My views code**
def home_view(request):
product_list = Product.objects.order_by('title')
context = {'product_list': product_list}
return render(request, 'my_rev/home_view.html', context)
def detail_view(request, product_id):
product = Product.objects.get(pk=product_id)
comment_form = CommentForm(request.POST, instance=product)
if comment_form.is_valid():
comment_form.save()
comment_form = CommentForm()
context = {'product': product, 'comment_form': comment_form}
return render(request, 'my_rev/detail_view.html', context)
def create_product_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
form = ProductForm()
context = {
'form': form
}
return render(request, 'my_rev/create_view.html', context)
def user_comment_view(request):
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
comment_form.save()
comment_form = CommentForm()
context2 = {
'comment_form': comment_form
}
return render(request, 'my_rev/comment_view.html', context2)
URL patterns
urlpatterns = [
path('', home_view, name='Home'),
path('<int:product_id>/', detail_view, name='detail'),
path('create/', create_product_view, name='create'),
path('comment/', user_comment_view, name='add comment'),
path('admin/', admin.site.urls),
urlpatterns = [
path('', home_view, name='Home'),
path('<int:product_id>/', detail_view, name='detail'),
path('create/', create_product_view, name='create'),
path('comment/', user_comment_view, name='add comment'),
path('admin/', admin.site.urls),
]
detail_view.html
<body>
<h1>{{ product.title }}</h1>
<p>
<p><strong>PRODUCT DESCRIPTION</strong></p>
{{ product.description }}
<p><strong>Price: </strong>Rs.{{ product.price }}</p>
<ul>
{% for comment in product.comment_set.all %}
<li>{{ comment.comment|capfirst }}</li>
{% endfor %}
</ul>
<p><a href="/comment/"><strong>ADD COMMENT</strong></a></p>
comment_view.html
<body>
<h1>{{product.title}}</h1>
<form method="POST"> {% csrf_token %}
{{ comment_form.as_p }}
<input type="submit" value="Save"/>
I am getting the Integrity error NOT NULL Constrained failed after the comment is submitted, it is not saved as well as i get the error