【问题标题】:Problems with updating a Django form with information from another model使用来自另一个模型的信息更新 Django 表单的问题
【发布时间】:2021-11-16 15:34:56
【问题描述】:

我基本上是在构建功能来使用我的 models.py 中一个表中的值更新表单,表单将使用该表(潜在客户)填充初始值,并且在提交信息后,表单将填充另一个模型(线索)

这是我的models.py

class Leads(models.Model):

    project_id = models.BigAutoField(primary_key=True, serialize=False)
    created_at = models.DateTimeField(auto_now_add=True)
    expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD')
    expected_licenses = models.IntegerField(blank=True)
    country = CountryField(blank_label='(select_country)')
    status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled')], max_length=10)
    estimated_closing_date = models.DateField(blank=True)
    services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'),
                                  ('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'),
                                  ('Software License', 'Software License'),
                                  ('Software Development','Software Development')], max_length=40)
    agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE)
    company = models.ForeignKey(Company,on_delete=models.CASCADE)
    point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE)
    updated_at = models.DateTimeField(auto_now=True)

class Deal(models.Model):
    project_id = models.ForeignKey(Leads, on_delete=models.CASCADE, default='id')
    agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent")
    service = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='service')
    closing_date = models.DateField(auto_now_add=True)
    client = models.ForeignKey(Client, on_delete=models.CASCADE,default='client')
    licenses = models.ForeignKey(Leads,on_delete=models.CASCADE, related_name='license')
    revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
    comments = models.TextField(blank=True,null=True)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)



Forms.py

class NewDealForm(forms.ModelForm):
    class Meta:
        model = Deal
        fields = ['project_id','agent','client','company','service', 'licenses','revenue','comments']


@login_required
def close_lead(request):
    if request.method == 'POST':

        deal_form = NewDealForm(request.POST)
        print(deal_form)
        if deal_form.is_valid():
            deal_form.save()
            messages.success(request, 'You have successfully updated the status from open to Close')
            id = request.GET.get('project_id', '')
            obj = Leads.objects.get(project_id=id)
            obj.status = "Closed"
            obj.save(update_fields=['status'])

            return HttpResponseRedirect(reverse('dashboard'))
        else:

            messages.error(request, 'Error updating your Form')
    else:
        id = request.GET.get('project_id', '')
        obj = get_object_or_404(Leads, project_id=id)

        m = obj.__dict__
        keys = Leads.objects.get(project_id=m['project_id'])

        form_dict = {'project_id': keys.project_id,
                     'agent': keys.agent,
                     'client': keys.point_of_contact,
                     'company': keys.company,
                     'service': keys.services,
                     'licenses':keys.expected_licenses
                     }
        print(form_dict)
        form = NewDealForm(request.POST or None, initial=form_dict)

    return render(request,
                  "account/close_lead.html",
                  {'form': form})

我的问题是为什么除了服务字段之外的所有值都被填充?

有人知道吗,我的字典的输出看起来是正确的,它包含服务信息,但不知何故这没有传递给表单?

{'project_id': 1, 'agent': , 'client': , 'company': , 'service': 'Software License' , '许可证': 3}

如你所见,服务是有实际价值的

【问题讨论】:

    标签: python django django-models django-views django-forms


    【解决方案1】:

    在您的 Deal 模型中,services 字段是 Leads 的外键:

    class Deal(models.Model):
        service = models.ForeignKey(Leads)
    

    你尝试用Leads中的services字段的值填充它,那是一个字符串。

    class Leads(models.Model):
        services = models.CharField()
    
    

    查看您的模型,您需要使用 Leads 实例填充 services 字段:

    
    form_dict = {'project_id': keys.project_id,
                         'agent': keys.agent,
                         'client': keys.point_of_contact,
                         'company': keys.company,
                         'service': keys, # <-- point to Leads
                         'licenses':keys.expected_licenses
                         }
    

    【讨论】:

    • Tonio - 谢谢,但这就是我正在做的,keys = Leads.objects.get(project_id=m['project_id']) ,变量 keys 正在获取特定模型的对象,如果我只添加键,结果是一个整数,在这种情况下,线索模型中线索(观察)的 id
    • 参见 = {'project_id': 3, 'agent': , 'client': , 'company': , 'service' : , 'licenses': 4}
    • @FranciscoColina,它不是整数,它是Leads 的一个实例。我认为这是 NewDealForm 期望在 service 字段中找到的内容。我不知道您应该使用什么确切的实例。
    • 根据我上面的代码,它在技术上应该是 keys.services
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多