Home > other >  Django: NOT NULL constraint failed: course_courserating.user_id
Django: NOT NULL constraint failed: course_courserating.user_id

Time:04-24

i am trying to create a logic where users can review and rate a course, the logic in my views.py looks fine but i keep gettting this errror NOT NULL constraint failed: course_courserating.user_id i removed some null=True from my models but it still keeps showing the error.

views.py

if request.method == "POST":
        form = CourseRatingForm(request.POST)
        if form.is_valid():
            rating_form = form.save(commit=False)
            user = request.user
            course = course
            rating_form.save()
            messages.success(request, f'You review was sent successfully!')
            return redirect("course:course-detail", course.slug)
    else:
        form = CourseRatingForm

models.py

class Course(models.Model):
    course_title = models.CharField(max_length=10000)
    slug = models.SlugField(unique=True)


class CourseRating(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
    rating = models.CharField(max_length=1000, choices=USER_COURSE_RATING)
    review = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)
    
    def __str__(self):
        return f"{self.course.course_title} - {self.rating}"

CodePudding user response:

You need to assign it to the CourseRating object, so:

if request.method == 'POST':
    form = CourseRatingForm(request.POST, request.FILES)
    if form.is_valid():
        form.instance.user = request.user
        form.instance.course = course
        form.save()
        messages.success(request, f'You review was sent successfully!')
        return redirect('course:course-detail', course.slug)
else:
    form = CourseRatingForm()
  • Related