Execute code in Django after response has been sent to the client

The method I am going for at the moment uses a subclass of HttpResponse: from django.template import loader from django.http import HttpResponse # use custom response class to override HttpResponse.close() class LogSuccessResponse(HttpResponse): def close(self): super(LogSuccessResponse, self).close() # do whatever you want, this is the last codepoint in request handling if self.status_code == 200: print(‘HttpResponse successful: … Read more

Django : How can I see a list of urlpatterns?

If you want a list of all the urls in your project, first you need to install django-extensions You can simply install using command. pip install django-extensions For more information related to package goto django-extensions After that, add django_extensions in INSTALLED_APPS in your settings.py file like this: INSTALLED_APPS = ( … ‘django_extensions’, … ) urls.py … Read more

Django – after login, redirect user to his custom page –> mysite.com/username

A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request. Suppose: LOGIN_REDIRECT_URL = ‘/profiles/home’ and you have configured a urlpattern: (r’^profiles/home’, home), Then, all you need to write for the view home() is: from django.http import HttpResponseRedirect from django.urls … Read more

How to use permission_required decorators on django class-based views

There are a few strategies listed in the CBV docs: Decorate the view when you instantiate it in your urls.py (docs) urlpatterns = [ path(‘view/’,login_required(ViewSpaceIndex.as_view(..)), … ] The decorator is applied on a per-instance basis, so you can add it or remove it in different urls.py routes as needed. Decorate your class so every instance … Read more

Django optional url parameters

There are several approaches. One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)? Making a Regex Django URL Token Optional Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view. urlpatterns = patterns(”, url(r’^project_config/$’, views.foo), url(r’^project_config/(?P<product>\w+)/$’, views.foo), url(r’^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$’, views.foo), ) Keep in mind … Read more