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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…