从多个路径在Django中提供图像

时间:2013-09-09 21:28:29

标签: django django-templates

我正在使用django package sorl缩略图来处理图像。

settings.py中的配置为:

MEDIA_ROOT = '/home/hammad/virt_env/virt1/gccFishing/media'
MEDIA_URL = '/media/'

我有两条路径上传的图片,问题是第一条路径的图片只会呈现给模板。

这是我的第一条工作正常的道路。

  • 用户个人资料照片,正在/gccFishing/media/Images/上传,并使用此代码呈现给模板
  

{%thumbnail user.image“50x50”crop =“center”as im%}

 <img src="{{im.url}}" width="{{ im.width }}" height="{{ im.height }}">    
     

{%endthumbnail%}

这是我上传图片但未呈现给模板的第二条路径。

  • 图片上传路径为/gccFishing/media/Images/WallImages。我使用此代码将它们呈现为模板:
  

{%thumbnail post.image“150x150”crop =“center”as im%}

 <img scr="{{im.url}}" width="{{im.width}}" height="{{im.height}}"></a>
     

{%endthumbnail%}

此外,当我尝试访问{{post.image.url}}

我收到此错误:

The 'image' attribute has no file associated with it

有什么想法吗?

models.py

class Wallpost(models.Model):

    author = models.ForeignKey(User)
    posted_on = models.DateTimeField(auto_now_add = True)
    points = models.IntegerField(default = 0, validators = [MaxValueValidator(100)])    # relate this to user reputation    
    #location
    #spot

    image = ImageField(upload_to = Imagepost_path, null = False, blank = True

views.py

class Wallview(View):


    def get(self, request, *args, **kwargs):    
        context = self.get_context_data()
        return render_to_response('wall.html', context, RequestContext(request))


    def post(self, request, *args, **kwargs):

        image = request.FILES.get('image', None)
        text = request.POST.get('text', None)
        user = request.user
        try:
            wallpost = Wallpost.objects.create(text = text, image = image, author = user)
            return HttpResponseRedirect('')
        except:
            return  HttpResponse('You should login to post')



def get_context_data(self, **kwargs):
            context = {}
            try:
                posts = Wallpost.objects.order_by('-posted_on')[:20]    
            except Wallpost.DoesNotExist:
                posts = None
            context['posts'] = posts
        return context

1 个答案:

答案 0 :(得分:0)

使用ModelForm处理文件的get和post。然后,您只需要一个视图方法,而不是get()和post()。 :

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import YourModelForm

def upload_file(request):
    if request.method == 'POST':
        form = YourModelForm(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = YourModelForm()
    return render(request, 'upload.html', {'form': form})

为您处理保存正确对象的所有逻辑。我怀疑你没有在WallPost图像中保存正确的对象类型。