授权错误-“未提供身份验证凭据” Angular和Django

时间:2018-10-31 21:40:46

标签: django angular forms registration

我正在尝试使用Django和Angular获得一份注册表格。

我是Angular和Django的新手,欢迎提供帮助。我不知道为什么它没有注册新用户,也没有将新注册用户重定向到登录页面。我尝试搜索答案已有四天了,没有找到任何有效结果。

我添加了图片和代码以供查看。代码在图片下方。如果还有更多代码需要查找问题,请在评论中告诉我,我将提供它。

这是我的代码的屏幕截图:

userView

userService_Angular

userSerializer

settings

这是我的控制台的屏幕截图:

console console 2

下面的代码是我的UserView:

    from django.contrib.auth.models import User
    from rest_framework import viewsets, status
    from kno.api.serializers import UserSerializer
    from rest_framework.authentication import TokenAuthentication, 
    SessionAuthentication
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.authtoken.views import ObtainAuthToken
    from rest_framework.authtoken.models import Token
    from rest_framework.response import Response
    from kno.api.models import Answer
    from kno.api.models import Question
    from kno.api.models import Campaign
    from kno.api.models import Rating
    from rest_framework.decorators import action

    from kno.api.serializers import AnsSerializer
    from kno.api.serializers import UserSerializer
    from kno.api.serializers import QusSerializer
    from kno.api.serializers import CampaignSerializer
    from kno.api.serializers import RatingSerializer


    class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all().order_by('-date_joined')
        serializer_class = UserSerializer
        authentication_classes = (TokenAuthentication, SessionAuthentication)
        permission_classes = (IsAuthenticated,)


    class AnsViewSet(viewsets.ModelViewSet):
    queryset = Answer.objects.all()
    serializer_class = AnsSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)


    class QusViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QusSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)


    class CampViewSet(viewsets.ModelViewSet):
    queryset = Campaign.objects.all()
    serializer_class = CampaignSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)


    class RatingViewSet(viewsets.ModelViewSet):
    queryset = Rating.objects.all()
    serializer_class = RatingSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)

    @action(detail=True, methods=['post'])
    def ans_rating(self, request):
        if 'answer' in request.data and 'user' in request.data and           
    'ratingStars' in request.data:
            answer = Answer.objects.get(id=request.data['answer'])
            user = User.objects.get(id=request.data['user'])
            ratingstars = request.data['ratingStars']

            try:
                my_rating = Rating.objects.get(answer=answer.id, user=user.id)
                my_rating.ratingStars = ratingstars
                my_rating.save()
                serializer = AnsSerializer(answer, many=False)
                response = {"message": "Rating updated", "result":     
    serializer.data}
                return Response(response, status=status.HTTP_200_OK)
            except:
                Answer.objects.create(answer=answer, user=user, 
    ratingstars=ratingstars)
                serializer = AnsSerializer(answer, many=False)
                response = {"message": "Rating created", "result": 
    serializer.data}
                return Response(response, status=status.HTTP_200_OK)

        else:
            response = {"message": "You need to pass all prams"}
            return Response(response, status=status.HTTP_400_BAD_REQUEST)


    class CustomObtainAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        response = super(CustomObtainAuthToken, self).post(request, *args, 
    **kwargs)
        token = Token.objects.get(key=response.data['token'])
        user = User.objects.get(id=token.user_id)
        serializer = UserSerializer(user, many=False)
        return Response({'token': token.key, 'user': serializer.data})

这是下面我的settings.py文件的代码:

    """
    Django settings for kno project.

    Generated by 'django-admin startproject' using Django 2.1.2.

    For more information on this file, see
    https://docs.djangoproject.com/en/2.1/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.1/ref/settings/
    """

    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '3%6_zct589%$ab1%a!@=hyfi)6zkm0d_9p=_eofrb832attf%h'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = []


    # Application definition

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'kno.api',
    'corsheaders',
    ]

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ]

    CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    '127.0.0.1:9000',
    'localhost:4200',
    '10.2.2'
    )


    ROOT_URLCONF = 'kno.urls'

    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
    ]

    REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.permissions.IsAuthenticated',
    )
    }

    WSGI_APPLICATION = 'kno.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/2.1/ref/settings/#databases

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
    }


    # Password validation
    # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password- 
   validators

    AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 

   'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 
   'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 
    'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 
    'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/2.1/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.1/howto/static-files/

    STATIC_URL = '/static/'

下面的代码是我的序列化器:

    from django.contrib.auth.models import User
            from rest_framework import serializers
            from kno.api.models import Answer
            from kno.api.models import Question
            from kno.api.models import Campaign
            from kno.api.models import Rating


            class UserSerializer(serializers.HyperlinkedModelSerializer):
                class Meta:
                    model = User
                    fields = ('id', 'username', 'email', 'password')
                    extra_kwargs = {'password': {'write_only': True, 
    'required': True}}

                def create(self, validated_data):
                    user = User.objects.create_user(**validated_data)
                    return user


            class AnsSerializer(serializers.ModelSerializer):
                class Meta:
                    model = Answer
                    fields = ('id', 'user', 'ans_grade', 'ans_cat', 'ans', 
    'campaign', 'question', )


            class QusSerializer(serializers.ModelSerializer):
                class Meta:
                    model = Question
                    fields = ('id', 'question', 'question_example', 
    'question_cat', )


            class CampaignSerializer(serializers.ModelSerializer):
                class Meta:
                    model = Campaign
                    fields = ('id', 'user', 'campaign_title',)


            class RatingSerializer(serializers.ModelSerializer):
                class Meta:
                    model = Rating
                    fields = ('user', 'ratingStars', 'answer', 'question', 
    'id', 'campaign', )

这是我的Angular文件中的代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';

@Injectable()
export class UserService {

  httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8'});
  baseUrl: string = environment.apiUrl;

  constructor(private https: HttpClient) { }

  loginUser(userData: any): Observable<any> {
    return this.https.post(this.baseUrl + 'authenticate/', userData);
  }

  registerUser(userData: any): Observable<any> {
    return this.https.post(this.baseUrl + 'users/', userData);
  }

}

0 个答案:

没有答案