Два Сериализатора СоздатьAPIView - Джанго - PullRequest
0 голосов
/ 18 февраля 2019

Я создал вид ниже.Похоже, я должен создать CreateAPIView.В следующем EmployeeAddView я взял два forms и добавил данные соответственно.Но я не понимаю, как это сделать в REST API.

@login_required
def EmployeeAddView(request):

    # Tab Opts Checking
    if request.user.userprofile.user_company.company_tab_opts:
            return redirect('admin_employee')

    if request.method == 'POST':
        random_password = User.objects.make_random_password() # generate password here 
        ur_form = EmployeeRegisterForm(request.POST, pwd=random_password)
        pr_form = EmployeeProfileForm(request.POST, request.FILES, user_company=request.user.userprofile.user_company.id)

        user_role = ACLRoles.objects.get(id=4)

        if ur_form.is_valid() and pr_form.is_valid():

            new_user = ur_form.save(commit=False)            
            new_user.username = new_user.email
            new_user.set_password(random_password)
            new_user.save()

            profile =  pr_form.save(commit=False)
            if profile.user_id is None:
                profile.user_id = new_user.id
                profile.user_role_id = user_role.id
                profile.user_company_id = request.user.userprofile.user_company.id
            profile.save()

            for group in request.POST.getlist('user_groups'): # For many to many field
                profile.user_groups.add(group)

            email= ur_form.cleaned_data.get('email')
            messages.success(request, 'Employee Added - %s!' % email)
            return redirect('admin_employee')

    else:
        ur_form = EmployeeRegisterForm(use_required_attribute=False)
        pr_form = EmployeeProfileForm(user_company=request.user.userprofile.user_company.id, use_required_attribute=False)

    return render(request, 'employee/employee_form.html', {'ur_form': ur_form, 'pr_form': pr_form})

Это моя попытка, но я не понимаю, как это сделать API-views.py

class EmployeeAddAPIView(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = EmployeeRegisterSerializer
    permission_classes = [UserIsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(
            userprofile__user_company = self.request.auth.application.company,
      )

API-Serializer.py

class EmployeeProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = [  'user_employee_id',
                    'user_phone', 
                    'user_payroll_id',
                    'user_hire_date',
                    'user_pay_rate',
                    'user_salaried',
                    'user_excempt',
                    'user_groups',
                    'user_state',
                    'user_city',
                    'user_zipcode', 
                    'user_status',
        ]

class EmployeeRegisterSerializer(serializers.ModelSerializer):
    userprofile = EmployeeProfileSerializer(read_only=True)

    class Meta:
        model = User
        fields = ['first_name','last_name', 'email', 'userprofile']

Как мне это сделать.

Я сделал что-то вроде этого

    from rest_framework.views import APIView
from rest_framework import status

    class EmployeeAddAPIView(APIView):

        def post(self, request, *args, **kwrgs):

            serializer1 = EmployeeRegisterSerializer(data=request.data)
            serializer2 = EmployeeProfileSerializer(data=request.data)

            user_role = ACLRoles.objects.get(id=4)

            if serializer1.is_valid():
                print('inside')
                new_user = serializer1.save(commit=False)            
                new_user.username = new_user.email
                new_user.set_password(random_password)
                new_user.save()

                profile =  serializer2.save(commit=False)
                if profile.user_id is None:
                    profile.user_id = new_user.id
                    profile.user_role_id = user_role.id
                    profile.user_company_id = self.request.auth.application.company
                profile.save()


                return Response(status=status.HTTP_200_OK)
            print('outside', serializer1)
            return Response(status=status.HTTP_200_OK)

1 Ответ

0 голосов
/ 18 февраля 2019

Вы можете добавить 2 сериализатора так же, как вы добавляете 2 формы

в serailizer.py

class Model1SerailizerOne(serializer.ModelSerializer):
    # code

class Model2SerailizerTwo(serializer.ModelSerializer):
    # code

в api.py

class APICreateView(APIView):

  def post(self, request, *args, **kwrgs):

      serializer1 = Model1SerailizerOne(data=request.data)
      serializer2 = Model2SerailizerTwo(data=request.data)

      if serializer1.is_valid() and serializer2.is_valid():

           # save code
         return ....

надеюсь, это поможет

Это будет работать -

class EmployeeAddAPIView(APIView):
    permission_classes = [UserIsAuthenticated]
    def post(self, request, *args, **kwrgs):

        serializer1 = EmployeeRegisterSerializer(data=request.data)
        serializer2 = EmployeeProfileSerializer(data=request.data)

        user_role = ACLRoles.objects.get(id=4)

        if serializer1.is_valid():

            print(serializer1.validated_data['email'])
            user = serializer1.save(
                username = serializer1.validated_data['email'],
            )

            random_password = User.objects.make_random_password()
            obj = get_object_or_404(User, pk=user.id)
            obj.set_password(random_password)
            obj.save()

            print(serializer1.errors)

            if serializer2.is_valid():
                serializer2.save(
                    user_id = user.id,
                    user_company_id = self.request.auth.application.company.id,
                    user_role_id = user_role.id
                )

            return Response(status=status.HTTP_200_OK)

        return Response(status=status.HTTP_404_NOT_FOUND)
...