我开发了一个使用FormView嵌套的inlineformset的Django项目。
我首先使用CreateView / UpdateView开发表单,并且可以使用,但是当我使用FormView时出现错误
'UtilisateurUpdateView'对象没有属性'object'
为什么当我使用UpdateView而不是FormView时为什么可以访问'object'?
我已经读到它可能来自重写方法,但是这里似乎不是这样吗?
forms.py
NAME = Thesaurus.options_list(2,'fr')
ACCESS = Thesaurus.options_list(3,'fr')
ApplicationFormset = inlineformset_factory(
UtilisateurProjet, Application, #Utilisateur, Application,
fields=('app_app_nom','app_dro'),
widgets={
'app_app_nom': forms.Select(choices=NAME),
'app_dro': forms.Select(choices=ACCESS)
},
extra=3,
can_delete=True,
)
class UtilisateurProjetUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs)
PROJETS = Projet.objects.all()
UTILISATEURS = Utilisateur.objects.all()
self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet']))
self.fields["uti_ide"] = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select, initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur']))
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide',)
views.py
class UtilisateurUpdateView(FormView):
template_name = 'project/utilisateurprojet_form.html'
form_class = UtilisateurProjetUpdateForm
def get_form_kwargs(self):
kwargs = super(UtilisateurUpdateView, self).get_form_kwargs()
kwargs['request'] = dict(utilisateur = self.kwargs['pk'], projet = self.kwargs['projet'])
return kwargs
def get_context_data(self, **kwargs):
data = super(UtilisateurUpdateView,self).get_context_data(**kwargs)
if self.request.POST:
data["utilisateur"] = self.request.user.username
data["user_profil"] = self.request.session.get('user_profil')
data["application"] = ApplicationFormset(self.request.POST, instance=self.object)
else:
data["application"] = ApplicationFormset(instance=self.get_object())
return data
def form_valid(self, form):
context = self.get_context_data()
application = context["application"]
user_profil = context["user_profil"]
self.object.uti_val = 1
self.object.uti_val_dat = timezone.now()
else:
self.object.uti_val = 0
self.object = form.save()
if application.is_valid():
form.instance = self.object
application.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("project:index")
FormView和DetailView是来自不同程序包的不同类:分别为django.views.generic.edit.FormView
和django.views.generic.detail.DetailView
。
来自DetailView的文档:
在执行此视图时,self.object将包含以下对象:视图正在运行。
FormView没有对象属性,因为它不一定与对象一起使用。
但是,由于您正在使用ModelForms,因此应该可以通过从form_valid
方法调用form.instance来访问Forms对象。