Jazi
Jazi

Reputation: 6752

Django image uploading

I have a problem with image uploading. For now, chosen image file is not copied to destination directory and path to this file is not added to database.

I'm giving my code below:

models.py:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(upload_to="avatar/")

form.py

class ProfileEditionForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ('user')

view.py:

def index(request):
    if request.user.is_authenticated():
        user = User.objects.get(pk=request.user.id)

        if request.method == "POST":
            form = ProfileEditionForm(request.POST, request.FILES, instance=user)

            if form.is_valid():
                form.save()
                #return HttpResponseRedirect(reverse('profile_edit'))
        else:
            form = ProfileEditionForm(instance=user)

        return direct_to_template(request, 'profile_edit.html', { 'form' : form })
    else:
        return HttpResponseRedirect(reverse('main_page'))

Thanks in advance for help.

Upvotes: 1

Views: 2184

Answers (2)

ftartaggia
ftartaggia

Reputation: 541

your ModelForm is bound to UserProfile model, but your are instantiating it with instance=user.

PS: request.user is User.objects.get(pk=request.user.id)

Upvotes: 1

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11046

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

your form should have the enctype="multipart/form-data" or request.FILES won't have any data stream associated

Upvotes: 2

Related Questions