通过GET或POST请求向表单发送一些值

时间:2019-06-17 10:24:15

标签: python django python-3.x

我需要使用GET或POST向表单发送一些值。

我的表单:

class InstallmentReportForm(forms.ModelForm):
    class Meta:
        model = InstallmentReport
        exclude = ()
    def __init__(self, *args, **kwargs):
        super(InstallmentReportForm, self).__init__(*args, **kwargs)
        self.fields['title'].queryset = Report.objects.filter(grant_name=??????)


InstallmentReportFormSet = inlineformset_factory(Installment,InstallmentReport,
                           form=InstallmentReportForm, fields=['title','spent'],
                                                         extra=1,can_delete=True)

这是我的视图模型:

class InstallmentReportCreate(LoginRequiredMixin,PermissionRequiredMixin,CreateView):
    model = Installment
    template_name = 'catalog/installment_report_update.html'
    permission_required = 'catalog.can_change_grant'
    form_class = InstallmentForm
    success_url = None

    def get_context_data(self, **kwargs):
        data = super(InstallmentReportCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['titles'] = InstallmentReportFormSet(self.request.POST)
        else:
            data['titles'] = InstallmentReportFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        print(titles)
        with transaction.atomic():
            form.instance.owner = self.request.user
            self.object = form.save()
            if titles.is_valid():
                titles.instance = self.object
                titles.save()
        return super(InstallmentReportCreate, self).form_valid(form)

    def get_success_url(self):
        return reverse('grant-installment-owner', args=(self.object.id,))

我需要获取'grant_name'来过滤数据。

我正在使用Python3.7.3和Django 2.2.1

1 个答案:

答案 0 :(得分:0)

让传递的查询参数为'grant_name',在 init ()中为

def __init__(self, *args, **kwargs):

    if self.request.method == 'POST';

        grant_name = self.request.POST.get('grant_name')

    else:

        grant_name = self.request.GET.get('grant_name')

    super(InstallmentReportForm, self).__init__(*args, **kwargs)
    self.fields['title'].queryset = Report.objects.filter(grant_name=grant_name)