why the image doesn't save on my code and just saved by admin page?

£可爱£侵袭症+ 提交于 2021-02-11 14:56:30

问题


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

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

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

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')

回答1:


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.



来源:https://stackoverflow.com/questions/65841863/why-the-image-doesnt-save-on-my-code-and-just-saved-by-admin-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!