I am getting this error but I don't know why.
models.py
class Year(models.Model):
year = models.CharField(max_length=5, unique=True)
class Meta:
ordering = ['-year']
def __str__(self):
return self.year
class Photo(models.Model):
title = models.CharField(max_length=64)
description = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='photos/')
thumbnail = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='thumbnails/')
submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE)
views.py
def photo_create_view(request):
form = AddPhotoForm()
if request.method == 'POST':
image = request.FILES['image']
thumbnail = request.FILES['image']
title = request.POST.get('title')
description = request.POST.get('description')
year = request.POST.get('year')
people = request.POST.get('people')
tags = request.POST.get('tags')
photo = Photo(image=image, thumbnail=thumbnail, title=title, description=description, year=year,
people=people, tags=tags, submitter=request.user,)
photo.save()
return redirect('/photo/?page=1')
return render(request, 'photoapp/create.html', context={'form':form})
Cannot assign "123": "Photo.year" must be a "Year" instance. I have checked the Year table and year.id 123 exists. What am I missing?
CodePudding user response:
year_id = int(request.POST.get('year'))
Photo(year_id=year_id, ...)
CodePudding user response:
It's got to be the physical Year object
year = Year.objects.get_or_create(year=request.POST.get('year'))
Notes:
- You could also use
.get()
or.filter().first()
, must be the object and not a QuerySet - If you use a form you can get away with just the Pk in the request.POST
My own two sense: I don't think there's a benefit of having Year as it's own table, but maybe you're just using placeholders