使用基于类的视图预填充Django表单

时间:2017-10-13 09:41:03

标签: django django-class-based-views

当我正在学习Django Class Based View(CBV)以处理我在Function Based View(FBV)中开发的脚本时,我想做以下过程。

我想根据self.request.GET预填充一个Django表单字段。

这是我的班级:

class IdentitySocieteFormView(LoginRequiredMixin, CreateView) :

    form_class = SocieteFormulaire
    template_name = 'Identity_Societe_Form.html'
    model = Societe

    def get_context_data(self, **kwargs) :

        data = super(IdentitySocieteFormView, self).get_context_data(**kwargs)

        if 'recherche' in self.request.GET :

            query_Responsable = self.request.GET.get('Responsable') 
            Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable)

            data['responsable'] = Responsable

        return data

    def form_valid(self, form) :

        form.instance.Reponsable = responsable
        form.instance.Utilisateur = self.request.user.last_name + " " + self.request.user.first_name

        return super(IdentitySocieteFormView, self).form_valid(form)

但我不确定这一行:form.instance.Reponsable = responsable让我重新填充我的领域。

以前,我的脚本看起来像这样:

@login_required
def IdentitySocieteForm(request) :

    query_Responsable = request.GET.get('Responsable') 

    success = False

    if request.method == 'POST':

        form = SocieteFormulaire(request.POST or None)

        if form.is_valid() :   # Vérification sur la validité des données
            post = form.save()

            messages.success(request, 'Le formulaire a été enregistré !')
            return HttpResponseRedirect(reverse('SocieteResume', kwargs={'id': post.id}))

        else:
            messages.error(request, "Le formulaire est invalide !")

    else:
        form = SocieteFormulaire()

        Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable)
        form.fields['Responsable'].queryset = Responsable
        form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name

    return render(request, 'Identity_Societe_Form.html', {"form" : form, "query_Responsable" : query_Responsable})

如果你能帮助我,请提前谢谢

编辑:

我尝试了get_initial()

def get_initial(self):

        initial = super(IdentitySocieteFormView, self).get_initial()

        if 'recherche' in self.request.GET :

            query_Responsable = self.request.GET.get('Responsable')
            Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable)
            initial['Responsable'].queryset = Responsable

        return initial

但我明白了:

File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Identity/views.py" in get_initial
  227.             initial['Responsable'].queryset = Responsable

Exception Type: KeyError at /Identification/Company/Form/
Exception Value: 'Responsable'

我的forms.py看起来像这样:

class SocieteFormulaire(forms.ModelForm) :

    Responsable = CustomLabelModelChoiceField(Individu.objects.filter(), required=False, label = "Responsable", label_func=lambda obj: '%s %s %s' % (obj.Nom, obj.Prenom, obj.NumeroIdentification))
    InformationsInstitution = forms.CharField(widget=forms.HiddenInput(), initial=InformationsInstitution.objects.using('default').last().Ville.encode('utf-8'))

    class Meta :
        model = Societe
        fields = [
                'Nom',
                'Etat', 
                'Adresse', 
                'Ville', 
                'Zip', 
                'Region',
                'Pays', 
                'Mail',
                'Web',
                'Telephone',
                'Fax',
                'SIREN',
                'SIRET',
                'NAF_APE',
                'RCS',
                'CHOIX_TVA',
                'TVA',
                'Type',
                'Effectif',
                'Domaine', 
                'Capital',
                'Responsable',
                'InformationsInstitution',]

1 个答案:

答案 0 :(得分:3)

跟随filtering-a-model-in-a-createview-with-get-queryset

将方法更新为get_form_kwargs

def get_form_kwargs(self):
    kwargs = super(IdentitySocieteFormView, self).get_form_kwargs()
    query_Responsable = self.request.GET.get('Responsable')
    Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable)
    kwargs['responsable_qs'] = Responsable
    u = request.user
    kwargs['user_initial'] = '{lname} {fname}'.format(lname=u.last_name, fname=u.first_name)
    return kwargs

表格

class SocieteFormulaire(forms.ModelForm):
    def __init__(self, *args, **kwargs):
       user_initial = kwargs.pop('user_initial', None)
       responsable_qs = kwargs.pop('responsable_qs', None)
       super(SocieteFormulaire, self).__init__(*args, **kwargs)
       self.fields['Responsable'].queryset = responsable_qs
       self.fields['InformationsInstitution'].initial = user_initial