Note that there are some explanatory texts on larger screens.

plurals
  1. POGet user from URL segment with Django
    primarykey
    data
    text
    <p>I have a web application which will return a user id based on the first segment of the url, much like Twitter:</p> <p><a href="http://www.myapplication.com/user-name-goes-here/" rel="nofollow noreferrer">http://www.myapplication.com/user-name-goes-here/</a></p> <p>It can go deeper too, like so:</p> <p><a href="http://www.myapplication.com/user-name-goes-here/news/article_1/" rel="nofollow noreferrer">http://www.myapplication.com/user-name-goes-here/news/article_1/</a></p> <p>In order to break the site down, I am using the following URL routing technique:</p> <pre><code>(r'^(?P&lt;slug&gt;\w+)/', include('myapp.sites.urls')), </code></pre> <p>This will then further route the user to the correct page, but as it stands I am having to query the database in every view in order to obtain the user_id based on the first url segment. I was hoping to somehow automate this so I don't have to bloat my views with the same code each time... my solution was to create some middleware which checks the url segment and returns a 404 if its not found:</p> <pre><code> from django.http import Http404 class DomainMiddleware(object): def process_request(self, request): from myapp.sites.models import Sites dname = request.path.split('/')[1] if not dname: return try: d = Sites.objects.get(domain__exact=dname) except Sites.DoesNotExist: raise Http404 return </code></pre> <p>This works, but it's trying to parse EVERY request, even those to images, favicons etc. </p> <p>My question is thus; Is there a way to run this query on every page load without clogging up my views with extra code? If middleware is the solution, how can I modify my code so that it doesn't include EVERY request, only those to successfully routed URLs?</p> <p>Hope someone can help!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload