ssharkar
ssharkar

Reputation: 57

django.db.utils.IntegrityError: null value in column "author_id" of relation "movie_movie" violates not-null constraint no idea why is this occurring

Seems like model is only getting "null". I tried to print the request user in views and it was fine.

View codes.

def add_item(request):  # add new media
quote = random.choice(quotes)
if request.method == "POST":
    new_item = MovieForm(request.POST)
    new_item.save(commit=False)
    new_item.author = request.user
    new_item.save()
    return redirect('movie:movie_library')
else:
    movie_form = MovieForm()
return render(request, 'movie/add_movie.html',
              context={'form': movie_form,
                       'quote': quote})

model

class Movie(models.Model):
STATUS_CHOICES = (
    ('Movie', 'Movie'),
    ('Tv-series', 'Tv Series'),
    ('Anime', 'Anime'),
)
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=50, null=False)
type = models.CharField(max_length=15,
                        choices=STATUS_CHOICES,
                        default='')
year = models.IntegerField(null=True, blank=True)
rating = models.FloatField(max_length=10, null=False)
review = models.TextField(null=True, blank=True)
img_url = models.TextField(default='https://betravingknows.com/wp-content/uploads/2017/'
                                   '06/video-movie-placeholder-image-grey.png')
active = models.BooleanField(default=True)

def __str__(self):
    return self.title

forms

from django import forms
from movie.models import Movie


class MovieForm(forms.ModelForm):
    class Meta:
        model = Movie
        fields = ('title', 'type', 'year', 'review',
                  'rating', 'img_url', 'active')

error

django.db.utils.IntegrityError: null value in column "author_id" of relation "movie_movie" violates not-null constraint DETAIL: Failing row contains (46, Sapiens, Movie, 435, 6.5, ftght, https://betravingknows.com/wp-content/uploads/2017/06/video-movi..., t, null).

Upvotes: 1

Views: 1621

Answers (3)

Amiay Narayan
Amiay Narayan

Reputation: 529

Just in case. If you are using Django rest framework, and you have your serializer set up as follows: author is foreign key. If you POST request is attempting to create a db object of model with a foreign key, then make sure it is not mentioned as read-only.

class PostSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')  # just comment this
    # author = UserSerializer(read_only=True) # remove this also if present

    ...

Please remove the readonly part. This stops the expected result to occur. Also make sure that, the author field receives the id of the type of foreingKey (here User).

Upvotes: 0

Guillaume
Guillaume

Reputation: 2006

In fact, in your code you're not assigning the request.user to your new object, but to your form, thus it's not saving.

form.save() returns the new object and that's what you need to manipulate here.

Also, consider handling the case where the form is not valid with form.is_valid().

if request.method == "POST":
    form = MovieForm(request.POST)
    if form.is_valid():
        new_item = form.save(commit=False)
        new_item.author = request.user
        new_item.save()

Hope that helped.

Upvotes: 0

Charnel
Charnel

Reputation: 4432

Isn't request.user return AnonymousUser instead of registered one? In this case author will get None that will raise your error. You can add login_required decorator to your view in order to avoid this:

from django.contrib.auth.decorators import login_required

@login_required
def add_item(request):
    ...

Upvotes: 2

Related Questions