0

I have a question, I wrote peace of Djnago code, to upload profile picture for user, from admin area model works fine, but from website itself image cannot be uploaded, it seems that code is not even being called. Here is my code, could you check and tell me what might be wrong?

models.py:

from django.conf import settings
from django.db import models
from django.core.files import File

def upload_location(instance, filename):
    location = str(instance.user.id)
    return "%s/%s" %(location, filename) 

class ProfilePicture(models.Model):
    user = models.ForeignKey(User)
    profile_picture = models.ImageField(upload_to=upload_location, null=True, blank=True)

    def __unicode__(self):
        return unicode(self.user.id)

forms.py:

from django import forms
from .models import ProfilePicture

class ProfileEditPicture(forms.ModelForm):
    class Meta:
        model = ProfilePicture
        fields = [
        "profile_picture"
        ]

views.py:

from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404, render_to_response
rom .forms import ProfileEditPicture
from .models import ProfilePicture

@login_required()
def profile_picture(request, id):
    user = get_object_or_404(User, id=id)
    title = "Profile Edit"
    profile, created = Profile.objects.get_or_create(user=user)
    form = ProfileEditPicture(request.POST, request.FILES)
    if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
    context = {
        "form":form,
        "title":title,
        "profile":profile
    }
    return render(request, "profile/form.html", context)

urls.py:

urlpatterns = [
    ...
    url(r'^profile_picture/(?P<id>[\w.@+-]+)/', 'profiles.views.profile_picture', name='profile_picture'),
    ...
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

HTML code in template is default django form.

Thanks in advance :)

pnuts
  • 58,317
  • 11
  • 87
  • 139
Tadas
  • 29
  • 5

1 Answers1

1

A useful piece of documentation is "Binding uploaded files to a form". Possibly if you follow this you will overcome your issue.

Among other things, it is important that include this attribute in your forms element:

<form method="post" action="..." enctype="multipart/form-data">
Wtower
  • 18,848
  • 11
  • 103
  • 80