I am writing a small project on django with an app 'santechnic' and ran into a problem.to In which folder should I upload the images in the model Product so that the get request can find them?
santechnic/models.py
class Category(models.Model):
category_name = models.CharField(max_length=200, default="", primary_key=True)
category_image = models.ImageField(default="", upload_to='upload/images/categories')
class Product(models.Model):
product_name = models.CharField(max_length=200, primary_key=True)
length = models.FloatField(default=0.0)
width = models.FloatField(default=0.0)
height = models.FloatField(default=0.0)
product_image = models.ImageField(default="", upload_to=)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('santechnic/', include('santechnic.urls'))
]
santechnic/urls.py
app_name = "santechnic"
urlpatterns = \[
path('', views.CategoryView.as_view(), name='category'),
path('\<slug:category_name\>/', views.ProductsView.as_view(), name='products'),
path('\<slug:category_name\>/\<slug:product_name\>/', views.ProductDetailView.as_view(), name='detail'),
\]
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
santechnic/views.py
class CategoryView(generic.ListView):
template_name = 'santechnic/home.html'
context_object_name = 'category_list'
model = Category
class ProductsView(generic.ListView):
template_name = 'santechnic/products.html'
context_object_name = 'products_list'
model = Product
part of settings.py
MEDIA_URL = ''
MEDIA_ROOT = ''
Directory
I've tried generate path:
def generate_path(instance, filename):
return '%s/upload/images/products/' % instance.category.category_name
But I had exception SuspiciousFileOperation.
Also for example I manually add path 'toilets/upload/images/products' in upload_to and got "GET /santechnic/toilets/toilets/upload/images/products/1.png HTTP/1.1" 404 (here category_name='toilets').
If path is 'upload/images/products' I again get "GET /santechnic/toilets/upload/images/products/1.png HTTP/1.1" 404
Help me, please. How can I solve it?
CodePudding user response:
Did you install Pillow?
pip install pillow
maybe you should Google this and try.
CodePudding user response:
First of all, you don't need to create folder manually for to store images, when you write upload_to in model field, it will create media folder automatically inside your project.
In models.py:
product_image = models.ImageField(upload_to="images/") #after writing this, it will create media/images folder inside your project.
To display this on template:
<img src="/media/{{product_image}}" /> #here image will display.
Note: don't forget to add media url and media root in settings.py file.