Django, extract kwargs from url - django

Suppose I have a url pattern
url(r'^/my_app/class/(?P<class_id>\d+)/$', my_class.my_class, name='my_class')
For a given url
http://example.com/my_app/class/3/, I'd like to get class_id.
I can do this with regex myself.
I am wondering if there's a utility function for this since Django is already doing this to resolve url to a view.

There is an example of using resolve() function in Django docs. Value of next variable has HTTP url to be parsed with urlparse() / resolve():
https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#resolve
from django.urls import resolve
from django.http import HttpResponseRedirect, Http404
from django.utils.six.moves.urllib.parse import urlparse
def myview(request):
next = request.META.get('HTTP_REFERER', None) or '/'
response = HttpResponseRedirect(next)
# modify the request and response as required, e.g. change locale
# and set corresponding locale cookie
view, args, kwargs = resolve(urlparse(next)[2])
kwargs['request'] = request
try:
view(*args, **kwargs)
except Http404:
return HttpResponseRedirect('/')
return response

If you are using generic views or just views, you can do something like this:
class myView(View): # or UpdateView, CreateView, DeleteView
template_name = 'mytemplate.html'
def get(self, request, *args, **kwargs):
context = {}
class_id = self.kwargs['class_id']
# do something with your class_id
return render(request, self.template_name, context)
# same with the post method.

Yes, you can do like this
def my_class(request, class_id):
# this class_id is the class_id in url
# do something;

Related

Use LoginRequiredMixin and UserPassesTestMixin at the same time

I want to have a TemplateView Class that uses LoginRequiredMixin and UserPassesTestMixin at the same time. Something like this:
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class FinanceOverview(LoginRequiredMixin, UserPassesTestMixin, TemplateMixin):
login_url = '/login'
redirect_field_name = 'next'
def test_func(self):
return self.request.user.groups.filter(name="FinanceGrp").exists()
def get(self, request, *args, **kwargs):
DO SOMETHING IF USER IS AUTHENTICATED AND ALSO MEMBER OF GROUP FinanceGrp
Basically as you can see above, what I want to achieve is the following:
If user is not authenticated, to redirect user to:
https://website/login?next=financeoverview
However what I can't figure out is how to redirect users who are authenticated but do not belong to group FinanceGrp to another page. For example:
https://website.com/access_denied?previous_page=financeoverview
In my case users are always redirected to /login page when they fail the group test. How can I achieve two mixins used at the same time but at the same time both of them are clashing around variable login_url. Unfortunately UserPassesTestMixin is using the same login_url so it makes this trouble for me.
Thanks in advance
Milos
I think you're better off subclassing AccessMixin and then performing these checks yourself. Something like this:
from django.contrib.auth.mixins import AccessMixin
from django.http import HttpResponseRedirect
class FinanceOverview(AccessMixin, TemplateMixin):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
# This will redirect to the login view
return self.handle_no_permission()
if not self.request.user.groups.filter(name="FinanceGrp").exists():
# Redirect the user to somewhere else - add your URL here
return HttpResponseRedirect(...)
# Checks pass, let http method handlers process the request
return super().dispatch(request, *args, **kwargs)
You should override get_login_url:
class FinanceOverview(LoginRequiredMixin, UserPassesTestMixin, TemplateMixin):
login_url = '/login'
redirect_field_name = 'next'
def test_func(self):
return self.request.user.groups.filter(name="FinanceGrp").exists()
def get_login_url(self):
if self.request.user.is_authenticated:
return URL_FOR_AUTHENTICATED_USERS
return super().get_login_url()
def get(self, request, *args, **kwargs):
DO SOMETHING IF USER IS AUTHENTICATED AND ALSO MEMBER OF GROUP FinanceGrp

Django : how to include a view.py file inside a view from another app?

