gpt4 book ai didi

django - 使用基于类的 View 预填充 Django 表单

转载 作者:行者123 更新时间:2023-12-02 03:46:06 25 4
gpt4 key购买 nike

当我正在学习 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',]

最佳答案

跟随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

关于django - 使用基于类的 View 预填充 Django 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46726971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com