Данные сериализатора не отображаются в API - PullRequest
0 голосов
/ 04 мая 2020

Эй, ребята, это мой первый проект в Django, я пытаюсь вставить поле "внешних ключей" в мой API с помощью Django Rest Framework.

Я пытаюсь сделать сообщение товар. так как я не вижу поля ввода, я застрял здесь.

Это может быть что-то очень простое, я мог бы этого не видеть.

******* ОБНОВЛЕНИЕ ********

Как запрошено, поместите здесь изображение для более подробной информации о том, чего я на самом деле хочу достичь.

На изображении ниже показано, что я ХОЧУ в своем api показать, и я получаю его вот так , все мои поля, такие как, как я хочу их (кроме того, я получаю категорию дважды, одна цифра тоже)

Но если вы присмотритесь ниже, форма POST ограничивается атрибутами продукта Сам класс модели. Поэтому я не могу сделать фактический пост со стороны интерфейса.

enter image description here

в сериализаторах enter image description here

Если я комментирую поля, я опускаюсь ниже своих полей в POST, да ... но когда я публикую сообщение, я получаю цифры в моем API, а не имена внешних ключей

enter image description here

Итак, обратите внимание, я получаю все поля, которые мне нужны для моего внешнего интерфейса, чтобы обрабатывать функцию post. Но тогда я получаю цифры в API вместо

enter image description here enter image description here

Надеюсь, я сделал это более ясно, чем раньше .. :)

Заранее спасибо

serializers.py

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from .models import *
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token


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

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


