Issue
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).
Solution
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.
Answered By - Guillaume
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.