Hello progers !
I have products that I add through the admin panel, but how can I make sure that not all products are displayed on the site, but which I need?
I know that this can be passed through the “id” of the object, but I did not find information on how to pass the “id” to the views.py or template.
I display the product image model, but I need to display the image of the selected product id ?
Have you worked your way through either of the Django Tutorial or the Django Girls Tutorial? Both of those show how you can send ID references through urls on your site.
Thanks, Ken. I also tried to create a variable in views.py for each object and filter them through id = number, it helped, but on djangogirls something I did not see this
Well if you get stuck, feel free to post your models, urls and views here and we’ll see what we can do to help.
(When you post code here, please post it between lines consisting of only three backtick - ` characters. That means you would have one line of only ```, then your lines of code, finally one more line of ```. Make sure the lines of ``` are lines by themselves - not on the same line as other text. Also make sure you use the backtick - ` and not the apostrophe - ')
views.py ( I created products_2 and products_3 for other product objects, and I’m going to add 17 more objects in the admin panel … I’m sure there is an easier way)
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(id=4)
products_2 = Product.objects.filter(id=5)
products_3 = Product.objects.filter(id=6)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request,
'teddy/teddy.html',
{'category': category,
'categories': categories,
'products': products,
'products_2': products_2,
'products_3': products_3})
models.py:
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products',on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
#index_together = (('id', 'slug'),)
def __str__(self):
return self.name
urls.py(app):
urlpatterns = [
path('', views.main_page, name='main_page'),
path('buy', views.product_list, name='product_list'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py(project):
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('teddy.urls')),
path('buy', include('teddy.urls')),
]
admin.py:
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category, CategoryAdmin)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', 'price', 'stock', 'available', 'created', 'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'stock', 'available']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Product, ProductAdmin)
html(output image):
{% for product in products %}
<svg class='bag_1' class="bi bi-cart3" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill="white" d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .49.598l-1 5a.5.5 0 0 1-.465.401l-9.397.472L4.415 11H13a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l.84 4.479 9.144-.459L13.89 4H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm7 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/>
</svg>
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
</a>
</div>
{% endfor %}
/
views.py ( I created products_2 and products_3 for other product objects, and I’m going to add 17 more objects in the admin panel … I’m sure there is an easier way)
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(id=4)
products_2 = Product.objects.filter(id=5)
products_3 = Product.objects.filter(id=6)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request,
'teddy/teddy.html',
{'category': category,
'categories': categories,
'products': products,
'products_2': products_2,
'products_3': products_3})
models.py:
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products',on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
#index_together = (('id', 'slug'),)
def __str__(self):
return self.name
urls.py(app):
urlpatterns = [
path('', views.main_page, name='main_page'),
path('buy', views.product_list, name='product_list'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py(project):
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('teddy.urls')),
path('buy', include('teddy.urls')),
]
admin.py:
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category, CategoryAdmin)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', 'price', 'stock', 'available', 'created', 'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'stock', 'available']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Product, ProductAdmin)
html(output image):
{% for product in products %}
<svg class='bag_1' class="bi bi-cart3" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill="white" d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .49.598l-1 5a.5.5 0 0 1-.465.401l-9.397.472L4.415 11H13a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l.84 4.479 9.144-.459L13.89 4H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm7 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/>
</svg>
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
</a>
</div>
{% endfor %}
In short, I need the product id to be passed without creating a new variable in views.py
Have you actually worked your way through the tutorials mentioned above? This type of information is covered. (The general pattern here is that of a listing page with individual links to a detail page.)
(By working, I don’t mean just reading them or copy/pasting the examples into your editor. I mean actually typing in the examples and following along the steps to do the work, validating what you’re getting with what’s being explained. If you do this, you will see how those examples relate to what you’re trying to do here - and teach you a number of other valuable concepts as well.)