我有一个模板,显示包含2个模型数据的表单。两个模型都包含一个名为“name”的属性。问题是,当我保存时,表单中“name”的错误值将保存为appuser模型。如何为“名称”字段中的每两个表单获取正确的值?
查看(#ISSUE)
class FarmCreateView(CreateView):
template_name = 'directory/farm_registration.html'
model = Appuser
success_url = '/'
def get_context_data(self, **kwargs):
context = super(FarmCreateView, self).get_context_data(**kwargs)
context['farm'] = FarmForm()
context['appuser'] = FarmUserCreateForm()
return context
def post(self, request, *args, **kwargs):
farm_form = FarmForm(self.request.POST)
appuser_form = FarmUserCreateForm(self.request.POST)
if farm_form.is_valid() and appuser_form.is_valid():
# Save the appuser
new_user = appuser_form.save(commit=False)
new_user.name = appuser_form.cleaned_data.get('name')
# ISSUE I would expect the line above to return the name from the
# appuser_form, but instead it return the name from the farm_form
new_user.save()
# Save the farm
new_farm = farm_form.save(commit=False)
new_farm.appuser = new_user;
new_farm.save()
farm_form.save_m2m() # This is needed because we
# initially save with commit=false - it's just the way django works
# Log user in after registration
new_user_login = authenticate(email=request.POST['email'],
password=request.POST['password'])
login(request, new_user_login)
return HttpResponseRedirect('/')
else:
return render_to_response('directory/farm_registration.html', {'farm':
farm_form, 'appuser': appuser_form},
context_instance=RequestContext(request))
模板提取
<div class="pure-g">
<div class="pure-u-1-2 {{appuser.name.css_classes}}" style="margin-bottom: 20px;">{{appuser.name}}</div>
<div class="pure-u-1-2 {{appuser.surname.css_classes}}"><div style="float:right;">{{appuser.surname}}</div></div>
<div class="pure-u-1-2 {{appuser.email.css_classes}}" style="margin-bottom: 20px;">{{appuser.email}}</div>
<div class="pure-u-1-2 {{appuser.phone_number.css_classes}}"><div style="float:right;">{{appuser.phone_number}}</div></div>
<div class="pure-u-1-2 {{appuser.password.css_classes}}" style="margin-bottom: 20px;">{{appuser.password}}</div>
<div class="pure-u-1-2 {{appuser.password1.css_classes}}"><div style="float:right;">{{appuser.password1}}</div></div>
</div>
<!-- Farm Info -->
<div style="height:28px; position:relative; text-align:center; margin-bottom:10px; margin-left:1px; margin-right:1px">
<div class="page_section_strikethrough"></div>
<div class="page_section_heading" style="background:rgb(246,246,246)">FARM INFO</div>
</div>
<div class="pure-g">
<div class="pure-u-1-1 {{farm.name.css_classes}}" style="margin-bottom: 20px;">{{farm.name}}</div>
答案 0 :(得分:1)
在表单中使用前缀,如下所示:
context['farm'] = FarmForm(prefix="farm_form")
context['appuser'] = FarmUserCreateForm(prefix='farm_user_create')
答案 1 :(得分:0)
检查已呈现表单中的name
属性,尤其是{{ appuser.name }}
和{{ farm.name }}
输入元素的属性。
我猜他们是一样的,因为我认为渲染模板里面没有命名空间。因此,将有两个<input name="name" ...>
元素,在POST
上,一个将覆盖另一个元素。
因此,当您在post(...)
方法中创建绑定表单时,可以使用相同的名称填充两个表单。您可以在运行开发服务器时打印self.request.POST
的值来验证后者:您应该只看到一个name
密钥。