0

I want to have vanity urls in my django application i.e. user's profile at url like example.com/username . I tried to do it like shown:

urlpatterns = patterns('',

    #sitemap generation
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'),
    url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
    url(r'^admin/', include(admin.site.urls)),

    ..other urls

    #User Profile URLs
    url(r'^(?i)(?P<username>[a-zA-Z0-9.-_]+)$','myapp.views.user_profile',name='user-profile'),
   )

As url pattern for vanity urls is at last in urlpatterns so django should match it at the last. But even though its conflicting with the admin urls and user_profile view renders 'example.com/admin' url instead of default.What's the best way of ensuring that vanity-urls do not clash with any of the django-urls ? Is there anyway to write regex such that it excludes the set of existing urls of the django application.

Ashish Gupta
  • 2,574
  • 2
  • 29
  • 58
  • It doesn't look like the URLs are conflicting. Is one of your usernames `admin`? That would be conflicting! It's common practice to use different namespaces for different apps, see `^admin/` as prefix for the whole admin-app. You could go with something like `^profile/(?P[a-zA-Z0-9.-_]+)$` for your profile-view. – Mischback Aug 01 '15 at 07:40
  • Ideally you would have a list of usernames which are not allowed in the system. For example do you want a standard user of the site calling themselves 'admin', or 'blog'? – Matt Seymour Aug 01 '15 at 08:10
  • @Mischback I have no user with name admin and I want urls like '^(?P[a-zA-Z0-9.-_]+)$' as we have in twitter, facebook. And Isn't django will match urlpattern from top to bottom ? In that case there should resolve `/admin` url using admin app views – Ashish Gupta Aug 01 '15 at 08:36
  • Yes @MattWritesCode u are correct.I will keep a list of reserved usernames. I have read about it [here](http://www.quora.com/How-do-sites-prevent-vanity-URLs-from-colliding-with-future-features) But I have problem in defining url patterns. Can u suggest ideal way of writing urlpatterns ? – Ashish Gupta Aug 01 '15 at 08:41
  • 1
    Does `example.com/admin/` (_with_ trailing slash) work as expected? – knbk Aug 01 '15 at 09:37
  • @knbk I am using this [middleware](https://gist.github.com/Sepero/2204099) to remove trailing slash. I think thats causing problem here – Ashish Gupta Aug 01 '15 at 10:13

1 Answers1

1

Your middleware redirects /admin/ to /admin. This does not match the regex for the admin, only for your user profile. With this middleware you cannot reach the admin index page.

One solution is to only redirect if the old path, with slashes, is invalid and the new one is valid.

knbk
  • 52,111
  • 9
  • 124
  • 122