我有一个包含用户列表的页面,并且希望能够单击链接来更新其个人资料。点击“更新”后,我应该可以使用一个提交按钮在一个页面中编辑用户名,名字,...电子邮件,电话号码,部门等。我通过使用两个表单完成了这个,一个用于User,另一个用于额外信息。 ListView,DeleteView和CreateView与这两种形式完美配合,但不适用于UpdateView。我无法使用初始数据实例化这两个表单。
问题是:如何使用数据实例化两个表单?覆盖self.object? get_form_kwargs?什么是最优雅的解决方案?
UpdateView类如下所示。我不是在寻找“复制 - 粘贴”解决方案,但可能会指出我正确的方向。
感谢。
保罗电话号码,部门在名为Employee的模型中定义。
class Employee(models.Model):
user = models.OneToOneField(User)
phone_number = models.CharField(max_length=13, null=True)
department = models.CharField(max_length=100)
模板是:
{% extends "baseadmin.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h4>Edit a user</h4>
<form action="" method="post" class="form-horizontal">
<legend>Edit a user</legend>
{% crispy form %}
{% crispy form2 %}
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Save">
<a href="{% url 'client_list' %}" class="btn">Cancel</a>
</div>
</form>
{% endblock content %}
视图类是:
class ClientUpdateView(UpdateView):
model = User
form_class = ClientsUserForm
second_form_class = ClientsForm
template_name = 'admin/client_update.html'
def get_context_data(self, **kwargs):
context = super(ClientUpdateView, self).get_context_data(**kwargs)
context['active_client'] = True
if 'form' not in context:
context['form'] = self.form_class(self.request.GET)
if 'form2' not in context:
context['form2'] = self.second_form_class(self.request.GET)
context['active_client'] = True
return context
def get(self, request, *args, **kwargs):
super(ClientUpdateView, self).get(request, *args, **kwargs)
form = self.form_class
form2 = self.second_form_class
return self.render_to_response(self.get_context_data(
object=self.object, form=form, form2=form2))
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.form_class(request.POST)
form2 = self.second_form_class(request.POST)
if form.is_valid() and form2.is_valid():
userdata = form.save(commit=False)
# used to set the password, but no longer necesarry
userdata.save()
employeedata = form2.save(commit=False)
employeedata.user = userdata
employeedata.save()
messages.success(self.request, 'Settings saved successfully')
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(
self.get_context_data(form=form, form2=form2))
def get_success_url(self):
return reverse('client_list')
答案 0 :(得分:4)
如果您需要,您应该可以使用“instance”kwarg从现有模型中实例化表单。例如:
context['form'] = self.form_class(self.request.GET, instance=request.user)
答案 1 :(得分:0)
尝试退出self.request.get
表单构造函数上的get_content_data
并使用&#34;对象&#34;变量。使用get
重新初始化构造函数,在this link中更多。
我的代码:
context['form'] = self.form_class(instance=self.object)