Class based view to function based view - django-views

How can I convert a class based view, which is used for creating REST API to a function based view
my input class view
class
Login_View_Sets(viewsets.ModelViewSet):
queryset = Login_Model.objects.all()
serializer_class = Login_Serializer()
Thanks in advance :)

The Django REST framework tutorial shows an example of a function based view for an entry point. You'll have to adjust things so it matches your model and serializer.

I got the answer, which I meant
from django.http import HttpResponse
def my_view(request):
if request.method == 'GET':
# <view logic>
return HttpResponse('result')
In a class-based view, this would become:
from django.http import HttpResponse
from django.views.generic import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')

I got the answer.
This is an example of function based view view
from django.http import HttpResponse
def my_view(request):
if request.method == 'GET':
# <view logic>
return HttpResponse('result')
In a class-based view, this would become:
from django.http import HttpResponse
from django.views.generic import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')

Related

superuser authenticate in class based view

I am working on blog project in which I added an add post which add post now I want only the superuser can add post and that page is visible only to superuser.
1st Method
Views.py
class AddPostView(CreateView):
model = Post
template_name = 'MainSite/add_post.html'
fields = '__all__'
this is my current view I am able to achieve authenticate for superuser using 2nd method
2nd Method
class AddPostView(View):
def get(self,request):
if request.user.is_superuser == True:
return render(...)
else:
pass
How can I achieve the same result using 1st method.I tried using LoginRequiredMixin but nothing is happening . I just import LoginRequiredMixin and use it like this .
class Addpost(CreateView,LoginRequiredMixin):
...
Thanks in advance and advice will be helpful.
You can work with a UserPassesTestMixin mixin [Django-doc]:
from django.contrib.auth.mixins import UserPassesTestMixin
class AddPostView(UserPassesTestMixin, CreateView):
# …
def test_func(self):
return self.request.user.is_superuser
# …
You can encapsulate this in a mixin:
from django.contrib.auth.mixins import UserPassesTestMixin
class AdminRequiredMixin(UserPassesTestMixin):
def test_func(self):
return self.request.user.is_superuser
and then use this mixin:
class AddPostView(AdminRequiredMixin, CreateView):
# …
def test_func(self):
return self.request.user.is_superuser
# …
Mixins should be put before the actual view in the inheritance hierarchy: otherwise these appear after the view in the method resolution order (MRO), and thus likely will not override the behavior (correctly).
class AddPostView(CreateView,LoginRequiredMixin):
model = Post
template_name = 'MainSite/add_post.html'
fields = '__all__'
def dispatch(self, request, *args, **kwargs):
if request.user.is_anonymous:
return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
elif request.user.is_superuser:
return render(.....)
else
return super(AddPostView, self).dispatch(request, *args, **kwargs)
Use method_decorator and user_passes_test to achieve this
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test
class AddPostView(View):
#method_decorator(user_passes_test(lambda u: u.is_superuser))
def post(self, *args, **kwargs):
pass

'CreateView' object has no attribute 'render_to_response'

