B
B
bielikovv2022-04-16 10:25:58
Django
bielikovv, 2022-04-16 10:25:58

How to make the form save data in two models?

I have a view that renders a form. During its normal presentation to the user, I filled in all the fields using instance and initial, but when submitting the form, I can transfer values ​​from only one form to instance, which refers to the model specified in the field (I expanded the user form). If I pass request.user, only the data of this model is saved, and vice versa - another one is saved through request.user.profile. You need to make sure that saving occurs in both. Here you need to somehow combine instance, how to do it?

def show_user_form(request):
    if request.method == 'POST':
        form = RedactInfoUserForm(request.POST, request.FILES, instance=request.user.profile)
        if form.is_valid():
            form.save()
            redirect('profile')
    else:
        form = RedactInfoUserForm(instance=request.user.profile, initial={'first_name':request.user.first_name, 'last_name':request.user.last_name, 'email':request.user.email })
    return render(request, 'musiccloud/user_profile.html', {'form':form})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kadabrov, 2022-04-16
@bielikovv

gorgeous article, learn to use the search
https://habr.com/ru/post/313764/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question