2

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?

4

1 回答 1

1

以下是文档中的相关示例:https ://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

基本上 clean() 可以通过 clean_data 访问所有字段。这是用于在 Form 中进行验证的方法。

如果您想在模型中执行此操作,请查看 pre_save。

于 2012-08-16T20:38:04.590 回答