How can I fix django rest framework metaclass conflict - django

I am a beginner learning django rest framework and I just encounter this error and I can't seem to find a way around it. Here is the permissions.py sample code
from rest_framework import permissions
class UpdateOwnProfile(permissions, BaseException):
"""Allow user to edit their own profile"""
def has_object_permission(self, request, view, obj):
"""Check if user is trying to update their own profile"""
if request.method in permissions.SAFE_METHODS:
return True
return obj.id == request.user.id
Here is also a sample of the views.py sample codes
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from profiles_api import serializers
from profiles_api import models from profiles_api import permissions
class HelloApiView(APIView): """Test Api view""" serializer_class = serializers.HelloSerializer
def get(self, request, format=None):
"""Returns a list of Api features"""
an_apiview = [
'Uses HTTP methods as function (get, post, patch, put, delete)',
'Is similar to a traditional Django view',
'Gives you the most control over your application logic',
'Is mapped manually to URLs',
]
return Response({'message': 'Hello', 'an_apiview': an_apiview})
def post(self, request):
"""Create a hello message with our name"""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.validated_data.get('name')
message = f'Hello {name}'
return Response({'message': message})
else:
return Response(
serializer.errors,
status = status.HTTP_400_BAD_REQUEST
)
def put(self, request, pk=None):
"""Handling updates of objects"""
return Response({'method': 'PUT'})
def patch(self, request, pk=None):
"""Handle a partial update of an object"""
return Response({'method': 'PATCH'})
def delete(self, request, pk=None):
"""Delete an object"""
return Response({'method': 'DELETE'})
class HelloViewset(viewsets.ViewSet): """Test API Viewset""" serializer_class = serializers.HelloSerializer
def list(self, request):
"""Return a hello message"""
a_viewset = [
'Uses actions (list, create, retrieve, update, partial update'
'Automatically maps to URLs using router'
'provides more functionality with less code'
]
return Response({'message': 'Hello', 'a_viewset': a_viewset})
def create(self, request):
"""Create a new hello message"""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.validated_data.get('name')
message = f'Hello {name}!'
return Response({'message': message})
else:
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
def retrieve(self, request, pk=None):
"""Handle getting an object by its ID"""
return Response({'http_method': 'GET'})
def update(self, request, pk=None):
"""Handle updating an object"""
return Response({'http_method': 'PUT'})
def partial_update(self, request, pk=None):
"""Handle updating of an object"""
return Response({'http_method': 'PATCH'})
def destroy(self, request, pk=None):
"""Handle removing an object"""
return Response({'http_method': 'DELETE'})
class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,)
And while running the development server I get this error:
class UpdateOwnProfile(permissions, BaseException): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

permissions (rest_framework.permissions) is of type module (whose type is type FWIW), but the type of BaseException is type (like all regular classes). So you have a metaclass conflict as expected.
Presumably, you meant to use permissions.BasePermission class from the module:
class UpdateOwnProfile(permissions.BasePermission, BaseException):
...
...
You can also import and refer the class directly:
from rest_framework.permissions import BasePermission
class UpdateOwnProfile(BasePermission, BaseException):
...
...

Related

Facing Issue when giving restricted permissions to particular group in Django

I am trying to make a REST API using Django REST Framework. In the section of Authentication and Authorization I created 2 groups namely Manager (which has permissions to perform CRUD on database) and Staff (which has only view permission). Using serializers I am displaying the data in json format. But I am still able to perform CRUD operation using Staff account. How can I fix that?
This is my models.py
from django.db import models
class Users(models.Model):
Aadhar_Number = models.IntegerField(unique=True, primary_key=True, default=0)
Is_Active = models.BooleanField()
street = models.CharField(max_length=100,null=True)
city = models.CharField(max_length=10,null=True)
state = models.CharField(max_length=10,null=True)
Postal_Code = models.IntegerField(null=True)
def __str__(self):
return f"{self.Aadhar_Number}-{self.Full_Name}"
This is my api.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import *
class UserList(APIView):
def get(self, request):
model = Users.objects.all()
serializer = UsersSerializer(model, many=True)
return Response(serializer.data)
def post(self, request):
serializer = UsersSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserDetail(APIView):
def get_user(self, employee_id):
try:
model = Users.objects.get(id=employee_id)
return model
except Users.DoesNotExist:
return
def get(self, request, employee_id):
if not self.get_user(employee_id):
return Response(f'User with {employee_id} is Not Found in database', status=status.HTTP_404_NOT_FOUND)
serializer = UsersSerializer(self.get_user(employee_id))
return Response(serializer.data)
def put(self, request, employee_id):
serializer = UsersSerializer(self.get_user(employee_id), data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, employee_id):
if not self.get_user(employee_id):
return Response(f'User with {employee_id} is Not Found in database', status=status.HTTP_404_NOT_FOUND)
model = self.get_user(employee_id)
model.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
I have added 2 groups using a Superuser and assigned them different permissions.
Permissions using Superuser
REST API View
When using DRF, you should go for its own permissions system.
Create a permissions.py inside your app.
# permissions.py
from rest_framework import permissions
class IsManagerOrReadOnly(permissions.BasePermission):
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
# GET, OPTIONS, HEAD are considered safe methods.
return True
# for other methods such as POST/PUT/DELETE,
# check if the user has access with group name
return request.user.groups.filter(name='manager').exists()
And in your views, since you're using APIView it's pretty straightforward.
# views.py
from .permissions import IsManagerOrReadOnly
class NameOfYourView(APIView):
permission_classes = [IsManagerOrReadOnly]
# rest of your code...

DRF Custom Permission is not firing

I wrote a custom permission class for a drf project to protect my view:
views.py
class Employee(APIView):
permission_classes = [BelongsToClient]
serializer_class = EmployeeSerializer
def get(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
serializer = EmployeeSerializer(employee, many=False)
return Response(serializer.data)
def delete(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
employee.Employees_deleted = True
employee.save()
return Response(status=status.HTTP_200_OK)
My permission class:
permission.py
from rest_framework import permissions
class BelongsToClient(permissions.BasePermission):
message= "You are only authorized to view objects of your client"
"""
Object-level permission to only see objects of the authenticated users client
"""
def has_object_permission(self, request, view, obj):
if obj.Mandant == request.user.Mandant:
return True
else:
return False
Unfortunatly this permission class isn't blocking my view even when it should. I dont know why. Did I miss something?
You need to call check_object_permissions method before response for APIView
class Employee(APIView):
permission_classes = [BelongsToClient]
serializer_class = EmployeeSerializer
def get(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
serializer = EmployeeSerializer(employee, many=False)
self.check_object_permissions(request, employee)
return Response(serializer.data)
has_object_permission only called when you use the DestroyAPIView or RetrieveAPIView or ViewSet.
Try to use a viewset just like below
from rest_framework import viewsets
class Employee(viewsets.ViewSet):
permission_classes = [BelongsToClient]
serializer_class = EmployeeSerializer
def delete(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
self.check_object_permissions(request, employee)
employee.Employees_deleted = True
employee.save()
return Response(status=status.HTTP_200_OK)
Note: I didn't test it but it should work.

Django:How can I prevent authenticated user from both register and login page in Django-registration-redux

I am currently using Django-registration-redux for my authentication system.
Already logged in user can visit the login and registration page again; which is not good enough. How can I prevent them from this since the views.py comes by default in Django-registration-redux
I think that should be done in the views.py that come with Django-registration-redux
Here is the views.py
"""
Views which allow users to create and activate accounts.
"""
from django.shortcuts import redirect
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
from django.conf import settings
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
try:
from django.utils.module_loading import import_string
except ImportError:
from registration.utils import import_string
from registration import signals
# from registration.forms import RegistrationForm
REGISTRATION_FORM_PATH = getattr(settings, 'REGISTRATION_FORM', 'registration.forms.RegistrationFormUniqueEmail')
REGISTRATION_FORM = import_string( REGISTRATION_FORM_PATH )
class _RequestPassingFormView(FormView):
"""
A version of FormView which passes extra arguments to certain
methods, notably passing the HTTP request nearly everywhere, to
enable finer-grained processing.
"""
def get(self, request, *args, **kwargs):
# Pass request to get_form_class and get_form for per-request
# form control.
form_class = self.get_form_class(request)
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
def post(self, request, *args, **kwargs):
# Pass request to get_form_class and get_form for per-request
# form control.
form_class = self.get_form_class(request)
form = self.get_form(form_class)
if form.is_valid():
# Pass request to form_valid.
return self.form_valid(request, form)
else:
return self.form_invalid(form)
def get_form_class(self, request=None):
return super(_RequestPassingFormView, self).get_form_class()
def get_form_kwargs(self, request=None, form_class=None):
return super(_RequestPassingFormView, self).get_form_kwargs()
def get_initial(self, request=None):
return super(_RequestPassingFormView, self).get_initial()
def get_success_url(self, request=None, user=None):
# We need to be able to use the request and the new user when
# constructing success_url.
return super(_RequestPassingFormView, self).get_success_url()
def form_valid(self, form, request=None):
return super(_RequestPassingFormView, self).form_valid(form)
def form_invalid(self, form, request=None):
return super(_RequestPassingFormView, self).form_invalid(form)
class RegistrationView(_RequestPassingFormView):
"""
Base class for user registration views.
"""
disallowed_url = 'registration_disallowed'
form_class = REGISTRATION_FORM
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, request, form):
new_user = self.register(request, form)
success_url = self.get_success_url(request, new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
def registration_allowed(self, request):
"""
Override this to enable/disable user registration, either
globally or on a per-request basis.
"""
return True
def register(self, request, form):
"""
Implement user-registration logic here. Access to both the
request and the full cleaned_data of the registration form is
available here.
"""
raise NotImplementedError
class ActivationView(TemplateView):
"""
Base class for user activation views.
"""
http_method_names = ['get']
template_name = 'registration/activate.html'
def get(self, request, *args, **kwargs):
activated_user = self.activate(request, *args, **kwargs)
if activated_user:
success_url = self.get_success_url(request, activated_user)
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
return super(ActivationView, self).get(request, *args, **kwargs)
def activate(self, request, *args, **kwargs):
"""
Implement account-activation logic here.
"""
raise NotImplementedError
def get_success_url(self, request, user):
raise NotImplementedError
Here is my main/project urls.py
urlpatterns = [
url( 'admin/', admin.site.urls),
url(r'^$', views.home, name='homepage'),
url(r'^user/', include('User.urls')),
#url(r'^accounts/register/$', MyRegistrationView.as_view(),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Thanks, any help will be appreciated
Below are the file showing identation error
indentaion error
views file
In the dispatch method of your views you can check if the user is authenticated and redirect them to another page, for example:
class RegistrationView(_RequestPassingFormView):
...
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if request.user.is_authenticated:
return redirect('some_url')
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
The if user.is_authenticated prevents both logged-in and not-logged-in user from accessing the registration page.
class RegistrationView(_RequestPassingFormView):
"""
Base class for user registration views.
"""
disallowed_url = 'registration_disallowed'
form_class = REGISTRATION_FORM
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if self.request.user.is_authenticated:
return redirect('/')
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, request, form):
new_user = self.register(request, form)
success_url = self.get_success_url(request, new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
def registration_allowed(self, request):
"""
Override this to enable/disable user registration, either
globally or on a per-request basis.
"""
return True
def register(self, request, form):
"""
Implement user-registration logic here. Access to both the
request and the full cleaned_data of the registration form is
available here.
"""
raise NotImplementedError

Implementing HATEOAS in Django REST framework

I'm trying to implement REST API that implements HATEOAS using Django REST Framework (DRF). I know that DRF itself doesn't support HATEOAS and I didn't find any examples of such implementation. Therefore I'm not sure on which level of DRF (Serializers / Views / Renderers) should I implement this functionality. Do you have some experiences, thoughts, insights or examples which could help me to start? Thank you.
Here is my solution implemented on level of Viewset:
from rest_framework import viewsets
from rest_framework import generics
from serializers import EventSerializer, BandSerializer
from rest_framework.response import Response
from rest_framework import status
from collections import OrderedDict
class LinksAwarePageNumberPagination(PageNumberPagination):
def get_paginated_response(self, data, links=[]):
return Response(OrderedDict([
('count', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data),
('_links', links),
]))
class HateoasModelViewSet(viewsets.ModelViewSet):
"""
This class should be inherited by viewsets that wants to provide hateoas links
You should override following methodes:
- get_list_links
- get_retrieve_links
- get_create_links
- get_update_links
- get_destroy_links
"""
pagination_class = LinksAwarePageNumberPagination
def get_list_links(self, request):
return {}
def get_retrieve_links(self, request, instance):
return {}
def get_create_links(self, request):
return {}
def get_update_links(self, request, instance):
return {}
def get_destroy_links(self, request, instance):
return {}
def get_paginated_response(self, data, links=None):
assert self.paginator is not None
return self.paginator.get_paginated_response(data, links)
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data, links=self.get_list_links())
serializer = self.get_serializer(queryset, many=True)
return Response(OrderedDict([
('results', serializer.data),
('_links', self.get_list_links(request))
]))
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
data = serializer.data
data['_links'] = self.get_retrieve_links(request, instance)
return Response(data)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
data = serializer.data
data['_links'] = self.get_create_links(request)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
data = serializer.data
data['_links'] = self.get_update_links(request, instance)
return Response(serializer.data)
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
data = {'_links': self.get_destroy_links(request, instance)}
self.perform_destroy(instance)
return Response(data, status=status.HTTP_204_NO_CONTENT)
Example of usage:
class EventViewSet(HateoasModelViewSet):
queryset = Event.objects.all()
serializer_class = EventSerializer
def get_list_links(self, request):
return {
'self': {'href': request.build_absolute_uri(request.path)},
'related_link1': {'href': '...'},
}
I know it is a relevant old thread, but for those who came to this now, there is a library django-rest-framework-json-api, which uses the json:api specification. This specification is completely compatible with the HATEOAS implementation.
I am also quite new to this; here is a tutorial that I used as a guide by the Columbia university which I found really helpful.
On the plus side I find it is compatible with api documentation using swagger, using the drf-yasg and drf-yasg-json-api libraries.

django-rest-framework multiple serializer for 1 model?

Suppose you want to give out
{field1, field2, field3} on detail request.
{field1, field2} on list request.
{field1} on some other simpler list request.
I have seen examples using get_serializer_class with self.action which can handle detail vs list scenario. (https://stackoverflow.com/a/22755648/433570)
Should I define two viewsets and two url endpoints?
Or is there a better approach here?
I guess this could be applied to tastypie as well. (two resources?)
I haven't tested it myself but I think you can do it overriding the methods you need.
According to the documentation (Marking extra actions for routing) you could do:
class UserViewSet(viewsets.ViewSet):
"""
Example empty viewset demonstrating the standard
actions that will be handled by a router class.
If you're using format suffixes, make sure to also include
the `format=None` keyword argument for each action.
"""
def list(self, request):
pass
def create(self, request):
pass
def retrieve(self, request, pk=None):
pass
def update(self, request, pk=None):
pass
def partial_update(self, request, pk=None):
pass
def destroy(self, request, pk=None):
pass
Or if you need custom methods:
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
#detail_route(methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.DATA)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.save()
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
#list_route()
def recent_users(self, request):
recent_users = User.objects.all().order('-last_login')
page = self.paginate_queryset(recent_users)
serializer = self.get_pagination_serializer(page)
return Response(serializer.data)