Is there a way to get swagger to use the login_required decorator? I have it on several views:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
pass
Is there a way I can get swagger to use this as well? It automatically will redirect users to the login page and would be handy to have in place.
Related
I have various applications in a Django project, but I only want users who are logged in to be able to access those pages. How can I restrict access to every pages except the login page which is my main page. For instance, mywebsite.com/home/user should be only available to user and if someone types in that it should redirect them to mywebsite.com
Currently I have two apps, main and Home, I am using ClassBased views on my Home app how can I restrict access to all my pages except login page and show a message as well?
I want to create a template that users can see other user profile details but not change or edit them. How can I do those above steps
Thanks in advance!
According to Docs you can decorate the class based views with #login_required
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ClassBasedView(View):
...
...
Since you are using class based view, you need to add method decorator, else you can use #logine_required directly.
And the other part in the question is again a separate one from this.
You can try This, In very simple way
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
return HttpResponse()
using #login_required means user have to login to access that view
Or If you you Want to use class then try this
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class RestrictedView(LoginRequiredMixin, TemplateView):
template_name = 'foo/restricted.html'
raise_exception = True
permission_denied_message = "You are not allowed here."
i am using django authentification to make a oneToone relation with the user table. I try to use decorator #login_required to the next page after the login. when i logout and click on the back button of firefox, i always go to the previous page even if #login_required is apply. but when i refresh it redirect me on the login page. Is it a cache problem? how can i solve it? I want to do it like how the administration works
def logout(request):
from django.contrib.auth import logout
from django.shortcuts import redirect
logout(request)
request.session.flush()
return redirect('/')
from django.contrib.auth.decorators import login_required
#login_required(login_url='/')
def administration(request):
do something
return something
I'm using TemplateView to display swagger pages (local files). However, now I need to restrict access. Using a normal view, I could use #login_required mixin on the view. Is there a way to do that with TemplateViews? Or should I be using some other way of displaying these swagger pages?
url(r'^swagger/', TemplateView.as_view(template_name='swagger.html'), name='swagger'),
The most clean way would be to create a view extending the TemplateView, so it would help leaving your urls.py clean.
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
class SwaggerView(LoginRequiredMixin, TemplateView):
template_name = 'swagger.html'
urls.py
from . import views
url(r'^swagger/', views.SwaggerView.as_view(), name='swagger'),
When I try to use staff_view, I get redirected in the admin authentication interface.
from django.contrib.admin.views.decorators import staff_member_required
#staff_member_required
def staff_view(request..):
...
How can I make a custom login, and not getting redirected in the default admin login interface?
You can use Django's user_passes_test decorator:
from django.contrib.auth.decorators import user_passes_test
#user_passes_test(lambda u:u.is_staff, login_url=reverse_lazy('foo'))
def staff_view(request..):
...
It's worth pointing out that staff_member_required is a wrapper around user_passes_test (see source code) and it also accepts a login_url parameter, so you could do:
#staff_member_required(login_url=example_url)
def staff_view(request..):
...
I'm trying to write a site in Django where the API URLs are the same as user-facing URLs. But I'm having trouble with pages which use POST requests and CSRF protection. For example, if I have a page /foo/add I want to be able to send POST requests to it in two ways:
As an end user (authenticated using a session cookie) submitting a form. This requires CSRF protection.
As an API client (authenticated using a HTTP request header). This will fail if CSRF protection is enabled.
I have found various ways of disabling CSRF, such as #csrf_exempt, but these all disable it for the entire view. Is there any way of enabling/disabling it at a more fine-grained level? Or am I just going to have to implement by own CSRF protection from scratch?
Modify urls.py
If you manage your routes in urls.py, you can wrap your desired routes with csrf_exempt() to exclude them from the CSRF verification middleware.
for instance,
from django.views.decorators.csrf import csrf_exempt
urlpatterns = patterns(
# ...
# Will exclude `/api/v1/test` from CSRF
url(r'^api/v1/test', csrf_exempt(TestApiHandler.as_view()))
# ...
)
Alternatively, as a Decorator
Some may find the use of the #csrf_exempt decorator more suitable for their needs
for instance,
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
#csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
There is a section of Django's CSRF Protection documentation titled View needs protection for one path which describes a solution. The idea is to use #csrf_exempt on the whole view, but when the API client header is not present or invalid, then call a function
annotated with #csrf_protect.
If you are you using class base view (CBV) and want to use the csrf_exempt decorator you will need to use the method decorator.
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
#method_decorator(csrf_exempt, name='dispatch')
class MyView(View):
def post(self, request):
pass # my view code here
In my case, I am using JWT authentication plus csrf_token for some views. And for some reasons that I am unaware of, csrf_exempt does not work when I set it as a decorator or when I wrap the view name in the url patterns.
So here's what I ended up doing. I overrided the initialize_request available in the APIView class.
class ClasssName(views.APIView):
def initialize_request(self, request, *args, **kwargs):
setattr(request, 'csrf_processing_done', True)
return super().initialize_request(request, *args, **kwargs)