简体   繁体   English

Django在序列化器中弹出数据返回空

[英]Django popping out data in a serializer returns empty

I have a problem, this line isn't popping any data despite me passing the data... 我有一个问题,尽管我传递了数据,但这条线并没有弹出任何数据...

company_data = validated_data.pop('company', None)

Does anyone have any idea why I'm not getting any data passed into my serializer? 有没有人知道为什么我没有将任何数据传递到我的序列化器? Thank you everyone ahead of time! 提前谢谢大家! These are parts of my serializer... (The ...... means other parts in between) 这些是我的序列化器的一部分...(......意味着其他部分)

class UserSerializer(serializers.ModelSerializer):
    company = CompanySerializer(required=False)
....
class Meta:
    model = User
    fields = ('id', 'email', 'username', 'password', 'first_name',
                                 'name','phone', 'company')
    extra_kwargs = {'password': {'write_only': True}}
....
def create(self, validated_data):
    profile_data = validated_data.pop('user_profile', None)

    company_data = validated_data.pop('company', None)

This next part is part of my views.... 下一部分是我的观点的一部分....

@api_view(['GET', 'POST'])
def users_list(request):
    """
    List all users or create a new user
    """
    if request.method == 'GET' and request.user.is_superuser:
        if request.user.is_superuser:
            records = User.objects.all()
            serializers = UserSerializer(records, many=True)
            return Response(serializers.data)
        else:
            return Response(status=status.HTTP_403_FORBIDDEN)
    elif request.method == 'POST':
        mutable = request.POST._mutable
        request.POST._mutable = True
        request.data["username"] = request.data["email"]
        request.POST._mutable = mutable

        serializer = UserSerializer(data=request.data) 
        if serializer.is_valid():
            serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(
            serializer.errors, status=status.HTTP_400_BAD_REQUEST )
.....
class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('date_of_subscription', 'company_name', 'address1',
                     'address2', 'city', 'zipcode')

Here are my models... 这是我的模特......

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    phone = models.CharField(max_length=20)
    email_validation_token = models.CharField(max_length=100)
    forgot_password_token = models.CharField(max_length=100)
    full_name = models.CharField(max_length=100)

    rewards = models.ManyToManyField('Reward', through='UserReward')
    user = models.OneToOneField(User, related_name="user_profile")

    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.username

class Company(models.Model):
    date_of_subscription = models.CharField(max_length=100)
    company_name = models.CharField(max_length=100)
    address1 = models.CharField(max_length=100)
    address2 = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100)
    zipcode = models.CharField(max_length=100)

    user = models.OneToOneField(User, related_name="company",
                    on_delete=models.CASCADE,
                    primary_key=True)

Thanks everyone! 感谢大家!

**I know that there is indentation errors (they were from copy/paste, there aren't errors on the site) **我知道存在缩进错误(它们来自复制/粘贴,网站上没有错误)

Also here is how I am calling it, I tried two ways, one it throws an error if I just pass in a stringified json. 这也是我如何调用它,我尝试了两种方法,如果我只是传入一个字符串化的json,它会抛出一个错误。

var data = new Object();
data.name = name;
data.email = email;
data.password = password;
data.phone = phone;
data.full_name = name;
data.company = {};
data.company.date_of_subscription = output;
data.company.address1 = companyAddress1;
data.company.company_name = companyName;
data.company.address2 = companyAddress2;
data.company.city = companyCity;
data.company.zipcode = companyZipcode;

$.ajax({
    type: 'POST',
    url: 'my url',
    data: data,
    crossDomain: true,
    success: function (msg) {
    },
    error: function (request, status, error) {
    }
});

I also tried... 我也试过......

data.company = {"company_name":"abc", "address1":"abc", "date_of_subscription":"date", "zipcode":"your zipcode", "city":"city name"};

It is creating a user and a userprofile but it won't create the company 它正在创建用户和用户配置文件,但它不会创建公司

The problem was I never stringified my object. 问题是我从未对我的对象进行过字符串化。 Once I did that it worked perfectly. 一旦我这样做,它完美地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM