1

How to show all fields values of a model from a form in Django?

I'm making a page to edit the user's account. The new values are saving with no problems, but I can't show the current values of the fields in the form (using forms.ModelForm).

forms.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' )

views.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,
    })

template:

{% 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 %}

models.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)

What do i need to do to the current values to be displayed on my form?

Submitted July 24th 2021 by Admin

Answers
0

You are swapping the instance=s. You provided the usario_form the user object, and the user_form the usario object. You need to do the opposite:

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 | 1 month ago



Relevant Questions