带有外键的 Django 表单 [英] Django Form With Foreign Key

查看:25
本文介绍了带有外键的 Django 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了节省一些输入,我制作了一个带有外键的模型,而且我认为这样看起来也更干净:

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" )

但是当我希望我的用户提交表单时,我想要子模型的新实例,而不是来自查询集.我希望 Model_Sub 作为表单无缝包含在主模型中.有没有办法使用 ModelForm 来实现这一点?

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?

感谢您的帮助

大卫

推荐答案

我认为您想使用 Model_Sub 类中的两个模型表单,然后使用它们来创建您的 Main_Model 对象

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

这篇关于带有外键的 Django 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