Проблемы с загрузкой Django ImageField

У меня есть вопрос, я написал кусок кода Djnago, чтобы загрузить изображение профиля для пользователя, из админки модель работает нормально, но с самого сайта изображение не может быть загружено, кажется, что код даже не вызывается. Вот мой код, не могли бы вы проверить и сказать мне, что может быть не так?

модели.ру:

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)

формы.py:

from django import forms
from .models import ProfilePicture

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

просмотров.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)

URL.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 в шаблоне является формой django по умолчанию.

Заранее спасибо :)


person Tadas    schedule 09.11.2015    source источник
comment
Вы включили enctype="multipart/form-data"?   -  person Wtower    schedule 09.11.2015
comment
Где я должен включить это? В формах.py? Мне нужно что-то импортировать, чтобы использовать его?   -  person Tadas    schedule 09.11.2015


Ответы (1)


Полезной частью документации является "Привязка загруженных файлов к форме". . Возможно, если вы будете следовать этому, вы преодолеете свою проблему.

Помимо прочего, важно включить этот атрибут в элемент формы:

<form method="post" action="..." enctype="multipart/form-data">
person Wtower    schedule 09.11.2015