[英]PRIMARY KEY must be unique error (Django)
->'views.py': ->'views.py':
def upload_event_image(request):
if request.method=="POST":
if request.FILES:
fest=get_object_or_404(Fest, pk=request.POST.get('fest_pk'))
if fest is not None:
event = Event.objects.create(
author = request.user,
fest = fest,
)
event.save()
if event:
photo= Photo.objects.create(
image = request.FILES['file'],
album = event //This line causes the error
)
photo.save()
return HttpResponse()
return HttpResponse()
-> model.py: -> model.py:
class Event(models.Model):
title = models.CharField(max_length=60, blank=True)
description = models.TextField(blank = True)
fest = models.ForeignKey(Fest)
pub_date = models.DateTimeField(default=datetime.datetime.now)
author = models.ForeignKey(User)
def __unicode__(self):
return self.description
def has_upvoted(self, user):
return user
class Photo(models.Model):
title = models.CharField(max_length=60 , blank= True, null = True)
image = models.ImageField(upload_to='site-media/media/images/')
thumbnail = models.ImageField(upload_to="site-media/media/images/thumbs/", blank=True, null=True)
thumbnail2 = models.ImageField(upload_to="site-media/media/images/thumbs2/", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
album = models.ForeignKey(Event)
When i make a post to the above view i get ' PRIMARY KEY must be unique' . 当我对以上观点发表文章时,我得到“ 主键必须是唯一的” 。 What am i doing wrong?
我究竟做错了什么? This is the line "album = event" which causes the error.
这是导致错误的“专辑=事件”行。
Final solution after correction: 校正后的最终解决方案:
def save(self, force_insert=False, force_update=False, **kwargs):
"""Save image dimensions."""
super(Photo, self).save(force_insert, force_update, **kwargs)
im = PImage.open(pjoin(MEDIA_ROOT, self.image.name))
self.width, self.height = im.size
self.create_thumbnail()
force_insert = False
force_update = True
super(Photo, self).save(force_insert, force_update, **kwargs)
From chat with Monique: the problem is in the (non-posted) Photo.save()
method that makes two calls to super().save()
, passing the same args in both cases , so the first call correctly creates the Photo
instance and the second tries to insert it again, which obviously fails. 与Monique聊天时:问题出在(未发布的)
Photo.save()
方法中,该方法对super().save()
进行了两次调用, 在两种情况下都传递了相同的args ,因此第一个调用正确地创建了Photo
实例,第二个尝试再次插入它,这显然失败了。
Solution (for anyone having the same problem): dont blindly pass *args
and **kwargs
to Model.save()
when your overload it and end up calling it a second time. 解决方案(对于有相同问题的任何人): 不要在重载时盲目将
*args
和**kwargs
传递给Model.save()
,并最终再次调用它。
class Foo(models.Model):
def save(self, force_insert=False, force_update=False, **kwargs):
super(Foo, self).save(force_insert, force_update, **kargs)
if somethings_needs_to_be_done:
do_something_here()
super(Foo, self).save(force_insert=False, force_update=True, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.