Django表单-为模型中的每个对象创建一个表单,然后保存到相应的PK [英] Django forms - create a form for each object in model, and then save to the corresponding PK

查看:61
本文介绍了Django表单-为模型中的每个对象创建一个表单,然后保存到相应的PK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手(和一般编程人员)。抱歉,如果我使用了错误的词汇(请纠正我)。这就是我想要做的:

I'm new to django (and programming in general). Sorry if I used the wrong vocabulary (and please correct me). This is what i'm trying to do:

我有这个模型:

Class A(models.Model):
    name = models.CharField(max_length=100, null=True, default='John')

    first_number = models.FloatField(blank=True, default=1)

    second_number = models.FloatField(blank=True, default=2)

    third_number = models.FloatField(blank=True, default=3)

我有这种形式:

class Numbers(ModelForm):
    class Meta:
        model = A

        fields = ['first_number', 'second_number']

在我的模板中,我为a中的x创建了for(假设'a'是A.objects.all()):

In my template, I created a for for x in a (given that 'a' is A.objects.all()):

{% for x in a %}
{{form}}
{% endfor %}

但是,当我提交表格时,我无法获得相应的数字。对于创建的两个对象,我只保存在 first_number和 second_number中输入的最后一个数字。

When I submit the form, though, I cant get the corresponding numbers. I only saves the last number I enter in both 'first_number' and 'second_number' for the both objects that I created.

如何保存正确的值?

推荐答案

在循环中呈现这种形式的表单时,您在页面代码中会获得许多相同的表单,并且输入的数目也具有相同的名称 ;属性。如果将循环包含在单个标签中,则POST请求将始终发送表单中每个字段名称的最后一个值。

When you render forms like this in a loop you get a number of identical forms in your page code with a number of inputs with the same "name" attributes. If you include your loop into a single tag your POST request will always send the last values found inside form for each field name.

<form>
    <input name="first_number" value="1">
    <input name="first_number" value="2">
    <input name="first_number" value="3">
</form>

POST字典将包含{ first_number: 3}

POST dict will contain {"first_number": "3"}

这将呈现您的每个表单,但您一次只能提交一个表单:

This will render each of your form but you'll be able to submit only one at once:

{% for x in a %}
    <form>
         {{form}}
    </form>
{% endfor %}

如果您要处理相同的数据并将其作为列表发送,将需要使用前缀表单实例中的arg:

If you want to deal with identical data and send it as a list you'll need to use "prefix" arg in your form instances:

a = [Numbers(instance=x, prefix=str(x.pk)) for x in A.objects.all()]

#and then in a view
a = [Numbers(request.POST, instance=x, prefix=str(x.pk)) 
     for x in A.objects.all()]

if all([f.is_valid() for f in a]):
    for f in a:
        f.save(commit=True)

这是一个稍微原始的示例。在现实生活中,您可能希望向表单中添加一些隐藏字段,以将ID(例如json)列表传递给表单,然后对其进行遍历,而不是遍历数据库中的所有实例

This is a slightly primitive example. In real life you would probably like to add some hidden field to your form to pass a list of ids (as json maybe) to a form, and then iterate over it instead of all instances in your db

这篇关于Django表单-为模型中的每个对象创建一个表单,然后保存到相应的PK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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