0

我正在使用 django 包 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

有什么想法吗 ?

模型.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

)

视图.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
4

1 回答 1

0

使用 ModelForm 处理文件的获取和发布。然后,您也只需要一个视图方法,而不是 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 图像中保存正确的对象类型。

于 2013-09-10T01:28:45.800 回答