I've made a "paginator" app, that add such SEO optimisation for all my pages.
So I need to pass all visible page url through paginator.view
But, I want to keep my apps as structured as possible.
For an example here is a view for my gallery app:
gallery.views
from django.shortcuts import render
from gallery.models import GalleryItem
def home(request):
img_to_display = GalleryItem.objects.filter(published=True
).order_by('-date')
return render(request, 'gallery/all.html', locals())
...
Now I'm doing like that form my view in paginator :
My current paginator.views
from django.shortcuts import render, get_object_or_404, redirect
from gallery.models import GalleryItem
from paginator.models import Page
import gallery
def custom_page(request, url):
current_page = url
# just for the gallery page :
if url == 'gallery':
img_to_display = GalleryItem.objects.filter(published=True
).order_by('-date')
# for all my page
page_to_load = get_object_or_404(Page, name=url)
template_to_load = "paginator/" + page_to_load.template_name
return render(request, template_to_load, locals())
So I copy/paste my view and all dependencies, but that is really ugly, and not at all DRY, worth it's not maintainable. I try something like that but it doesn't work :
paginator.views : option1
from django.shortcuts import render
import gallery
def custom_page(request, url):
if url == 'gallery':
gallery.views.home(request)
if url == 'anotherpage':
anotherapp.views.home(request)
...
Or something like that :
paginator.views : option 2
from django.shortcuts import render
def custom_page(request, url):
if url == 'gallery':
include("gallery.views.py")
if url == 'anotherpage':
include("anotherapp.views.py")
...
Note: I prefer the last style option because it minimize the import at the start of the paginator.views file.
Thanks a lot for helping ! :)
If you need a mechanism which is executed before the request is dispatched to a view, I would recommend using a middleware class. You can read more about it in the Django docs.
Another option is to use class based views to create a SEOView which can be inherited by every custom page view of yours. Some example of how it could look like:
from django.views.generic.base import View
class MySeoView(View):
def dispatch(self, request, *args, **kwargs):
# some logic for SEO
return super().dispatch(request, *args, **kwargs)
class CustomView1(MySeoView):
def get(self, request, *args, **kwargs):
# do normal stuff for this page
return HttpResponse(...)
def post(self, request, *args, **kwargs):
# maybe some other logic for posts
return HttpResponse(...)
To come back to your own options:
If you want to make #1 work, I guess you have to return the result of the view:
...
if url == 'someUrl':
return gallery.views.home(request)
...
Firstly I want to thanks Gocht to have sended me on a good way. So that's what I've done :
paginator.views
def custom_page(request, url):
"""
Vue d'une page statique.
"""
if url == 'gallery':
import gallery
gal = gallery.views.render_gallery(request)
gal.render()
gallery_html = gal.rendered_content
if url == 'xxx':
...
page_to_load = get_object_or_404(Page, url=url)
template_to_load = "paginator/" + page_to_load.template_name
return render(request, template_to_load, locals())
gallery.views
from django.template.response import TemplateResponse
from gallery.models import GalleryItem
def render_gallery(request):
img_to_display = GalleryItem.objects.filter(published=True
).order_by('-date')
return TemplateResponse(request, 'gallery/gallery.html', locals())
But yes, now, I understand that something like simP will be more clean. Thanks !

How to override render_to_response method in CreateView Django?

I'm writing CreateView generic-view in my application and I want to override the render_to_response method.
I've tried to do the same thing with below code.
from edxmako.shortcuts import render_to_response as render_to_response_mako
class CreateView( generic.CreateView ):
template_name = 'cms/templates/form_bsct.html'
print dir(generic.CreateView)
def get_context_data(self, **kwargs):
context = super(CreateView, self).get_context_data(**kwargs)
context.update({'name':'jay'})
return context
def get(self, request, *args, **kwargs):
print args
print kwargs
"""
Handles GET requests and instantiates a blank version of the form.
"""
template_name = 'cms/templates/form_bsct.html'
import os
print os.getcwd()
return render_to_response_mako(template_name)
In above code I'm trying to override the native render_to_response method with edxmako render_to_response method.
It is giving me below error.
"Cant locate template for uri %r" % uri)
TopLevelLookupException: Cant locate template for uri 'cms/templates/form_bsct.html'
It is not getting the template. Please help me how to do that?

