如何在Django modelform中执行查询?

时间:2018-10-26 07:29:51

标签: django django-models django-forms django-views

我在模型表单中尝试过此操作

class Ledgerform(forms.ModelForm):

class Meta:
    model = ledger1
    fields = ('name', 'group1_Name')


def __init__(self, User, Company,  *args, **kwargs):
    self.User = kwargs.pop('User', None)        
    self.Company = kwargs.pop('Company', None)
    super(Ledgerform, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs = {'class': 'form-control',}
    self.fields['group1_Name'].queryset = group1.objects.filter(User= self.User,Company = self.Company)

在我的views.py中,我做了这样的事情:

class ledger1ListView(LoginRequiredMixin,ListView):
    model = ledger1
    paginate_by = 15

    def get_queryset(self):
        return ledger1.objects.filter(User=self.request.user, Company=self.kwargs['pk'])

class ledger1CreateView(LoginRequiredMixin,CreateView):
    form_class = Ledgerform

    def form_valid(self, form):
        form.instance.User = self.request.user
        c = company.objects.get(pk=self.kwargs['pk'])
        form.instance.Company = c
        return super(ledger1CreateView, self).form_valid(form)

我想通过在模型窗体中使用queryset来执行与在ledger1ListView中传递的查询相同的查询,但是我的kwargs.pop不会返回当前用户或公司...

这是我的模型。py:

class ledger1(models.Model):
    User            = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    Company         = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys')
    name            = models.CharField(max_length=32)
    group1_Name     = models.ForeignKey(group1,on_delete=models.CASCADE,blank=True,null=True)

有人知道我的代码在做什么错吗?

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以在视图中覆盖FormMixin.get_form_kwargs [Django-doc],因为它使用初始化表格所需的参数构造了一个字典,例如:

class ledger1CreateView(LoginRequiredMixin,CreateView):
    form_class = Ledgerform

    def get_form_kwargs(self):
        data = super(ledger1CreateView, self).get_form_kwargs()
        data.update(
            User=self.request.User,
            Company=company.objects.get(pk=self.kwargs['pk'])
        )
        return data

form_valid函数在表单被构造,验证并看上去有效之后被称为 。通常,它用于将用户重定向到“成功页面”。