0

I've a model called: "Sample", It reference my Sample products. I want to show all my Samples in a page: shop/muestras.html or:

http://127.0.0.1:8000/muestras

This model has a ForeignKey reference to my Category model. I use this field called category to filter all the samples by doing:

c_slug = 'muestras'

muestras = Sample.objects.filter(category__slug=c_slug)

I could also just do:

muestras = Sample.objects.all()

Becuase all my samples have that category 'muestras'. Either way my Samples are not been shown.

However, If I filter my other model Products by it's category's slug 'muestras' all the items with this category are shown:

muestras = Product.objects.filter(category__slug=c_slug)

Just to be sure, I've tested filtering the Sample model in Shell and I'm getting the expected objects:

from shop.models import Sample

samples = Sample.objects.filter(category__slug = 'muestras')
samples
<QuerySet [<Sample: Cinta de embalaje personalizada de muestra>, <Sample: Etiquetas personalizadas de muestra>, <Sample: Imanes personalizados de muestra>, <Sample: Paquete d
e muestra>, <Sample: Stickers personalizados de muestra>]>

What could be wrong?

views.py:

def SamplePackPage(request):
# La categoria es necesaria para mostrar el video de c/categoria

categoria_muestras = Category.objects.get(slug='muestras')

# Productos que pertenecen a la categoria muestras

c_slug = 'muestras'
# muestras = Sample.objects.all()
#
muestras = Sample.objects.filter(category__slug=c_slug)
#
# muestras = Product.objects.filter(category__slug=c_slug)

return render(request, 'shop/muestras.html', {'categoria_muestras': categoria_muestras,
                                              'muestras':muestras})

models.py:

class Category(models.Model):
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='category', blank=True)
    video = EmbedVideoField()

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def get_url(self):
        return reverse('shop:allCat', args=[self.slug])

    def __str__(self):
        return '{}'.format(self.name)


class Product(models.Model):
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='product', blank=True)
    stock = models.IntegerField()
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'product'
        verbose_name_plural = 'products'

    def get_url(self):
        return reverse('shop:ProdDetail', args=[self.category.slug, self.slug])

    def __str__(self):
        return '{}'.format(self.name)



### Sample Packs ###

class Sample(models.Model):
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.IntegerField(default=1)
    image = models.ImageField(upload_to='product', blank=True)
    stock = models.IntegerField()
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'sample'
        verbose_name_plural = 'samples'

    def get_url(self):
        return reverse('shop:ProdDetail', args=[self.category.slug, self.slug])

    def __str__(self):
        return '{}'.format(self.name)

urls.py:

app_name = 'shop'

urlpatterns = [

    path('admin', admin.site.urls),
    path('', views.allCat, name='allCat'),
    path('<slug:c_slug>', views.ProdCatDetail, name='ProdCatDetail'),
    path('<slug:c_slug>/<slug:product_slug>', views.SamplePack, name='SamplePack'),
    path('muestras', views.SamplePackPage, name='SamplePackPage'),
    path('<slug:c_slug>/<slug:product_slug>/medida-y-cantidad', views.StepOneView.as_view(), name='ProdDetail'),
    path('<slug:c_slug>/<slug:product_slug>/subir-arte', views.StepTwoView.as_view(), name='UploadArt'),
    path('province/', views.get_province, name='province'),
    path('district/', views.get_district, name='district'),
    path('quienes_somos/', views.quienes_somos, name='quienes_somos'),
]

project's urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    # path('', views.index, name = 'index'),
    path('', include('shop.urls')),
    path('cart/', include('cart.urls')),
    path('order/', include('order.urls')),
    path('account/create/', views.signupView, name = 'signup'),
    path('account/login/', views.signinView, name = 'signin'),
    path('account/logout/', views.signoutView, name = 'signout'),
    path('province/', views.get_province, name = 'province')
]

html:

{% extends 'base.html' %}
{% load staticfiles %}
{% load embed_video_tags %}
{% block metadescription %}
    {% if category %}
        {{ category.description|truncatewords:155 }}
    {% else %}
        Welcome to the Cushion Store
    {% endif %}
{% endblock %}
{% block title %}
    {% if category %}
        {{ category.name }} - Perfect Cushion Store
    {% else %}
        See Our Cushion Collection - Perfect Cushion
    {% endif %}
{% endblock %}

{% block content %}





    <div class="my_header_samples">

        <br>
        <br>
        <br>
        <div class="container">
            <p class="my_samples_title">Paquete de muestras a S/10</p>
            <p>192 reviews<i class="gold-star fas fa-star-half-alt"></i>
                <i class="gold-star fas fa-star-half-alt"></i>
                <i class="gold-star fas fa-star-half-alt"></i>

            </p>

            <div class="row">

                <div class="text-center">
                    <a href="{% url 'shop:SamplePack' 'muestras' 'sample-pack' %}"
                    class="btn btn-azul text-white btn-block">Agregar al carrito</a>
                </div>

            </div>

        </div>
    </div>

    <br>
    <br>


    <div class="container">

    <br>
    <br>
    <br>

    <p class="my_samples_subtitle text-center">O también puedes obtener tus muestras con tu diseño personalizado.</p>

    <br>


        <div class="row col-md-12">
            {% for muestra in muestras %}
                <div class="col-md-3">
                    <div class="text-center">
                        <a href="{{muestra.get_url }}"><img class="my_image_medium"
                                                             src="{{ muestra.image.url }}"
                                                             alt="{{ muestra.name }}"></a>
                    </div>
                    <p class="text-center">{{ muestra.name }}</p>
                </div>
            {% endfor %}
        </div>

    <br>
    <br>

                <div class="row col-md-12">

                <p class="text-center">

                    {% video categoria_muestras.video as my_video %}

                    {% video my_video "medium" %}
                    {% endvideo %}

                </p>

                </div>


    </div>

    <br>
    <br>

{% endblock %}
4
  • What is happening when you browse to that page? Is it erroring or showing an empty list? Commented Feb 2, 2019 at 15:49
  • Also, please show shop/muestras.html Commented Feb 2, 2019 at 15:52
  • @schillingt updated muestras.html. It just appears empty. But when in the same view I filter for the other model Product I see the products (I've to change the products item category's slug to 'muestras' for them to show). Commented Feb 2, 2019 at 15:56
  • @schillingt if I comment all the code in that page, it still renders... why? Commented Feb 2, 2019 at 16:02

1 Answer 1

1

I think the problem is your shop/urls.py file. You need to arrange it so that the more specific urls are caught first, then the more generic ones later.

urlpatterns = [
    path('admin', admin.site.urls),
    path('', views.allCat, name='allCat'),
    path('muestras', views.SamplePackPage, name='SamplePackPage'),
    path('province/', views.get_province, name='province'),
    path('district/', views.get_district, name='district'),
    path('quienes_somos/', views.quienes_somos, name='quienes_somos'),
    path('<slug:c_slug>/<slug:product_slug>/medida-y-cantidad', views.StepOneView.as_view(), name='ProdDetail'),
    path('<slug:c_slug>/<slug:product_slug>/subir-arte', views.StepTwoView.as_view(), name='UploadArt'),
    path('<slug:c_slug>/<slug:product_slug>', views.SamplePack, name='SamplePack'),
    path('<slug:c_slug>', views.ProdCatDetail, name='ProdCatDetail'),
]

What's happening is that when you were browsing to /muestras/ it was catching on the ProdCatDetail url because it was higher up in the list and that muestras is a valid slug. If you are going to have dynamic urls at a root, you need to put them last in the list so that everything else can still be triggered.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.