Reputation: 441
I'm facing some trouble to pass variables trough templates/URL/view in my index.html.
This is my URLs:
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('django.contrib.auth.urls')),
path('', include('dma.urls')),
]
app_name = 'root'
urlpatterns = [
path('<int:category_id>', views.index, name='index'),
path('buy/', views.buy, name='buy'),
path('sell/', views.sell, name='sell'),
path('stock/', views.stock, name='stock'),
path('debtor/', views.debtor, name='debtor'),
path('debtor/<str:buyer>', views.debt, name='debt'),
path('financial/', views.financial, name='financial'),
]
My view:
def index(request, category_id):
products = Buy.objects.filter(sell__buyer__isnull=True)
categories = Category.objects.all()
context = {'products': products, 'categories': categories}
return render(request, 'index.html', context)
My template:
{% for category in categories %}
<a href="{% url 'root:index' category.id %}" class="list-group-item">{{ category.name }}</a>
{% endfor %}
I'm not sure but the problem might be in URL code. The template is printing exactly the categories names in the {{ category.name }}
Error:
Using the URLconf defined in home.urls, Django tried these URL patterns, in this order:
admin/
users/
<int:category_id> [name='index']
buy/ [name='buy']
sell/ [name='sell']
stock/ [name='stock']
debtor/ [name='debtor']
debtor/<str:buyer> [name='debt']
financial/ [name='financial']
^media/(?P<path>.*)$
The empty path didn't match any of these.
EDIT -> maybe the problem is: the index can work without requesting the variable 'category_id'. In this way, should I have 2 URLs like these:
path('', views.index, name='index'),
path('<int:category_id>/', views.index, name='index'),
Upvotes: 0
Views: 1892
Reputation: 441
I discovered what it was wrong. Two modifications:
URL (two paths for the same view -> index):
app_name = 'root'
urlpatterns = [
path('', views.index, name='index'),
path('<int:category_id>', views.index, name='index'),
VIEWS (set 'category_id' as a default value):
def index(request, category_id=''):
products = Buy.objects.filter(sell__buyer__isnull=True)
if category_id != '':
products = products.filter(category=category_id)
categories = Category.objects.all()
context = {'products': products, 'categories': categories,
'category_id': category_id}
return render(request, 'index.html', context)
Thank you for sharing different ideas!
Upvotes: 2