如何保存Django ModelFormSet? [英] How to save Django ModelFormSet?

查看:41
本文介绍了如何保存Django ModelFormSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在非常绝望,我无法弄清楚.对我来说,这应该很容易做到,但是我没有找到任何能解释这一点的答案.

I'm quite desperate now and I cannot figure this out. To me it should be easy to do, but I have not come across any answers that explains this.

两个模型之间没有外键:

Two models with no foreign keys between them:

class Employee(models.Model):
    surname = models.CharField(max_length=100)
    name = models.CharField(max_length=100)


class Salary(models.Model):
    date = models.DateField(auto_now_add=True)
    surname = models.CharField(max_length=100)
    name = models.CharField(max_length=100)
    salary = models.DecimalField(max_digits=20, decimal_places=2)

一个要保存到ModelB的modelformset.

One modelformset to save to ModelB.

SalaryFormSet = modelformset_factory(Salary, extra=0)

然后进入views.py:

Then in views.py:

def createForm(request):
    formset = SalaryFormSet(queryset=Employee.objects.all())
    return render(request, 'formfile.html', {'formset': formset})

def submitForm(request)
    f = ModelBFormSet(request.POST)
    if f.is_valid():
        f.save()
        return HttpResponse('Submitted successfully')
    else:
        return HttpResponse(f.errors, request.POST)

在formfile.html中:

In formfile.html:

<form action="submitForm/" method="post">
    {{ formset.management_form }}
    <table>
        {{ formset }}
    </table>
    {% csrf_token %}
    <input type="submit" value="Submit">
</form> 

点击提交"后,该表单集就被解析为无效和f.errors状态(对于Employee中的每一行):

As soon as I hit Submit, the formset is parsed as invalid and f.errors states (for each row in Employee):

<ul class="errorlist"><li>id<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

我只想将Employee中所有行的姓氏和名字预先加载到SalaryFormSet中,我应该为每一行输入薪水并将其保存到Salary.工资中的记录不应更新,但应创建一个新条目.

I just want to have surname and name from all rows in Employee preloaded into SalaryFormSet, and I should enter salary for each row and save them to Salary. The records in Salary should not be updated, but a new entry should be created.

Employee模型已经具有从管理站点创建的记录.随着员工薪资的增加,我将从薪资模型生成薪资单,并从最近的日期获取相关薪水.

The Employee model already has records created from the admin site. As employees' salaries increase, I will generate payslips from Salary model and capture the relevent salary from the latest date.

如果我将queryset更改为queryset = Salary.objects.none()并将SalaryFormSet更改为extra = 2,则该模板将显示为空.如果我手动输入姓,名和薪水,则表单集可以正确保存.工资中有两个新条目.为什么我不能只预加载名称(我应该将它们加载为str()吗?)并手动添加薪水?

If I change the queryset to queryset=Salary.objects.none() and change SalaryFormSet to extra=2, the template is rendered empty. If I insert surnames, names and salary manually, the formset saves correctly. Two new entries in Salary. Why can't I just have the name preloaded (should I load them as str()?) and manually add the salary?

推荐答案

将雇员"的查询集传递给薪金"表单集的实例是没有意义的.我认为,无论出于何种原因,您都试图将这两个模型完全分开,并且每次都想创建新的Salary实例,最好传递一组 initial 数据.

As I said in the comment, it doesn't make sense to pass a queryset of Employees to the instantiation of the Salary formset. I think given you're trying to keep these two models completely separate for whatever reason, and you want to create new Salary instances each time, you would be better off just passing a set of initial data.

这有点棘手,因为initial仅适用于额外的表单,而且extra是由formset工厂设置的,因此您需要在视图中进行操作.像这样:

This is slightly tricky, because initial only applies to extra forms, and extra is set by the formset factory, so you need to do it in the view. Something like this:

employees = Employee.objects.values('name', 'surname')
SalaryFormSet = modelformset_factory(Salary, extra=len(employees))
formset = SalaryFormSet(initial=employees, queryset=Salary.objects.none())

这篇关于如何保存Django ModelFormSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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