Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
axios post user to userProfile

So, I Have:

UserProfile:

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

Order:

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);
        }
    };
...

Question is:

User creation works fine, its create the user, it shows at the rest-api, and .db

How to create UserProfile? How I can add user, which I created first, and the add empty orders list??

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you need to set the OrderSerializer in the UserProfileSerializer.

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

Then in post API, you need to upload user_id and orders like the following. Here I assume user has already been created and orders need to be created.

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

Of course, you can create user when create user profile, but in order to do that, you can change a code little bit.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda