简体   繁体   中英

unique_together django with foreign keys raise Validation error

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

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

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. But, you can try to cal 'by hand' 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM