我有一个小问题:) 我想直接使用Django模型添加/编辑用户。我做到了:
class AddClientView(generic.FormView):
success_url = 'manager/liste'
form_class = AddClientForm
template_name = 'Manager/Clients/formClient.html'
def get_context_data(self, **kwargs):
retour = super(AddClientView, self).get_context_data()
retour['forms'] = AddClientForm
return retour
def form_valid(self, form):
retour = super(AddClientView, self).form_valid(form)
form.save()
return retour
class EditClientView(generic.FormView):
success_url = '/manager/liste'
form_class = AddClientForm
template_name = 'Manager/Clients/formClient.html'
def get_context_data(self, **kwargs):
retour = super(EditClientView, self).get_context_data()
client = Clients.objects.get(id=self.kwargs["client"])
retour['forms'] = AddClientForm(instance=client)
retour['client'] = client
return retour
def form_valid(self, form):
retour = super(EditClientView, self).form_valid(form)
a = Clients.objects.get(id=self.kwargs['client'])
a.prenom = form.cleaned_data['prenom']
a.nom = form.cleaned_data['nom']
a.telephone = form.cleaned_data['telephone']
a.mail = form.cleaned_data['mail']
a.adresse = form.cleaned_data['adresse']
a.date_anniversaire = form.cleaned_data['date_anniversaire']
a.save()
for pConseomme in form.cleaned_data['pConsomme']:
a.pConsomme.add(pConseomme)
for pInteret in form.cleaned_data['pInteret']:
a.pInteret.add(pInteret)
return retour
对于编辑,我想做与添加相同的操作,例如: 只是
form.save()
但是它不起作用...它创建了一个新用户。我该怎么做? 谢谢你们 !
答案 0 :(得分:0)
您可以对编辑执行相同的操作,但是考虑添加新用户和更新用户不是同一回事。添加时,它会创建一个新用户,但是在编辑时,您应该首先找到该特定用户并更改其数据,然后再保存模型。
user= get_object_or_404(User, pk=form.cleaned_data['user'].pk)
您可以get_object_or_404()
根据其 pk 查找用户,并执行与添加操作相同的过程。