Django ImageField上传的问题

时间:2015-11-09 13:25:50

标签: python django upload imagefield

我有一个问题,我写了和平的Djnago代码,为用户上传个人资料图片,从管理区域模型工作正常,但从网站本身图片无法上传,似乎代码甚至没有被调用。这是我的代码,你能检查并告诉我可能出现的问题吗?

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代码是默认的django形式。

提前致谢:)

1 个答案:

答案 0 :(得分:1)

有用的文档是"Binding uploaded files to a form"。可能如果你遵循这个,你将克服你的问题。

除此之外,在表单元素中包含此属性非常重要:

<form method="post" action="..." enctype="multipart/form-data">