[英]unique_together django with foreign keys raise Validation error
models.py models.py
class Follow(models.Model):
date_time = models.DateTimeField(auto_now_add=True, blank=True, unique=False)
user = models.ForeignKey(User)
follower = models.ForeignKey(User, related_name="followers", unique=False)
def __unicode__(self):
return '%s, %s' % (self.user.username, self.follower)
class Meta:
unique_together = [("user", "follower")]
view.py view.py
def new_follow(request):
if request.method == 'POST':
form = FollowForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
if not hasattr(instance, 'user'):
instance.user = request.user
instance.save()
form.save_m2m()
return HttpResponseRedirect('/followers/' + request.user.username)
else:
new_follow()
else:
form = FollowForm()
args = {}
args.update(csrf(request))
args['form'] = form
variables = RequestContext(request, {'form': form})
return render_to_response('new_follow.html', variables)
forms.py forms.py
class FollowForm(forms.ModelForm):
class Meta:
model = Follow
exclude = ['user']
I am getting this error when an existing follow already exists in the database how can i solve that? 当数据库中已经存在现有跟踪时,我会收到此错误,我该如何解决呢? An error is raised correctly in the admin panel on the other hand. 另一方面,会在管理面板中正确引发错误。
IntegrityError at /follow/
columns user_id, follower_id are not unique
Request Method: POST
Django Version: 1.6
Exception Type: IntegrityError
Exception Value:
columns user_id, follower_id are not unique
Perhaps the easy way to fix your code is to set user to model instance before to call is_valid()
method. 修复代码的简单方法可能是在调用is_valid()
方法之前,将用户设置为模型实例。 But, you can try to cal 'by hand' validate_unique : 但是,您可以尝试手动“ 校验 ” validate_unique :
...
instance = form.save(commit=False)
if not hasattr(instance, 'user'):
instance.user = request.user
try:
instance.validate_unique()
instance.save()
form.save_m2m()
return HttpResponseRedirect('/followers/' + request.user.username)
except ValidationError, e: #<---- Capturing validate unique exception
# and append error to form error dict
form._errors = {}
for _, v in e.message_dict.items():
form._errors.setdefault(NON_FIELD_ERRORS, []).extend( v )
Disclaimer, not tested. 免责声明,未经测试。
PE: Check your code, has no sense save instance only if user is not informed. PE:检查您的代码,只有在不通知用户的情况下,才可以保存实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.