2012-08-16 126 views
2

鑑於下面的示例代碼,驗證沒有重複code/account的最佳方法是什麼?Django - unique_together驗證

型號

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

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

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

查看

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 

我已經找到答案提示somethi ng類似於使用clean_code(),但account似乎並不存在。你有什麼建議?

回答

1

下面是相關的例子,從文檔:https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

基本上乾淨的()可以訪問通過cleaned_data各個領域。這是爲了在Form中驗證的方法。

如果你想在模型中做到這一點,請看pre_save。

+0

Jure,我明白你在說什麼,但'帳戶'似乎並不存在。 – RS7 2012-08-16 20:52:34

+0

啊,我明白了。在你的meta:fields =('code',),爲什麼不包括帳戶?這樣它將成爲代碼的一部分。你可以隱藏它。 – 2012-08-16 21:34:42