Fernanda Martínez
Fernanda Martínez

Reputation: 227

Django form isn't showing the correct fields

The django form to let users change their information fields should let them change username, email, name and last_name, but instead, it shows their nationality, gender, score on app and birthday.

views.py

def  profileedit_view(request):
    if request.method== 'POST':
        form= PerfilEditadoForm(request.POST, instance = request.user)
        if form.is_valid():
            form.save()
            return redirect('login')
        else:
            form= PerfilEditadoForm(instance=request.user)
            args= {'form': form}
            return render(request, 'profileedit', args)

    form = UsuarioForm(request.POST or None)
    if form.is_valid():
        form.save()

    context = {
        'form': form
    }
    return render(request, "profileedit.html", context)

forms.py

class PerfilEditadoForm(UserChangeForm):
    class Meta:
        model = User
        fields= ('email', 'username', 'first_name', 'last_name')

profileedit.py

<form method="POST" action="#"> {% csrf_token %}
        <p>
        {{ form.as_ul }}
        <button class="btn btn-primary py-1 px-2" type="submit" > Save </button>
        </p>
        </form>

Upvotes: 0

Views: 33

Answers (2)

slackmart
slackmart

Reputation: 4934

Your form is being overridden by form = UsuarioForm(request.POST or None). Assuming the fields you want to show belong to PerfilEditadoForm, you should change that line to form = PerfilEditadoForm(request.POST or None).

My suggestion would be to move that particular line just before the if request.method== 'POST':. Something like

def  profileedit_view(request):
    form= PerfilEditadoForm(request.POST or None)
    if request.method== 'POST':
        form.instance = request.user
        if form.is_valid():
            form.save()
            return redirect('login')
        else:
            form= PerfilEditadoForm(instance=request.user)
            args= {'form': form}
            return render(request, 'profileedit', args)

    context = {
        'form': form
    }
    return render(request, "profileedit.html", context)

Upvotes: 1

Muvva Teja Reddy
Muvva Teja Reddy

Reputation: 76

In forms.py change the brackets- use [] instead of ()

class PerfilEditadoForm(UserChangeForm):
    class Meta:
        model = User
        fields= ['email', 'username', 'first_name', 'last_name']

Upvotes: 0

Related Questions