Angular - Django REST api «Bad Request» ошибка при регистрации пользователя - PullRequest
0 голосов
/ 05 декабря 2018

Заголовок ## Я пытаюсь переслать регистрационные данные ученика и учителя из углового в django rest api.Учитель может успешно зарегистрироваться, когда я получаю сообщение об ошибке «Bad Request» при регистрации ученика.Все отлично работает при отправке запроса через почтальона

ошибка

:

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad 
## Heading ##Request", url: "http://localhost:8000/auth/student/", ok: false, …}

student-register-component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-student-register',
  templateUrl: './student-register.component.html',
  styleUrls: ['./student-register.component.css']
})
export class StudentRegisterComponent implements OnInit {

registerStudentData = {}

constructor(private _auth: AuthService) { }

ngOnInit() {
}

registerStudent(){
this._auth.registerStudent(this.registerStudentData)
  .subscribe(
    res => console.log(res),
    err => console.log(err)
  )
}

}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
providedIn: 'root'
})
export class AuthService {

private _registerTeacherUrl = "http://127.0.0.1:8000/auth/teacher/"
private _registerStudentUrl = "http://localhost:8000/auth/student/"

private _loginTeacherUrl = ""
private _loginStudentUrl = ""

constructor(private http:HttpClient) { }

registerTeacher(teacher){
return this.http.post<any>(this._registerTeacherUrl, teacher)
}

registerStudent(student){
return this.http.post<any>(this._registerStudentUrl, student)
}
}

views.py

from authapi.serializers import TeacherSerializer, StudentSerializer
from authapi.models import Teacher, Student
from django.http import Http404
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator



# Create your views here.

class TeacherList(APIView):
"""
List all teachers, or create a new teacher.
"""

    def get(self, request, format=None):
        teachers = Teacher.objects.all()
        serializer = TeacherSerializer(teachers, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = TeacherSerializer(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 TeacherDetail(APIView):
"""
Retrieve, update or delete a teacher instance.
"""
    def get_object(self, pk):
        try:
            return Teacher.objects.get(pk=pk)
       except Teacher.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = TeacherSerializer(snippet)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = TeacherSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, 
    status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

class StudentList(APIView):

    def get(self, request, format=None):
        students = Student.objects.all()
        serializer = StudentSerializer(students, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = StudentSerializer(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 StudentDetail(APIView):
    def get_object(self, pk):
        try:
            return Student.objects.get(pk=pk)
        except Student.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = StudentSerializer(snippet)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = StudentSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, 
        status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

serializers.py

from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from authapi.models import Teacher, Student

class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        # fields = '__all__'
        fields = ('name', 'subject', 'couchingCode', 'mobile', 'password')


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        # fields = '__all__'
        fields = ('name', 'studentClass', 'couchingCode', 'mobile', 'password', 'batch_id')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...