当我想使用CreateAPIView创建对象时遇到问题,我收到消息: “ detail”:“未提供身份验证凭据。”。
我使用rest-auth和rest-authtoken应用程序。
这是我到目前为止所做的:
class CustomUser(AbstractUser):
objects = CustomUserManager()
is_normal_user = models.BooleanField(default=False)
is_corporate_user = models.BooleanField(default=False)
class CompanyProfile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
corporate_name = models.CharField(max_length=30)
class CompanyProfileSerializer(serializers.ModelSerializer):
class Meta:
model = CompanyProfile
fields = ['user', 'corporate_name',]
read_only_fields = ('id',)
class Authorized_Company_User(permissions.BasePermission):
def has_permission(self, request, view):
return bool(request.user and request.user.is_corporate_user)
class CompanyCreateProfileView(generics.CreateAPIView):
#queryset = CompanyProfile.objects.all()
serializer_class = CompanyProfileSerializer
#authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated, Authorized_Company_User)
我想知道是否需要定义创建函数,并使用get方法来获取用户身份验证。
答案 0 :(得分:0)
“详细信息”:“未提供身份验证凭据。”
此消息是由permission_classes = IsAuthenticated
您需要提供令牌才能创建。
从rest_auth应用添加此网址:
re_path(r'^rest_auth/',include('rest_auth.urls'))
然后您可以使用邮递员进行测试
method :POST
url: http://127.0.0.1:8000/rest_auth/login/
body: {"username":"user", "password":"password"}
headers: Content-Type: Application/json
您得到的回应
`{"key":"here your token"}`
使用此令牌,您可以添加新用户
method :POST
url: http://127.0.0.1:8000/add_user_url/
body: {"corporate_name":"corporate"}
headers: Content-Type: Application/json
Authorization: "Token ########here your token########"
在您的CreateAPIView中,您可以分配用户:
class CompanyCreateProfileView(generics.CreateAPIView):
def perform_create(self, serializer):
serializer.save(user=self.request.user)