I have this create view and it throws the error 'CreateView' object has no attribute 'render_to_response'
urls.py
path(
"p/<int:id>/food/create",
views.FoodCreateView.as_view(),
name="food-create",
),
views.py
class FoodCreateView(BaseCreateView):
template_name = "food_form.html"
form_class = forms.FoodForm
success_message = "successfully created"
def get_queryset(self):
return Food.all(#####)
def get_success_url(self):
return reverse(
"food_list"
)
am I lacking anything with the code?
In newer Django newer Versions, CreateView is inherits with BaseCreateView . AND in newer version render_to_response is also replaced with render
So you should import it like :-
from django.views.generic import CreateView
After change it :-
Your view should look like this :-
from django.shortcuts import render
from django.views.generic import CreateView
class FoodCreateView(CreateView):
template_name = "food_form.html"
form_class = forms.FoodForm
success_message = "successfully created"
def get_queryset(self):
return Food.all(#####)
def get_success_url(self):
return reverse(
"food_list"
)

Problems importing mixin into another app for apply to Class Based View

I have the file userprofiles/mixins.py in which I've created this mixin
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
class LoginRequiredMixin(object):
#method_decorator(login_required(login_url = '/login/'))
def dispatch(self, request, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
In my file userprofiles/views.py I have the following class based view named ProfileView of this way:
from .mixins import LoginRequiredMixin
class ProfileView(LoginRequiredMixin,TemplateView):
template_name = 'profile.html'
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated():
context.update({'userprofile': self.get_userprofile()})
return context
def get_userprofile(self):
return self.request.user.userprofile
In this class based view named ProfileView I could inherit from LoginRequiredMixin without any trouble
These mixin LoginRequiredMixin I also applied to the class based view named AlbumListView which is located in other module or app artists/views.py.
The class based view AlbumListView is this:
from sfotipy.userprofiles.mixins import LoginRequiredMixin
class AlbumListView(LoginRequiredMixin,ListView):
model = Album
template_name = 'album_list.html'
def get_queryset(self):
if self.kwargs.get('artist'):
queryset = self.model.objects.filter(artist__slug__contains=self.kwargs['artist'])
else:
queryset = super(AlbumListView, self).get_queryset()
return queryset
The unique way for my IDE don't mark error when I import the LoginRequiredMixin for I inherit from it is of this way:
from sfotipy.userprofiles.mixins import LoginRequiredMixin
I know that this import way is not correct, because is a absolute import and the right way is doing a relative import.
Other way in where should work is this:
from userprofiles.mixins import LoginRequiredMixin
But, when I want test I get the following error message...
How to can I do this import and that works?
Thanks for the orientation :D

Django Template Context Processor with Class Based Views

I have a Login Class Based View which I want to include in all my pages.
Is there a way to include Class Based View as template context processor, or do we have any other way to include in all pages ?
class LoginView(RedirectAuthenticatedUserMixin, FormView):
form_class = LoginForm
template_name = "account/login.html"
success_url = None
redirect_field_name = "next"
def form_valid(self, form):
success_url = self.get_success_url()
return form.login(self.request, redirect_url=success_url)
def get_success_url(self):
# Explicitly passed ?next= URL takes precedence
ret = (get_next_redirect_url(self.request,
self.redirect_field_name)
or self.success_url)
return ret
def get_context_data(self, **kwargs):
ret = super(LoginView, self).get_context_data(**kwargs)
signup_url = passthrough_next_redirect_url(self.request,
reverse("account_signup"),
self.redirect_field_name)
redirect_field_value = self.request.REQUEST \
.get(self.redirect_field_name)
ret.update({"signup_url": signup_url,
"site": Site.objects.get_current(),
"redirect_field_name": self.redirect_field_name,
"redirect_field_value": redirect_field_value})
return ret
login = LoginView.as_view()
You can decorate the view:
Either in urls.py:
from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import TemplateView
from .views import VoteView
urlpatterns = patterns('',
(r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
)
Or in views.py:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
class ProtectedView(TemplateView):
template_name = 'secret.html'
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectedView, self).dispatch(*args, **kwargs)
Or, you can inherit from LoginRequiredMixin from django-braces:
from braces.views import LoginRequiredMixin
class Index(LoginRequiredMixin, TemplateView):
template_name = 'sekret.html'
All these examples show how to require authentication for class based views (which I believe is what you are trying to do). The first two are directly from the documentation.
Once you implement either of the above examples, your application will behave like this:
A user enters a URL that maps to one of the above views.
django middleware checks if the user is logged in.
If not, django will redirect to LOGIN_URL, by default its /accounts/login/, and add a ?next parameter, pointing to the original URL from #1.
The view from #3 will display a login form.
Once the user successfully authenticates, the view from #3 will update the session, and redirect the user to the URL from the next parameter.
If the user is logged in, then the decorated view will be executed as normal.

django #login_required decorator for a superuser

Is there a decorator in django similar to #login_required that also tests if the user is a superuser?
Thanks
Use the user_passes_test decorator:
from django.contrib.auth.decorators import user_passes_test
#user_passes_test(lambda u: u.is_superuser)
def my_view(request):
...
In case staff membership is sufficient and you do not need to check whether the user is a superuser, you can use the #staff_member_required decorator:
from django.contrib.admin.views.decorators import staff_member_required
#staff_member_required
def my_view(request):
...
If you want to have similar functionality to #staff_member_required you can easily write your own decorator. Taking #staff_member as an example we can do something like this:
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.admin.views.decorators import user_passes_test
def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='account_login_url'):
"""
Decorator for views that checks that the user is logged in and is a
superuser, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_superuser,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
This example is a modified staff_member_required, just changed one check in lambda.
For class based views, creating a reusable decorator:
from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import View
def superuser_required():
def wrapper(wrapped):
class WrappedClass(UserPassesTestMixin, wrapped):
def test_func(self):
return self.request.user.is_superuser
return WrappedClass
return wrapper
#superuser_required()
class MyClassBasedView(View):
def get(self, request):
# ...
I recommend using Mixins, example:
from django.contrib.auth.mixins import UserPassesTestMixin
class SuperUserCheck(UserPassesTestMixin, View):
def test_func(self):
return self.request.user.is_superuser
Then you can add SuperUserCheck to View class:
class MyView(SuperUserCheck, View):
if you have your profile of user you can simply do this
#login_required
#user_passes_test(lambda u: True if u.profile.role==2 else False )
def add_listing(request):
#...
To require a superuser on a class based view without writing new code:
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test
#method_decorator(user_passes_test(lambda u: u.is_superuser), name='dispatch')
class AdminCreateUserView(LoginRequiredMixin, FormView):
...
...
...
To check if user is logged in use #login_required decorator and check if logged in user is superuser or not inside the function through if/else condition and return your response accordingly.
'''
from django.shortcuts import HttpResponse, redirect
from django.contrib.auth.decorators import login_required
#login_required
def function_name(request):
if not request.user.is_superuser:
return redirect('profile')
else:
return HttpResponse('Superuser')
'''