profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Sunday, July 22, 2018

Django dyanimic url for employees or users

Let us say you are creating a site and you want your users to sign up and you want them to redirected once they log in. Below are some url formats for some well known sites.
linkedin
https://www.linkedin.com/in/<username>/
facebook
https://www.facebook.com/<username>/
How can we do that?
It is extremely inefficient to have an html page created for each user and it is a very heavy load on your site.
How to achieve this?
By default django and allauth redirect the logged in user to domain/profile so let us use that to do some magic. Here is my urls.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.contrib import admin
from django.urls import path, include
from . import views as core_views
from stars import views as star_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', core_views.welcome, name="welcome"),
    path('settings/', core_views.settings, name='settings'),

    # allauth
    path('accounts/', include('allauth.urls')),

    # stars
    path('profile/', star_views.profile, name="profile"),
    path('<slug:pid>/', star_views.rprofile, name='rprofile'),
]

Concentrate on the line 15,16. So I am letting the django/allauth redirect the url to domain/profile.html and then use the star_views.profile to redirect the request to star_views.rprofile and that is done like this

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect
##Create your views here.

def profile(request):
    site = 'http://127.0.0.1:8000'
    username = request.user.username
    url = f'{site}/{username}'
    return HttpResponseRedirect(url)

def rprofile(request, pid):
    u = User.objects.get(username=pid)
    if u:
        return render(request, 'profile.html')

Now every user has his own url which will be easy to share.