How do I redirect from a Django DetailView when the specified object doesn't exist?

So, right now when my DetailView subclass doesn't find an object using the PK (which is taken from the URL), I see the 404.html template page. What I'd rather do is just redirect to another URL. Here's my url patterns:
url(r'^(?P<pk>[0-9]+)/$', DeviceDetailView.as_view(
template_name='devices/detail.html',
queryset=Device.objects.all(),
context_object_name="device",
)),
url(r'^$', FullListView.as_view(template_name='devices/devices.html',)),
So, if my url looks like /devices/8/, it uses 8 as the primary key. Works great when 8 exists in the database. However, when 8 doesn't exist, it goes to the 404 page. What I would rather it do is go to a list - in fact, the FullListView listed when last url (which is what happens when the url looks like /devices/nonnumericstuff/.
Seems like that should be pretty easy, no? I don't want all 404's to go there so i can't use handler404.
The DetailView's get_object method raises an Http404 exception if the object doesn't exist in the queryset. Instead of overriding the get_object method you could catch the exception in the view's get method:
from django.http import Http404
from django.views.generic import DetailView
from django.shortcuts import redirect
class MyDetailView(DetailView):
def get(self, request, *args, **kwargs):
try:
self.object = self.get_object()
except Http404:
# redirect here
return redirect(url)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
For common cases
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import DetailView
class MyDetailView(DetailView):
def get(self, request, *args, **kwargs):
try:
return super().get(request, *args, **kwargs)
except Http404:
return redirect(reverse('my_list_view_name'))
You should redefine def get_object(self): of the DetailView
There's something similar in this question

How to use permission_required decorators on django class-based views

