2017-03-06 111 views
0

我只想篩選表單中與當前記錄的用戶有關的選擇字段。每個用戶都有自己的類別和預算 - 我只想顯示與當前登錄用戶相關的模型。我已經嘗試過在is_valid字段之前進行過濾,但沒有結果。請找我下面的代碼:Django:如何使用ModelFormSet通過request.user篩選ForeignKey選項

views.py

@login_required 
def day_data_multiadd(request, no_of_lines=0): 
    no_of_lines = int(no_of_lines) 
    CostFormSet = modelformset_factory(Cost, form=DataAddForm, extra=no_of_lines) 
    if request.method == 'POST' and 'form' in request.POST: 
     formset = CostFormSet(request.POST, request.FILES) 
     if formset.is_valid(): 
      for form in formset.forms: 
       f = form.save(commit=False) 
       f.user = request.user 
       f.save() 
    else: 
    formset = CostFormSet(queryset=Cost.objects.none()) 

    if request.method == 'POST' and 'no_line' in request.POST: 
    generate_form = MultiaddGenerateForm(request.POST) 
    if generate_form.is_valid(): 
     cd = generate_form.cleaned_data 
    return HttpResponseRedirect(reverse('core_sm:day_data_multiadd', args=(cd['formy'],))) 
    else: 
    generate_form = MultiaddGenerateForm() 

    return render(request, 'core_sm/costs/multi_add.html', {'formset': formset, 
    'no_of_lines': no_of_lines, 
    'generate_form': generate_form}) 

forms.py

class DataAddForm(forms.ModelForm): 
    class Meta: 
    model = Cost 
    fields = ['title', 'value', 'publish', 'category', 'budget'] 
    exclude = ['user'] 
    labels = { 
     'title': _('Tytuł'), 
     'value': _('Wartość'), 
     'publish': _('Data'), 
     'category': _('Kategoria'), 
     'budget': _('Budżet') 
    } 

models.py

class Category(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL) 
    title = models.CharField(max_length=200) 
    publish = models.DateField(auto_now_add=True) 
    updated = models.DateField(auto_now=True) 

    class Meta: 
     ordering = ('-publish',) 

    def __str__(self): 
     return self.title 

    def get_absolute_ur(self): 
     return reverse('core_sm:category_detail', args=[self.id]) 


class Budget(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL) 
    title = models.CharField(max_length=200, db_index=True) 
    value = models.DecimalField(decimal_places=2, max_digits=10) 
    publish = models.DateField(auto_now_add=True) 
    updated = models.DateField(auto_now=True) 

    class Meta: 
     ordering = ('-publish',) 

    def __str__(self): 
     return self.title 

    def get_absolute_url(self): 
     return reverse('core_sm:budget_detail', args=[self.id]) 


class Cost(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL) 
    budget = models.ForeignKey(Budget, related_name='cost') 
    category = models.ForeignKey(Category, related_name='cost') 
    title = models.CharField(max_length=200, db_index=True) 
    publish = models.DateField(default=timezone.now) 
    created = models.DateField(auto_now_add=True) 
    updated = models.DateField(auto_now=True) 
    value = models.DecimalField(max_digits=10, decimal_places=2) 

    class Meta: 
     ordering = ('-publish',) 

    def get_absolute_url(self): 
     return reverse('core_sm:stats_detail', args=[self.publish.year, 
             self.publish.strftime('%y'), 
             self.publish.strftime('%m'), 
             self.publish.strftime('%d')]) 

    def __str__(self): 
     return self.title 

回答

2

按照docs你可以通過自定義參數到formset形式。

class DataAddForm(forms.ModelForm): 
    class Meta: 
    model = Cost 
    fields = ['title', 'value', 'publish', 'category', 'budget'] 
    exclude = ['user'] 
    labels = { 
     'title': _('Tytuł'), 
     'value': _('Wartość'), 
     'publish': _('Data'), 
     'category': _('Kategoria'), 
     'budget': _('Budżet') 
    } 

    def __init__(self, *args, **kwargs): 
     user = kwargs.pop('user') 
     self.fields['category'].queryset = Category.objects.filter(user=user) 
     self.fields['budget'].queryset = Budget.objects.filter(user=user) 
     super(DataAddForm, self).__init__(*args, **kwargs) 

views.py

formset = CostFormSet(queryset=Cost.objects.none(), form_kwargs={'user': request.user}) 
+0

謝謝你的答案,但我收到一個錯誤: _init __()得到了一個意想不到的關鍵字參數 '用戶' –

+0

嘗試:'高清__init __(自我,用戶,*參數,** kwargs):' – alfredo138923

+0

不,它不起作用 –

相關問題