RS7
RS7

Reputation: 2361

Django - unique_together validation

Given the example code below, what would be the best way to validate that there are no duplicate code per account?

Model

class Post(models.Model):
    account = models.ForeignKey('Account', editable=False)
    code = models.CharField()

    class Meta:
        unique_together = ('account', 'code')

Form

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('code',)

View

def post_add(request):
    try:
        account = Account.objects.get(membership__user=request.user)
    except:
        login_url = reverse('login') + ('?next=%s') % request.path
        return HttpResponseRedirect(login_url)

    post = Post()

    if request.method == "POST":
        post_form = PostForm(request.POST, prefix='post')

        if post_form.is_valid():
            post = post_form.save(commit=False)
            post.account = account
            post.save()

        # other code

I've found answers suggesting something similar to using clean_code() but account doesn't seem to exist at that point. What do you suggest?

Upvotes: 2

Views: 2223

Answers (1)

Jure C.
Jure C.

Reputation: 3080

Here's relevant example from documentation: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Basically clean() has access to all fields via cleaned_data. This is for approach for validation within Form.

If you want to do it in model, look at pre_save.

Upvotes: 1

Related Questions