【问题标题】:axios post user to userProfileaxios 将用户发布到 userProfile
【发布时间】:2022-06-25 20:20:18
【问题描述】:

所以,我有:

用户资料:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', unique=False)
    orders = models.ManyToManyField(Order, blank=True)

订单:

class Order(models.Model):
    car_brand = models.CharField(max_length=30)
    car_model = models.CharField(max_length=30)
    repair_type = models.CharField(max_length=30)

Register.js:

...
// Handling the form submission
    const handleSubmit = (e) => {
        e.preventDefault();
        if (name === '' || email === '' || password === '') {
            setError(true);
        } else {


            console.log('component Register registering ')


            let user = {
                username: name,
                email: email,
                password: password,
                is_active: false,
            }


            axios.post('http://localhost:8000/api/users/', {
                username: name,
                email: email,
                password: password,
                is_active: false,
            })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error.response);
                });

            axios.post('http://localhost:8000/api/profiles/', {
                user: null,
                orders: []
            })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error.response);
                });


            setSubmitted(true);
            setError(false);
        }
    };
...

问题是:

用户创建工作正常,它创建用户,它显示在rest-api和.db中

如何创建用户档案?如何添加我首先创建的用户和添加空订单列表??

【问题讨论】:

  • 您是否为UserProfile 创建了序列化程序?
  • @DavidLu 是的。 class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user', 'orders']

标签: javascript reactjs django-rest-framework axios


【解决方案1】:

我认为您需要在UserProfileSerializer 中设置OrderSerializer

class UserProfileSerializer(serializers.ModelSerializer):
    orders = OrderSerializer(many = True)
    user_id = serializers.IntegerField(write_only = True)
    user = UserSerializer(read_only = True)

    class Meta:
        model = UserProfile
        fields = ['user', 'orders', 'user_id']
    
    def create(self, validated_data):
        order_ids = []
        order_data = validated_data.pop('orders')
        for order_item in order_data:
            new_order = Order.objects.create(**order_item)
            order_ids.append(new_order.id)
        new_profile = UserProfile.objects.create(user_id = validated_data['user_id'])
        new_profile.set(order_ids)
        return new_profile

然后在 post API 中,您需要上传 user_id 和订单,如下所示。这里我假设已经创建了用户并且需要创建订单。

{
    "user_id": 1,
    "orders": [
        {
            "car_brand": "...",
            "car_model": "...",
            "repair_type": "..."
        },
        ...
    ]
}

当然,您可以在创建用户配置文件时创建用户,但是为了做到这一点,您可以稍微更改一下代码。

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2019-01-08
    • 2020-12-15
    • 2019-03-03
    • 2020-02-15
    • 2021-11-13
    • 2022-11-12
    • 2018-06-20
    • 2020-07-01
    相关资源
    最近更新 更多