Django:如何使用ModelFormSet通过request.user过滤ForeignKey选项

时间:2017-03-06 15:54:39

标签: python django django-forms formset

我只想过滤表格中的选择字段,关于当前登录的用户。每个用户都有自己的类别和预算 - 我只想显示与当前登录用户相关的模型。我在is_valid字段之前尝试了过滤,但没有结果。请在下面找到我的代码:

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

1 个答案:

答案 0 :(得分:2)

根据docs,您可以将自定义参数传递给表单集表单。

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})