Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

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

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')
question from:https://stackoverflow.com/questions/65841863/why-the-image-doesnt-save-on-my-code-and-just-saved-by-admin-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...