![](/img/trans.png)
[英]A 404 error if slug begins with “id-” on multilingual website with Indonesian language in Django 3.0
[英]When I change the language of the website, the slug is not translated causing a 404 error
我是 Django 的新編程人員。 我目前正在為我的第一個項目使用 2.2 版。
到目前為止一切順利,我的網站包含一個帶有產品目錄的登錄頁面,該目錄必須使用兩種語言:英語和西班牙語。
我的問題是,當我嘗試將 URL 從英語更改為西班牙語或從西班牙語更改為英語時,我收到 404 錯誤,因為產品 slug 沒有被翻譯。
讓我解釋。 對於一個產品,我有一個 URL 結構,英文為:mywebsite.com/products_en/item-name_en 西班牙語為:mywebsite.com/products_es/item-name_es
只要相應的語言處於活動狀態,這兩個鏈接都可以正常工作。 問題是,例如,如果我在英文產品頁面上並嘗試切換到西班牙文頁面,它會嘗試將我帶到 mywebsite.com/products_es/item-name_en
我知道這個問題已經在 Stack Overflow 上被問過,但答案並沒有讓我找到解決方案
我怎樣才能避免這種情況? 先感謝您。
這是我的 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')),
]
我的 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)
我的產品目錄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,} )
我的產品目錄 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 是自動生成的,因為我使用 django-modeltranslation
好的,@Lau,我認為這篇文章將幫助您解決您的問題:
Django 模型翻譯 slug 問題。 當我更改語言時不要 go 對 url
我還認為蛞蝓應該是 static 而不是如上面鏈接中的評論中指出的那樣翻譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.