I'm having a bit of trouble understanding how the new CBVs work. My question is this, I need to require login in all the views, and in some of them, specific permissions. In function-based views I do that with #permission_required() and the login_required attribute in the view, but I don't know how to do this on the new views. Is there some section in the django docs explaining this? I didn't found anything. What is wrong in my code?
I tried to use the #method_decorator but it replies "TypeError at /spaces/prueba/ _wrapped_view() takes at least 1 argument (0 given)"
Here is the code (GPL):
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required
class ViewSpaceIndex(DetailView):
"""
Show the index page of a space. Get various extra contexts to get the
information for that space.
The get_object method searches in the user 'spaces' field if the current
space is allowed, if not, he is redirected to a 'nor allowed' page.
"""
context_object_name = 'get_place'
template_name = 'spaces/space_index.html'
#method_decorator(login_required)
def get_object(self):
space_name = self.kwargs['space_name']
for i in self.request.user.profile.spaces.all():
if i.url == space_name:
return get_object_or_404(Space, url = space_name)
self.template_name = 'not_allowed.html'
return get_object_or_404(Space, url = space_name)
# Get extra context data
def get_context_data(self, **kwargs):
context = super(ViewSpaceIndex, self).get_context_data(**kwargs)
place = get_object_or_404(Space, url=self.kwargs['space_name'])
context['entities'] = Entity.objects.filter(space=place.id)
context['documents'] = Document.objects.filter(space=place.id)
context['proposals'] = Proposal.objects.filter(space=place.id).order_by('-pub_date')
context['publication'] = Post.objects.filter(post_space=place.id).order_by('-post_pubdate')
return context
There are a few strategies listed in the CBV docs:
Decorate the view when you instantiate it in your urls.py (docs)
from django.contrib.auth.decorators import login_required
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 of your view is wrapped (docs)
There's two ways to do this:
Apply method_decorator to your CBV dispatch method e.g.,
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
#method_decorator(login_required, name='dispatch')
class ViewSpaceIndex(TemplateView):
template_name = 'secret.html'
If you're using Django < 1.9 (which you shouldn't, it's no longer supported) you can't use method_decorator on the class, so you have to override the dispatch method manually:
from django.contrib.auth.decorators import login_required
class ViewSpaceIndex(TemplateView):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ViewSpaceIndex, self).dispatch(*args, **kwargs)
Use a mixin like django.contrib.auth.mixins.LoginRequiredMixin outlined well in the other answers here:
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
Make sure you place the mixin class first in the inheritance list (so Python's Method Resolution Order algorithm picks the Right Thing).
The reason you're getting a TypeError is explained in the docs:
Note:
method_decorator passes *args and **kwargs as parameters to the decorated method on the class. If your method does not accept a compatible set of parameters it will raise a TypeError exception.
Here is my approach, I create a mixin that is protected (this is kept in my mixin library):
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class LoginRequiredMixin(object):
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
Whenever you want a view to be protected you just add the appropriate mixin:
class SomeProtectedViewView(LoginRequiredMixin, TemplateView):
template_name = 'index.html'
Just make sure that your mixin is first.
Update: I posted this in way back in 2011, starting with version 1.9 Django now includes this and other useful mixins (AccessMixin, PermissionRequiredMixin, UserPassesTestMixin) as standard!
Here's an alternative using class based decorators:
from django.utils.decorators import method_decorator
def class_view_decorator(function_decorator):
"""Convert a function based decorator into a class based decorator usable
on class based Views.
Can't subclass the `View` as it breaks inheritance (super in particular),
so we monkey-patch instead.
"""
def simple_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return simple_decorator
This can then be used simply like this:
#class_view_decorator(login_required)
class MyView(View):
# this view now decorated
For those of you who use Django >= 1.9, it's already included in django.contrib.auth.mixins as AccessMixin, LoginRequiredMixin, PermissionRequiredMixin and UserPassesTestMixin.
So to apply LoginRequired to CBV(e.g. DetailView):
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.detail import DetailView
class ViewSpaceIndex(LoginRequiredMixin, DetailView):
model = Space
template_name = 'spaces/space_index.html'
login_url = '/login/'
redirect_field_name = 'redirect_to'
It's also good to keep in mind GCBV Mixin order: Mixins must go on the left side, and the base view class must go in the right side. If the order is different you can get broken and unpredictable results.
I realise this thread is a bit dated, but here's my two cents anyway.
with the following code:
from django.utils.decorators import method_decorator
from inspect import isfunction
class _cbv_decorate(object):
def __init__(self, dec):
self.dec = method_decorator(dec)
def __call__(self, obj):
obj.dispatch = self.dec(obj.dispatch)
return obj
def patch_view_decorator(dec):
def _conditional(view):
if isfunction(view):
return dec(view)
return _cbv_decorate(dec)(view)
return _conditional
we now have a way to patch a decorator, so it will become multifunctional. This effectively means that when applied to a regular view decorator, like so:
login_required = patch_view_decorator(login_required)
this decorator will still work when used the way it was originally intended:
#login_required
def foo(request):
return HttpResponse('bar')
but will also work properly when used like so:
#login_required
class FooView(DetailView):
model = Foo
This seems to work fine in several cases i've recently come across, including this real-world example:
#patch_view_decorator
def ajax_view(view):
def _inner(request, *args, **kwargs):
if request.is_ajax():
return view(request, *args, **kwargs)
else:
raise Http404
return _inner
The ajax_view function is written to modify a (function based) view, so that it raises a 404 error whenever this view is visited by a non ajax call. By simply applying the patch function as a decorator, this decorator is all set to work in class based views as well
Use Django Braces. It provides a lot of useful mixins that is easily available.
It has beautiful docs. Try it out.
You can even create your custom mixins.
http://django-braces.readthedocs.org/en/v1.4.0/
Example Code:
from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
class SomeSecretView(LoginRequiredMixin, TemplateView):
template_name = "path/to/template.html"
#optional
login_url = "/signup/"
redirect_field_name = "hollaback"
raise_exception = True
def get(self, request):
return self.render_to_response({})
In my code I have written this adapter to adapt member functions to a non-member function:
from functools import wraps
def method_decorator_adaptor(adapt_to, *decorator_args, **decorator_kwargs):
def decorator_outer(func):
#wraps(func)
def decorator(self, *args, **kwargs):
#adapt_to(*decorator_args, **decorator_kwargs)
def adaptor(*args, **kwargs):
return func(self, *args, **kwargs)
return adaptor(*args, **kwargs)
return decorator
return decorator_outer
You can simply use it like this:
from django.http import HttpResponse
from django.views.generic import View
from django.contrib.auth.decorators import permission_required
from some.where import method_decorator_adaptor
class MyView(View):
#method_decorator_adaptor(permission_required, 'someapp.somepermission')
def get(self, request):
# <view logic>
return HttpResponse('result')
If it's a site where the majority of pages requires the user to be logged in, you can use a middleware to force login on all views except some who are especially marked.
Pre Django 1.10 middleware.py:
from django.contrib.auth.decorators import login_required
from django.conf import settings
EXEMPT_URL_PREFIXES = getattr(settings, 'LOGIN_EXEMPT_URL_PREFIXES', ())
class LoginRequiredMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
path = request.path
for exempt_url_prefix in EXEMPT_URL_PREFIXES:
if path.startswith(exempt_url_prefix):
return None
is_login_required = getattr(view_func, 'login_required', True)
if not is_login_required:
return None
return login_required(view_func)(request, *view_args, **view_kwargs)
views.py:
def public(request, *args, **kwargs):
...
public.login_required = False
class PublicView(View):
...
public_view = PublicView.as_view()
public_view.login_required = False
Third-party views you don't want to wrap can be made excempt in the settings:
settings.py:
LOGIN_EXEMPT_URL_PREFIXES = ('/login/', '/reset_password/')
It has been a while now and now Django has changed so much.
Check here for how to decorate a class-based view.
https://docs.djangoproject.com/en/2.2/topics/class-based-views/intro/#decorating-the-class
The documentation did not include an example of "decorators that takes any argument". But decorators that take arguments are like this:
def mydec(arg1):
def decorator(func):
def decorated(*args, **kwargs):
return func(*args, **kwargs) + arg1
return decorated
return deocrator
so if we are to use mydec as a "normal" decorator without arguments, we can do this:
mydecorator = mydec(10)
#mydecorator
def myfunc():
return 5
So similarly, to use permission_required with method_decorator
we can do:
#method_decorator(permission_required("polls.can_vote"), name="dispatch")
class MyView:
def get(self, request):
# ...
I've made that fix based on Josh's solution
class LoginRequiredMixin(object):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
Sample usage:
class EventsListView(LoginRequiredMixin, ListView):
template_name = "events/list_events.html"
model = Event
This is super easy with django > 1.9 coming with support for PermissionRequiredMixin and LoginRequiredMixin
Just import from the auth
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
class YourListView(LoginRequiredMixin, Views):
pass
For more details read Authorization in django
If you are doing a project which requires variety of permission tests, you can inherit this class.
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import user_passes_test
from django.views.generic import View
from django.utils.decorators import method_decorator
class UserPassesTest(View):
'''
Abstract base class for all views which require permission check.
'''
requires_login = True
requires_superuser = False
login_url = '/login/'
permission_checker = None
# Pass your custom decorator to the 'permission_checker'
# If you have a custom permission test
#method_decorator(self.get_permission())
def dispatch(self, *args, **kwargs):
return super(UserPassesTest, self).dispatch(*args, **kwargs)
def get_permission(self):
'''
Returns the decorator for permission check
'''
if self.permission_checker:
return self.permission_checker
if requires_superuser and not self.requires_login:
raise RuntimeError((
'You have assigned requires_login as False'
'and requires_superuser as True.'
" Don't do that!"
))
elif requires_login and not requires_superuser:
return login_required(login_url=self.login_url)
elif requires_superuser:
return user_passes_test(lambda u:u.is_superuser,
login_url=self.login_url)
else:
return user_passes_test(lambda u:True)
Here the solution for permission_required decorator:
class CustomerDetailView(generics.GenericAPIView):
#method_decorator(permission_required('app_name.permission_codename', raise_exception=True))
def post(self, request):
# code...
return True