1

如何从 Django 的表单中显示模型的所有字段值?

我正在制作一个页面来编辑用户的帐户。新值保存没有问题,但我无法在表单中显示字段的当前值(使用 forms.ModelForm)。

表格.py:

 class UserForm(forms.ModelForm): class Meta: model = User fields = ('email', 'first_name', 'last_name') class UsuarioForm(forms.ModelForm): class Meta: model = USUARIO fields = ('cpfCnpj', 'dataNascimento', 'telefone', 'receberNotificacoes', 'tipoUsuario' )

视图.py:

 @login_required @transaction.atomic def modificar_cadastro(request): if request.method == "POST": user_form = UserForm(request.POST, instance=request.user) usuario_form = UsuarioForm(request.POST, instance=request.user.usuario) if usuario_form.is_valid() and user_form.is_valid(): user_form.save() usuario_form.save() return render(request, 'index.html') else: messages.error(request, ('Please correct the error below.')) else: usuario_form = UsuarioForm(instance=request.user) user_form = UserForm(instance=request.user.usuario) return render(request, 'modificar-cadastro.html', { 'usuario_form': usuario_form, 'user_form': user_form, })

模板:

 {% extends 'base.html' %} {% load crispy_forms_tags %} {% block conteudo %} <h2>Modificar cadastro</h2> <form method="POST" class="post-form">{% csrf_token %} {{ user_form|crispy }} {{ usuario_form|crispy }} <button type="submit" class="btn btn-outline-dark">Save</button> </form> {% endblock %}

模型.py:

 class USUARIO(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) tipoUsuario = models.IntegerField(choices=TIPOS_USUARIO, default=1) cpfCnpj = models.CharField(max_length=11, blank=False, null=True, verbose_name='CPF') dataNascimento = models.DateField(blank=False, null=True, verbose_name='Data de nascimento') telefone = models.CharField(max_length=11, blank=True, null=True, verbose_name='Número de telefone') pontuacao = models.DecimalField(max_digits=30, decimal_places=15, blank=True, null=True) receberNotificacoes = models.BooleanField(default=False)

我需要对表单上显示的当前值做什么?

已提交 July 24th 2021 通過 Admin

答案
0

您正在交换instance= s。您提供了usario_form user对象,而user_formusario对象。你需要做相反的事情:

 def modificar_cadastro(request): if request.method == 'POST': # … else: # not request.user ↓ usuario_form = UsuarioForm( instance=request.user.usuario ) # not request.user.usario ↓ user_form = UserForm( instance=request.user ) # …

Admin | 2个月前



枪支相关