2017-10-09 34 views
0

我正在做簡單的費用經理。每個用戶都可以添加/刪除/編輯代表費用或收入的操作。不過,我注意到一個錯誤 - 在添加新的操作時,可以選擇其他用戶帳戶和類別。如何限制與數據庫中另一個表相關的字段選擇?

這裏是我的操作模式:

class Operation(models.Model): 

    def get_category_color(self): 
     return Category.objects.get(name=self.category).color 

    types_tuples = ((-1, 'expense'), (1, 'earning')) 

    user = models.ForeignKey(User) 
    account = models.ForeignKey(Account) 
    category = models.ForeignKey(Category) 
    date = models.DateField() 
    amount = models.DecimalField(max_digits=10, decimal_places=2) 
    type = models.IntegerField(choices=types_tuples) 
    currency = models.CharField(max_length=3) 

    color = property(get_category_color) 

OperationCreate觀點:

class OperationCreate(CreateView, OperationMixIn): 

    model = Operation 
    form_class = OperationForm 
    success_url = reverse_lazy('manage_operations') 

    def form_valid(self, form): 
     operation = form.save(commit=False) 
     operation.currency = Account.objects.get(pk=form.instance.account_id).currency 
     self.update_account_balance(form) 
     form.instance.user = self.request.user 
     return super(OperationCreate, self).form_valid(form) 

和OperationForm:

class OperationForm(ModelForm): 
    class Meta: 
     model = Operation 
     fields = ['account', 'type', 'category', 'date', 'amount'] 

問題是我怎麼可以限制帳戶和類別的選擇,在發佈新操作期間是否可用?我希望用戶只能看到與他/她的帳戶相關的內容。

我試過limit_choices_to作爲參數models.ForeignKey(Account)models.ForeignKey(Category)在操作模式,但不能使它的工作方式。

我假設我需要使用一個查詢,它將只返回與當前用戶相關的賬戶和類別。但我不知道如何以及在哪裏應用它。

請你指點我正確的方向?

編輯:

OperationForm編輯由於@efkin建議:

class OperationForm(ModelForm): 
    class Meta: 
     model = Operation 
     fields = ['account', 'type', 'category', 'date', 'amount'] 

    def __ini__(self, user, *args, **kwargs): 
     super(OperationForm, self).__init__(*args, **kwargs)  
     self.fields['account'] = ModelChoiceField(queryset=Account.objects.filter(user=user)) 
     self.fields['category'] = ModelChoiceField(queryset=Category.objects.filter(user=user)) 

回答

1

你可以使用一個簡單的形式與外鍵ModelChoiceField領域。

+0

嘿,感謝:OperationForm必須使用ModelChoiceFiled被修改(如@efkin所述)和OperationCreate應包含倍率爲get_form_kwargs方法從ModelFormMixIn。我查了一下,並有相關問題。 我認爲我可以按照以下方式修改我的操作表單,這些方法是在對原始文章進行編輯時顯示的。我不確定,但是我怎樣才能從視圖中傳遞'request.user'。 – Arxas

+0

好的,我找到了通過這個'request.user'參數的方法。看到下面的解決方案:) – Arxas

0

好的,所以我做了一些更多的挖掘並提出瞭解決方案。一個答案

class OperationCreate(CreateView, OperationMixIn): 

    model = Operation 
    form_class = OperationForm 
    success_url = reverse_lazy('manage_operations') 

    def get_form_kwargs(self): 
     kwargs = super(OperationCreate, self).get_form_kwargs() 
     kwargs.update({'user': self.request.user}) 
     return kwargs 

    def form_valid(self, form): 
     operation = form.save(commit=False) 
     operation.currency = Account.objects.get(pk=form.instance.account_id).currency 
     self.update_account_balance(form) 
     form.instance.user = self.request.user 
     return super(OperationCreate, self).form_valid(form) 
相關問題