Wrapping / decorating a function in urls.py vs in views.py

So, I am very familiar with the wrapping functions in views.py. So I wrote a decorator to redirect to REDIRECT_URL by default if the user is logged in (like reverse login_required ); this is based on how I made representations in the past:

 def not_logged_in(redirect_url=None, redirect_field_name=REDIRECT_FIELD_NAME): def decorator(view_func, *args, **kwargs): def wrapper(request, *args, **kwargs): if not request.user.is_authenticated(): return view_func(*args, **kwargs) else: redirect_url = (request.REQUEST.get(redirect_field_name, redirect_url) or settings.REDIRECT_URL) return HttpResponseRedirect(redirect_url) return wrapper return decorator 

However, I get the following error: 'function' object has no attribute 'status_code' , which is caused by MiddleWare waiting for HttpResponse. When I look at the value for response , I see that it is <function wrapper at 0x2b3a9922a500> .

Here is what I call it in urls.py :

 url(r'login/', not_logged_in(auth_views.login), {'authentication_form': LoginForm }, ), 
+6
source share
3 answers

Here is my implementation of the same.

 def logout_required(view): def f(request, *args, **kwargs): if request.user.is_anonymous(): return view(request, *args, **kwargs) return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) return f 

In urls.py :

 urlpatterns = patterns("", url(r"^login/", logout_required(login), {"template_name": "users/login.html"}, "login"), # ... 

Hope this helps (though not sure).

+8
source

The first argument to the decorator should be the function that needs to be styled.

 def not_logged_in(func, redirect_url=None, redirect_field_name=REDIRECT_FIELD_NAME): 

The decorator function is also not needed. Return the wrapper function from not_logged_in.

+1
source

How you implemented your decorator, it is parameterized and therefore can be called up: why you have an extra level of function that fizixx says incorrectly is not required. First you need to call the outer shell to return the actual decorated function. So something like:

 url(r'login/', not_logged_in(auth_views.login)('/redirect/', 'redirect_field'), {'authentication_form': LoginForm }, ), 
+1
source

Source: https://habr.com/ru/post/886744/


All Articles