I'm new programming with Django. I'm currently using version 2.2 for my first project.
So far it's going well, my website consists of a landing page with a product catalog which has to work in two languages: English and Spanish.
My problem is that when I try to change a URL from English to Spanish or from Spanish to English, I get a 404 error because the product slug does not get translated.
Let me explain. For a product, I have a URL structure in English: mywebsite.com/products_en/item-name_en In Spanish, it would be: mywebsite.com/products_es/item-name_es
Both links work well, as long as the corresponding language is active. The problem is that, for example, if I am on the English product page and try to switch to the Spanish page, it tries to take me to mywebsite.com/products_es/item-name_en
I know this question has been already asked here on Stack Overflow but the answers didn't get me to the solution
How can I avoid this? Thank you in advance.
Here's my urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
path('',include('landing_page.urls')),
path('',include('products_catalog.urls')),
]
My products_catalog urls.py
from django.urls import include, path
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.utils.translation import gettext_lazy as _
from . import views
app_name = 'catalog'
urlpatterns = [
path(_('products'), views.products, name='products'),
path(_('products/<slug:product_slug>'), views.product_detail, name='product-detail'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My products_catalog views.py
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from .models import *
def products(request):
products_list = product.objects.all()
return render(request, 'products_catalog/products.html', {'products': products_list,})
def product_detail(request, product_slug):
product = get_object_or_404(product, slug=product_slug)
return render(request, 'products_catalog/product.html', {'product': product,} )
My product_catalog models.py
class product(models.Model):
name = models.CharField(_("Name"),max_length=100, unique=True)
description = models.TextField(_("Description"), max_length=2000)
features = models.TextField(_("Features"), max_length=10000, null=True, blank=True)
slug = models.SlugField("Slug", null=True, blank=True)
def save(self, *args, **kwargs):
if not self.id:
self.slug_es = slugify(self.name_es)
self.slug = slugify(self.name)
super(product, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = _("Product")
verbose_name_plural = _("Products")
slug_es was automatically generated because I use django-modeltranslation