shweta
shweta

Reputation: 33

How to display the edited profile picture in django

I am able to upload the profile picture but i am not able edit it

I have the form populating with the image browse option, but when I click save, it doesn't actually update in template. but it is working fine in admin

views.py

def create_form(request):
        form = AlbumForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            album = form.save(commit=False)
            album.user = request.user
            album.image= request.FILES['image']
            album.save()
            return render(request, 'about.html', {'album': album})
        context = {
            "form": form,
        }
        return render(request, 'create_form.html', context)

def profile_edit(request):
    if request.method == 'POST':
        form = AlbumForm(request.POST, instance=request.user.album)
        if form.is_valid():
            album = form.save(commit=False)
            album.user = request.user
            form.save()
            return redirect(reverse('about'))
    else:
        form = AlbumForm(instance=request.user.album)
        args = {'form': form}
        return render(request, 'profile_edit.html', args)

models.py

class Album(models.Model):
    user = models.OneToOneField(User)
    image = models.FileField()

forms.py

class AlbumForm(forms.ModelForm):
    class Meta:
        model = Album
        fields = ['image']

profile_edit.html

{%  extends 'base.html' %}
{%  block   content %}

<form action="{% url 'profile_edit' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">save</button>
</form>
<div>
      <img src="{{ user.album.image.url }}" class="img-responsive">
</div>

{%  endblock    %}

Upvotes: 2

Views: 922

Answers (3)

itzMEonTV
itzMEonTV

Reputation: 20349

Try this

AlbumForm(request.POST, request.FILES, instance=request.user.album)

Upvotes: 2

Mubariz Feyziyev
Mubariz Feyziyev

Reputation: 412

If you upload file you must use request.Files read for more info this link

https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/#basic-file-uploads

Upvotes: 0

slurms
slurms

Reputation: 768

You need to add request.FILES to your AlbumForm in the profile edit view.

Upvotes: 0

Related Questions