Search code examples
pythondjangourlconf

Remove a part of url address in Django


I'm developing a multilingual web page.

url.py

urlpatterns = patterns('',
     url(r'^$', 'mysite.views.home', name='home'),
     url(r'^(?P<lang>\w{2})/$', 'mysite.views.home')
     url(r'^admin/', include(admin.site.urls)),
)

views.py

def home(request,lang='fa'):
    language_mapping = {'en': 'en', 'ar': 'ar'}
    selected_lang = language_mapping.get(lang, 'fa')
    return render_to_response('index.html',{'lang':selected_lang})

In my html I have some <img> tags

<img src="media/image.jpg" alt="">

The problem is if I run my address like mysite.com, I can see the image but address like these

mysite.com/fa/
mysite.com/en/
mysite.com/ar/

make my image goes away as it make my address like mysite.com/en/media/image.jpg

So How can I remove /lang/ part from my address in <img> tags?

Something like this maybe?

url(r'^(?P<lang>\w{2})/media' = r'^/media/' )

I have no idea where to do this.


Solution

  • Two things:

    1. You can change the 'media/img.jpg' to '/media/img.jpg' (note the leading slash) to make it a root-relative url -- thus making it always request mysite.com/media/img.jpg instead of attaching the lang tag.

    2. You can switch to using Django's static file management which is probably a better idea in the long run anyway.