为什么图片不保存在我的代码中,而是仅通过管理页面保存? [英] why the image doesn't save on my code and just saved by admin page?

查看:49
本文介绍了为什么图片不保存在我的代码中,而是仅通过管理页面保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道为什么图像没有保存在路径中.我从路径中检查了一下,静态根目录和媒体根目录似乎都可以正常工作,但是图像无法保存,这是您可以查看所发生情况的代码:

I need to know why the images don't save in the path. I checked from the path and both of static root and media root seems to work good but the image doesn't save, here is the code where you can see what's happening:

通知:该图像工作正常,并且已通过管理页面安装,但无法保存或无法通过我的代码使用.

notice: the image works fine and has installed by admin page but doesn't save or work by my code.

models.py

models.py

class Product(models.Model):
    ...
    image = models.ImageField(upload_to='img/', blank=True)

    def save(self, *args, **kwargs):
        if not self.image:
            self.image = 'empty.jpg'
        super().save(*args, **kwargs)

settings.py

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/img/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'img')

通常在项目中存在的

urls.py

urls.py that exists in the project generally

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

views.py

@login_required(login_url=reverse_lazy('accounts:login'))
def createProduct(request, slug=None):
    user = User.objects.get(slug=slug)
    if user.user_admin:
        form = CreateProduct(None)
        if request.method == 'POST':
            form = CreateProduct(request.POST, request.FILES or None)
            if form.is_valid():
                Product.objects.create(
                    user=request.user,
                    name=form.cleaned_data['name'],
                    price=form.cleaned_data['price'],
                    digital=form.cleaned_data['digital'],
                    image=form.cleaned_data['image']
                )
                return redirect('store:store')
        return render(request, 'store/create_product.html', {'forms': form})
    else:
        raise ValueError('You have no perm to make something here')

推荐答案

请确保您将上传文件绑定到您的模板中的表单中.确保您的表单如下所示.

Make sure you are binding upload files to your form in your template. Make sure your form looks like this.

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

有关更多详细信息,请访问

For more detail visit django docs here.

这篇关于为什么图片不保存在我的代码中,而是仅通过管理页面保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