Django 2 models 1 form

前端 未结 3 845
轻奢々
轻奢々 2020-12-10 22:12

So, I\'m still a total noob at Django and I was wondering how to do the following:

So lets say that I have something like the below code:

class UserP         


        
相关标签:
3条回答
  • 2020-12-10 22:37

    This kind of problem is what inline formsets are designed for.

    0 讨论(0)
  • 2020-12-10 22:39

    The way I did it was to create a form based on the first model, and then to create a form based on the second model that inherits the first form. Meaning:

    class UserProfileForm(ModelForm): ...

    class UserProfileOtherForm(UserProfileForm): ...

    And pass the UserProfileOtherForm to form template. It worked for me. Not sure if there is a simpler approach.

    0 讨论(0)
  • 2020-12-10 22:46

    You can create two separate ModelForm classes. But in your view, you have to add a prefix to their instances.

    def viewname(request):
        if request.method == 'POST':
            form1 = forms.YourForm(request.POST, prefix="form1")
            form2 = forms.YourOtherForm(request.POST, prefix="form2")
            if form1.is_valid() and form2.is_valid():
                # process valid forms
        else:
            form1 = forms.YourForm(prefix="form1")
            form2 = forms.YourOtherForm(prefix="form2")
    
        ....
    

    Using a prefix ensures that fields with similar names are not mixed up.

    0 讨论(0)
提交回复
热议问题