简体   繁体   中英

django update user form

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

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM