view.py
class UserViewSet(viewsets.ModelViewSet):
""" API endpoint that allows users to be viewed or edited. """
serializer_class = UserSerializer
queryset = UserRegister.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateRegister,)
This is the view.py file. Here i have added authentication and permission to my view set.
permission.py
class UpdateRegister(permissions.BasePermission):
""" Allow user to edit their own profile. """
def has_object_permissions(self, request, view, obj):
""" Check user is trying to edit their own profile. """
if request.method in permissions.SAFE_METHODS:
return True
return obj.id == request.user.id
serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = UserRegister
fields = ('id', 'name', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
""" Create and return a new user"""
user = UserRegister(
email=validated_data['email'],
name=validated_data['name'],
)
user.set_password(validated_data['password'])
user.save()
return user
Error shown in network tab
So guy i am being bother by this error. Hope you guys will address my mistake and help me to solve the error.
Related
I'm having the following problem: the login request returns "Unable to login with provided credentials" after I do a PUT request (changing fields like first_name, last_name, address) even though the username and password are correct in the DB.
The following view I use to make my Login Request.
class RetrieveAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
resp = Response({
'token': token.key,
'user_id': user.pk,
'email': user.email,
'role': user.role,
})
return resp
And these are for my users and registration of a user:
from users.models import User
from users.serializers import UserSerializer, RegistrationSerializer
from rest_framework import viewsets, generics
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
# Create your views here.
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
class RegistrationView(generics.CreateAPIView):
model = User
serializer_class = RegistrationSerializer
My serializers look like this:
from rest_framework import serializers, status
from users.models import User
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'})
class Meta:
model = User
fields = '__all__'
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
instance = super(UserSerializer, self).update(instance, validated_data)
instance.set_password(validated_data['password'])
instance.save()
return instance
class RegistrationSerializer(serializers.ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
def create(self, validated_data):
user = super(RegistrationSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = User
fields = ['email', 'username', 'password']
It looks like the problem is coming from the serializer:
Solved the problem guys! So, the problem was coming from the is_active field from User. On my update method from the serializer, that field was set to False after I did that request. In order to solve this, on my update method I set the is_active field to True.
def update(self, instance, validated_data):
instance = super(UserSerializer, self).update(instance, validated_data)
instance.set_password(validated_data['password'])
instance.is_active = True
instance.save()
return instance
I am using Django 2.2 with Django Rest Framework 3.7.
I have a class like this:
class UserViewSet(viewsets.ModelViewSet):
permission_classes = [AllowAny]
serializer_class = UserSerializer
queryset = User.objects.all()
def update(self, request, *args, **kwargs):
import pdb;pdb.set_trace()
I've created UserSerializer like this:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'name', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
def create(self, validated_data):
user = User.objects.create(
email=validated_data['email'],
name=validated_data['name'],
)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
print('lalala from serialzier')
import pdb;pdb.set_trace()
instance.username = validated_data['username']
instance.save()
return instance
Only allowed methods being shown are - Allow: GET, POST, HEAD, OPTIONS
I wonder why I am unable to perform actions like PUT, DELETE, RETRIEVE. These are by default supported by using ModelViewset as per documentation.
In shown code neither serializer's update() nor views.py update() method getting called. Any hint would be appreciated.
Does this answer your question?
class UserViewSet(viewsets.ModelViewSet):
permission_classes = [AllowAny]
serializer_class = UserSerializer
queryset = User.objects.all()
def put(self, request, id, format=None):
...
def delete(self, request, id, format=None):
...
I am trying to create a sign up api using createAPIView on Django rest Framework. Everytime I post data on Postman it returns the above error although it gets response when I run it in browser. Also the image field is causing problem in raw data on postman. I have tried a lot of things but nothng has seemed to work. What am I supposed to do?
serializers
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(min_length=8)
class Meta:
model = User
fields = ('id', 'first_name','last_name', 'email', 'username','password')
extra_kwargs = {'user': {'required': False}}
class UserProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
code = serializers.CharField(read_only=True)
avatar = serializers.FileField(use_url=False)
class Meta:
model = UserProfile
fields = '__all__'
extra_kwargs = {'user': {'required': False}}
def create(self, validated_data):
user_data = validated_data.pop('user',None)
image = validated_data.pop('avatar')
upr=UserProfile.objects.create(user=user_data, image=image**validated_data)
return upr
views
class UserCreate(generics.ListCreateAPIView):
serializer_class = UserProfileSerializer
user_serializer = UserSerializer
queryset = UserProfile.objects.all()
parser_classes = (FormParser,MultiPartParser,FileUploadParser)
def post(self, request):
serializer = UserProfileSerializer(data=request.data)
print(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)
You are trying to send profile data without creating a user first. And a profile object must be applied to an already existing user.
how do I create user with default group? my serializer
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password')
def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
views.py
class UserView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
How do I set user group when creating from this view?
Just add something like
user.groups.add(Group.objects.get(name='Whatever'))
after user.save() in the create method.
I'm trying to add a custom create method, and am using the Django REST FRAMEWORK. Once a user is created, I want to create an auth token and then return a JSON response with this user AND an auth token.
UPDATE: I was able to update the below to create the user, but now I am getting Cannot assign "<User: User object>": "Token.user" must be a "User" instance What am i doing wrong?
How can I modify the below so when POST to users/, I create a user, create an auth token, and return both?
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 's3_link', 'phone_confirmed', 'agreed_to_tos', 'phone_number', 'facebook_id', 'stripe_id', 'phone_verification_code')
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
##ISSUE WITH CODE STARTS HERE
user = serializer.save()
token = Token.objects.create(user=user)
You could use a custom Response to add the token to the user data:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 's3_link', 'phone_confirmed', 'agreed_to_tos', 'phone_number', 'facebook_id', 'stripe_id', 'phone_verification_code')
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Customized rest_framework.mixins.CreateModelMixin.create():
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
# Your code
user = serializer.save()
token = Token.objects.create(user=user)
# Create custom response
data = serializer.data
# You may need to serialize your token:
# token = token.your_token_string_field
data.update({'token': token})
headers = self.get_success_headers(serializer.data)
return Response(data, status=status.HTTP_201_CREATED, headers=headers)
If you want to create a user, I would recommend following this format:
serializers.py:
class AccountCreateSerializer(serializers.ModelSerializer):
class Meta:
model = User
# You will need to check accuracy of fields, but this is for demo purposes
fields = ['username', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
username=validated_data['username'],
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
views.py:
from rest_framework import generics
from serializers.py import AccountCreateSerializer
class AccountCreateAPIView(generics.CreateAPIView):
serializer_class = AccountCreateSerializer