class ProductSerializer(serializers.ModelSerializer):
    product_id = serializers.CharField(source='product.url', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    user_id = serializers.CharField(source='user.id', read_only=True)
    subject = serializers.CharField(source='subject.subject', read_only=True)
    condition = serializers.CharField(source='condition.condition', read_only=True)
    major = serializers.CharField(source='major.major', read_only=True)
    state = serializers.CharField(source='state.state', read_only=True)
    school = serializers.CharField(source='school.school', read_only=True)
    location = serializers.CharField(source='location.location', read_only=True)

    class Meta:
        model = Product
        fields = '__all__'


class SubjectSerializer(serializers.ModelSerializer):
        model = Subject
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = ('url', 'id', 'name')

class StateSerializer(serializers.ModelSerializer):
 #   state_count = serializers.SerializerMethodField()
    class Meta:
        model = State
        fields = ['id', 'url', 'state']

    # def get_state_count(self, obj):
    #     if State.objects.count()
    #         return obj.children().count()
    #         return 0


class ConditionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Condition
        fields = '__all__'

class MajorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Major
        fields = '__all__'

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = '__all__'

class FaqSerializer(serializers.ModelSerializer):
    class Meta:
        model = Faq
        fields = '__all__'



просмотров

from django.shortcuts import render
from  rest_framework import viewsets, status
from  rest_framework.decorators import api_view
from .models import Product, State, Category, Subject
from django.contrib.auth.models import User
from .serializer import *
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework.authentication import TokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.pagination import LimitOffsetPagination

class ProductViewPagination(LimitOffsetPagination):
    default_limit = 8
    max_limit = 12


class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    product_count = Product.objects.count()
    authentication_classes = (TokenAuthentication,)
    permission_calsses = (IsAuthenticated,)
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    search_fields = ('=title','=category__name','=user__id','=subject__subject', '=major__major', '=condition__condition', '=location__location')
    pagination_class = ProductViewPagination

    # def delete(self,request,*args,**kwargs):
    #     response = {'message':'product cannot be updated like this'}
    #     return Response(response, status = statu.HTTP_400_BAD_REQUEST)

    # def create(self,request,*args,**kwargs):
    #     response = {'message':'product cannot be created like this'}
    #     return Response(response, status = status.HTTP_400_BAD_REQUEST)

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_calsses = (IsAuthenticated,)
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    search_fields = ('=name', 'id')

class SubjectViewSet(viewsets.ModelViewSet):
    queryset = Subject.objects.all()
    serializer_class = SubjectSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    search_fields = ('=subject',)

class ConditionViewSet(viewsets.ModelViewSet):
    queryset = Condition.objects.all()
    serializer_class = ConditionSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    search_fields = ('=condition',)

class MajorViewSet(viewsets.ModelViewSet):
    queryset = Major.objects.all()
    serializer_class = MajorSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    search_fields = ('=major',)

class LocationViewSet(viewsets.ModelViewSet):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    search_fields = ('=location',)


# class StateCountViewSet(viewsets.ModelViewSet):
#     queryset = State.objects.all()
#     serializer_class = StateSerializer
#     permission_calsses = (IsAuthenticated,)

#     def get(self, request, format=None):
#         state_count = State.objects.count()
#         content = {'state_count' : state_count}
#         return Response(content)

class StateViewSet(viewsets.ModelViewSet):
    queryset = State.objects.all()
    serializer_class = StateSerializer
    permission_calsses = (IsAuthenticated,)

class FaqViewSet(viewsets.ModelViewSet):
    queryset = Faq.objects.all()
    serializer_class = FaqSerializer
    permission_calsses = (AllowAny,)

class UserViewSet(viewsets.ModelViewSet):
  queryset = User.objects.all()
  serializer_class = UserSerializer
  authentication_classes = (TokenAuthentication,)
  permission_classes = (AllowAny, )

# @api_view(['POST',])
# def registration_view(request):

#     if request.method == 'POST':
#         serializer = RegristrationSerializer(data=request.data)
#         data = {}
#         if serializer.is_valid():
#             user = serialzer.save()
#             data['response'] = "successfully registered a new userrrR"
#             data['username'] = user.username
#         else:
#                 data = serializer.errors
#                 return user


urls.py


from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from django.urls import path
from restapi.views import *

# class UserSerializer(serializers.HyperlinkedModelSerializer):
#     class Meta:
#         model = User
#         fields = ['id', 'url', 'username', 'email', 'is_staff']

# # ViewSets define the view behavior.
# class UserViewSet(viewsets.ModelViewSet):
#     queryset = User.objects.all()
#     serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.

router = routers.DefaultRouter()
router.register('users', UserViewSet)
router.register('product', ProductViewSet)
router.register('category', CategoryViewSet)
router.register('state', StateViewSet)
#router.register('stateCount', StateCountViewSet)
router.register('subject', SubjectViewSet)
router.register('major', MajorViewSet)
router.register('condition', ConditionViewSet)
router.register('location', LocationViewSet)
router.register('faq', FaqViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    #path('state/count/:state_id', StateCountViewSet, name='states-count')
 ]



admin.py

from django.contrib import admin
from .models import *


admin.site.register(Product)
admin.site.register(Category)
admin.site.register(Subject)
admin.site.register(State)
admin.site.register(Major)
admin.site.register(Condition)
admin.site.register(Location)
admin.site.register(Faq)

model.py



from django.db import models
from django.contrib.auth.models import User
# class User(models.Model):
#     id_user = models.DecimalField(max_digits=10, decimal_places=2, null=True)
#     def __str__(self):
#        return self.id_user

class Faq(models.Model):
    question = models.CharField(max_length = 400, null = True,)
    answer = models.CharField(max_length = 900, null = True,)
    def __str__(self):
       return self.question

class Category(models.Model):
    name = models.CharField(max_length = 200, null = True,)
    def __str__(self):
       return self.name

class State(models.Model):

    STATE_CHOICES = [('Ordered', 'Ordered'), ('Pending', 'Pending'),
        ('Placed', 'Placed')
    ]
    state = models.CharField(max_length = 200, null = True,
    choices = STATE_CHOICES)

    def __str__(self):
       return self.state

class Subject(models.Model):
    SUBJECT_CHOICES=[('Mathematics','Mathematics'),('Algoritmes','Algoritmes'),('Analyses','Analyses'),('Informatica','Informatica'),]
    subject=models.CharField(max_length=200,null=True,choices=SUBJECT_CHOICES)
    def __str__(self):return self.subject

class Major(models.Model):
    MAJOR_CHOICES = (
        ('IT','IT'),
        ('Marketing','Marketing'),
        ('DIFF','DIFF'),
    )
    major = models.CharField(max_length=200,choices=MAJOR_CHOICES, null=True)
    def __str__(self):return self.major

class Condition(models.Model):
    CONDITION_CHOICES = [
        ('New','New'),
        ('Used','Used'),
    ]
    condition = models.CharField(max_length=200,choices=CONDITION_CHOICES, null=True)
    def __str__(self):return self.condition

class Location(models.Model):
    LOCATION_CHOICES = [
        ('Brussel','Brussel'),
        ('Leuven','Leuven'),
        ('Gent','Gent'),
        ('Antwerpen','Antwerpen'),
    ]
    location = models.CharField(max_length=200,choices=LOCATION_CHOICES, null=True)
    def __str__(self):return self.location

class Product(models.Model):
    user = models.ForeignKey(User,null=True, on_delete=models.SET_NULL)
    state = models.ForeignKey(State, null=True, on_delete=models.SET_NULL)
    category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
    subject = models.ForeignKey(Subject, null=True, on_delete=models.SET_NULL)
    major = models.ForeignKey(Major, null=True, on_delete=models.SET_NULL)
    condition = models.ForeignKey(Condition, null=True, on_delete=models.SET_NULL)
    location = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=800, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    #image = models.ImageField(upload_to='post_image', blank=True, width_field=None, height_field=None, max_length=100,)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        unique_together = (('user','title'),)
        index_together = (('user','title'),) 


    SCHOOL_CHOICES = (
        ('Erasmushogeschool | EHB',(
            ('Campus Kaai', 'Campus Kaai'),
            ('Campus Bloemberg', 'Campus Bloemberg'),
        )),
        ('Vrije Universiteit Brussel | VUB',(
            ('Campus Jette', 'Campus Jette'),
            ('Campus Schaarbeek', 'Campus Schaarbeek'),
        )),
        ('Katholieke universiteit leuven | KUL',(
            ('KUL Gent', 'KUL Gent'),
            ('Campus Antwerpen', 'Campus Antwerpen'),
        )),
    )
    school = models.CharField(max_length=50, choices=SCHOOL_CHOICES, null=True)

    # MAJOR_CHOICES = (
    #     ('IT','IT'),
    #     ('Marketing','Marketing'),
    #     ('DIFF','DIFF'),
    # )
    # major = models.CharField(max_length=200,choices=MAJOR_CHOICES, null=True)

    # SUBJECT_CHOICES = [
    #     ('Mathematics','Mathematics'),
    #     ('Algoritmes','Algoritmes'),
    #     ('Analyses','Analyses'),
    # ]
    # subject = models.CharField(max_length=200,choices=SUBJECT_CHOICES, null=True)

    # CONDITION_CHOICES = [
    #     ('New','New'),
    #     ('Used','Used'),
    # ]
    # condition = models.CharField(max_length=200,choices=CONDITION_CHOICES, null=True)

    # LOCATION_CHOICES = [
    #     ('Brussel','Brussel'),
    #     ('Leuven','Leuven'),
    #     ('Gent','Gent'),
    #     ('Antwerpen','Antwerpen'),
    # ]
    # location = models.CharField(max_length=200,choices=LOCATION_CHOICES, null=True)


    def __str__(self):
        return self.title





...