Home > Enterprise >  django update user form
django update user form

Time:10-13

here the problem with form, all fields are applied except for the avatar field. i can't see the reason why.

forms

class UserEditForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'name', 'email', 'bio', 'avatar']
        exclude = ()
        widgets = {
            'avatar': forms.FileInput(),
            'bio': forms.Textarea(),
        }

views

@login_required(login_url='login')
def edit_profile(request):
    user = request.user
    form = UserEditForm(instance=user)

    if request.method == 'POST':
        form = UserEditForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            form.save()
            return redirect('get_author', pk=user.id)
    return render(request, 'account/edit_profile.html', {'form': form})

template

<form class="form-horizontal" role="form" method="POST" action="">
                {% csrf_token %}

                <div class="col-md-3">
                    <div class="text-center">
                        <img src="{{ request.user.avatar.url }}" class="avatar img-circle" alt="avatar"
                             style="width: 100px; height: 100px;">
                        <h6>Upload a different photo...</h6>
                        {{ form.avatar }}
                    </div>
                </div>

... other fields

thanks for ur help

CodePudding user response:

You need to specify an enctype="…" attribute [mozilla-dev] of the form: this explains how the files will be encoded:

<form enctype="multipart/form-data" class="form-horizontal" role="form" method="POST" action=""></form>

CodePudding user response:

You need to update the template code and use the 'multipart/form-data' in you form tag to upload the files as part of you request object.

<form class="form-horizontal" role="form" method="POST" action="" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="col-md-3">
                    <div class="text-center">
                        <img src="{{ request.user.avatar.url }}" class="avatar img-circle" alt="avatar"
                             style="width: 100px; height: 100px;">
                        <h6>Upload a different photo...</h6>
                        {{ form.avatar }}
                    </div>
                </div>
</form>
  • Related