猿问

Django 表单未显示正确的字段

让用户更改信息字段的 django 表单应该让他们更改用户名、电子邮件、姓名和姓氏,但它会显示他们的国籍、性别、应用得分和生日。


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>


函数式编程
浏览 107回答 2
2回答

烙印99

您的表单正在被覆盖form = UsuarioForm(request.POST or None)。假设您要显示的字段属于 PerfilEditadoForm,您应该将该行更改为form = PerfilEditadoForm(request.POST or None)。我的建议是将该特定行移到if request.method== 'POST':. 就像是def&nbsp; profileedit_view(request):&nbsp; &nbsp; form= PerfilEditadoForm(request.POST or None)&nbsp; &nbsp; if request.method== 'POST':&nbsp; &nbsp; &nbsp; &nbsp; form.instance = request.user&nbsp; &nbsp; &nbsp; &nbsp; if form.is_valid():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; form.save()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return redirect('login')&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; form= PerfilEditadoForm(instance=request.user)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; args= {'form': form}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return render(request, 'profileedit', args)&nbsp; &nbsp; context = {&nbsp; &nbsp; &nbsp; &nbsp; 'form': form&nbsp; &nbsp; }&nbsp; &nbsp; return render(request, "profileedit.html", context)

catspeake

在 forms.py 中更改括号 - 使用 [] 而不是 ()class PerfilEditadoForm(UserChangeForm):&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = User&nbsp; &nbsp; &nbsp; &nbsp; fields= ['email', 'username', 'first_name', 'last_name']
随时随地看视频慕课网APP

相关分类

Html5
我要回答