The problem of using the Arabic language in django links

39 Views Asked by At

I am programming a website in Django I want to put the Arabic language in my link, but when I make the link in Arabic and when I choose it, it takes me to the page page not found Note: This only happens on the hosting server, meaning it does not happen on localhost

urls.py
from django.urls import path, re_path
from . import views

urlpatterns = [
    # pages
    path('',views.index,name='index'),
    path('الصفحة/',views.listArticle,name='listArticle'),
    path('TravelTips/',views.TravelTips,name='TravelTips'),
    # view article 
    path('الصفحة/<str:slug_url>/', views.view_article, name='Page_Article'),
    path('TravelTips/<str:slug_url>/',views.view_article,name='Page_Article'),
,]

I expected that the problem was in the slug, but it turned out that Django in general did not accept Arabic letters

1

There are 1 best solutions below

0
Samuel On

When using Django to handle Arabic language in URLs or links, there are a few considerations to keep in mind to ensure proper functionality and compatibility.

  1. URL Encoding: URLs can only contain ASCII characters, and non-ASCII characters (such as Arabic letters) need to be encoded. Django provides the urlquote function to properly encode non-ASCII characters for URLs. Here's an example:
from django.utils.http import urlquote

arabic_text = "مرحبا"
encoded_text = urlquote(arabic_text)
# Output: '%D9%85%D8%B1%D8%AD%D8%A8%D8%A7'
  1. Localization Middleware: Django's LocaleMiddleware should be enabled in your project's middleware settings. This middleware handles language preferences, including Arabic, based on the user's browser settings.

  2. Language and Locale Configuration: In your Django project settings, make sure to set the appropriate language and locale settings. This includes specifying the LANGUAGE_CODE and LOCALE_PATHS. For Arabic, the LANGUAGE_CODE would be 'ar' for Modern Standard Arabic or 'ar-xx' for a specific Arabic variant (e.g., 'ar-sa' for Saudi Arabian Arabic).

  3. URL Patterns and Views: When defining URL patterns in your Django urls.py file, you can include parameters that capture the Arabic text as variables in the URL. For example:

from django.urls import path
from . import views

urlpatterns = [
    path('arabic/<str:arabic_text>/', views.arabic_view, name='arabic-url'),
]

In your view function arabic_view, you can access the captured Arabic text as a parameter.

It's important to note that while Django supports Arabic language handling, it's still crucial to ensure the proper configuration of your web server, database, and client-side settings to handle Unicode and text directionality correctly.