【问题标题】:how to save parent , child and grand child forms in one submit - django如何在一个提交中保存父母、孩子和孙子表格 - django
【发布时间】:2022-01-01 17:47:55
【问题描述】:

我正在为一家移动贸易公司构建一个应用程序,情况如下:每张发票都有一个唯一的invoice number,每个唯一的date 有几个phone models,每个手机型号都有一个IMEI这是我设计数据库模型的方式

class Collection(models.Model):
    admin = models.ForeignKey(User,on_delete=models.PROTECT)
    company = models.ForeignKey(Company,on_delete=models.PROTECT)
    invoice_no = models.IntegerField(unique=True)
    collection_date = models.DateTimeField(default=timezone.now)

class MobileCollection(models.Model):
    collection = models.ForeignKey(Collection,on_delete=models.PROTECT,related_name='collections')
    mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category')
    qnt = models.IntegerField()
    price = models.DecimalField(decimal_places=3,max_digits=20)

class Imei(models.Model):
    mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT)
    imei = models.CharField(max_length=15,unique=True)

我必须一次性提交所有这些!我不确定如何构建它的视图,而MobileCollection 模型应该动态增加,并且MobileCollection 中的qnt 字段应该增加Imei 表单应该增加,例如如果qnt=10 我们应该添加10 Imei 表格,我考虑过inlineformset_factory,但在我的情况下它不起作用。请问有没有更好的方法来实现这一目标?提前谢谢你

【问题讨论】:

    标签: python jquery django database-design


    【解决方案1】:

    在上下文中发送多个表单,并以与处理一个表单相同的方式处理所有表单。

    例子:

    class MyView(View):
        template_name = 'my_template.html'
        collection_form = CollectionForm
        mcollection_form = MobileCollectionForm
        # and so on..
    
        def get(self, request, *args, **kwargs):
            context = {
                'collection_form': collection_form,
                'mcollection_form': mobile_collection_form
            }
            return render(request, self.template_name, context=context)
    
        def post(self, request, *args, **kwargs):
            collection_form = self.collection_form(request.POST)
            mcollection_form = self.mcollection_form(request.POST)
    
            if collection_form.is_valid() and mcollection_form.is_valid():
                collection_form.save()
                mcollection_form.save()                
                return # your response, and so on..
        return # your forms above in the post method if the forms are not valid
    

    【讨论】:

    • 那么Imei 在哪里,这不是我要的朋友
    • @HunarMohammed 是的,它在哪里?您必须自己填写,这里没有人会为您编写代码。 100% 清楚您需要从这里做什么。
    • 我知道你写了 mate ,我也添加了Imei 我只是在寻找更好的方法
    • 问题是如何一次性发送所有三种表格。即使你有多个表单,你也没有同一个表单的多个实例,就像在表单集中一样。如果您有一个待办事项列表,那么同时只能输入一个待办事项会很无聊,因此您可以为同一字段获取多个输入并一次发送所有内容。在这里你也有很多输入,我没有看到同时需要的三个对象中的每一个都有一个以上的值。
    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多