Django上传的图片未显示

时间:2013-10-28 21:11:12

标签: django image-uploading

显示通过表单上传的图片时出现问题。以下是相关部分:

models.py

def get_uplaod_file_name(instance,filename): #rename the uploaded file
    return 'uploaded_files/%s_%s' % (str(time()).replace('.','_'), filenam

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=30)
    occupation = models.CharField(max_length=50)
    city = models.CharField(max_length=30)
    thumbnail = models.FileField(upload_to=get_uplaod_file_name)

fomrs.py

class UserProfileForm(forms.ModelForm):

    class Meta:
        model= UserProfile
        fields = ( 'name', 'occupation', 'city', 'thumbnail')

views.py

@login_required
def user_profile(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, 
                               instance=request.user.profile)
        if form.is_valid():
            form.save()
            message = 'Your profile is updated!'
            return render_to_response('home.html',{'message':message}, 
                                      context_instance=RequestContext(request))

在模板中,而不是我得到的完整图像路径:

<img src="/static/assets/uploaded_files/" width="200" />

将图像文件正确上载到静态文件夹。所以我真的很困惑,并欣赏你的提示。

1 个答案:

答案 0 :(得分:2)

您的模板是否包含以下内容?

{% load staticfiles %}

您是否在settings.py中定义了静态文件夹?

STATICFILES_DIRS = (
    'filepath/to/folder'
)

尝试加载像这样的图片

<img src="{% static "/static/assets/uploaded_files/" %}" width="200" />