Django Form With Foreign Key

会有一股神秘感。 提交于 2019-12-08 11:26:50

问题


I've made a model with foreign keys in order to save some typing, and I think it also looks cleaner this way:

class Model_Sub( models.Model ):
    some_fields

class Model_Main( models.Model ):
    field_1 = models.ForeignKey( Model_Sub, related_name="sub_field_1" )
    field_2 = models.ForeignKey( Model_Sub, related_name="sub_field_2" )

But when I want my users to submit the form, I want new instances of the sub model, not from a query set. I want the Model_Sub to be seamlessly included with the main model as a form. Is there anyway to achieve this using ModelForm?

Thanks for the help

David


回答1:


I think you want to use two models forms from your Model_Sub class then use them to create your Main_Model object

class SubForm(models.ModelForm):
    class Meta:
        model = Sub_Model

def your_view(request):
    if request.method == 'POST':
        form1 = SubForm(request.POST, prefix='no1')
        form2 = SubForm(request.POST, prefix='no2')
        if form1.is_valid() and form2.is_valid():
           main_model = Main_Model(field1 = form1.save(),
                                   field2 = form2.save())
           main_model.save()
           #...
     else:
         form1 = SubForm(prefix = 'no1')
         form2 = SubForm(prefix = 'no2')
     return render(request, 'your_template.html', {'form1': form1,
                                                   'form2': form2})


来源:https://stackoverflow.com/questions/15145774/django-form-with-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!