从复杂的Django表单获取POST数据?

时间:2021-09-30 15:59:45

I have a Django form that uses a different number of fields based on the year/month. So I create the fields in the form like this:

我有一个Django表单,根据年/月使用不同数量的字段。所以我在表单中创建如下字段:

for entry in entry_list:
    self.fields[entry] = forms.DecimalField([stuffhere])

but now I don't know how to get the submitted data from the form.

但现在我不知道如何从表单中获取提交的数据。

Normally I would do something like:

通常我会做类似的事情:

form.cleaned_data["fieldname"]

but I don't know what the names of the fields are. The debug screen shows my POST data as simply "Entry Object" with a value of "u''". Calling POST.lists() doesn't show anything.

但我不知道这些字段的名称是什么。调试屏幕将我的POST数据显示为“Entry Object”,其值为“u”。调用POST.lists()不会显示任何内容。

I am sure I am missing something obvious, but I've been stuck on this for a few days too many. Is there a better way to do this? Is all of the data in the request object, but I just don't know how to use it?

我确信我错过了一些明显的东西,但我已经被困在这几天了太多。有一个更好的方法吗?是请求对象中的所有数据,但我只是不知道如何使用它?

Here is the code for the model/form/view: http://pastebin.com/f28d92c0e

以下是模型/表单/视图的代码:http://pastebin.com/f28d92c0e

Much Thanks!

EDIT:

I've tried out both of the suggestions below. Using formsets was definitely easier and nicer.

我已经尝试了以下两个建议。使用formset肯定更容易和更好。

2 个解决方案

#1


I think you might be better off using formsets here. They're designed for exactly what you seem to be trying to do - dealing with a variable number of items within a form.

我想你最好在这里使用formset。它们的设计完全符合您的目的 - 处理表单中可变数量的项目。

#2


In this line:

在这一行:

self.fields[entry] = forms.DecimalField(max_digits=4, decimal_places=1, label=nice_label)

self.fields [entry] = forms.DecimalField(max_digits = 4,decimal_places = 1,label = nice_label)

entry is a model instance. But fields are keyed by field names (strings). Try something like:

entry是一个模型实例。但字段由字段名称(字符串)键入。尝试类似的东西:

self.fields[entry.entry_name] = forms.Decimal(...)

self.fields [entry.entry_name] = forms.Decimal(...)

(substitute appropriate for "entry_name").

(替换为“entry_name”)。

#1


I think you might be better off using formsets here. They're designed for exactly what you seem to be trying to do - dealing with a variable number of items within a form.

我想你最好在这里使用formset。它们的设计完全符合您的目的 - 处理表单中可变数量的项目。

#2


In this line:

在这一行:

self.fields[entry] = forms.DecimalField(max_digits=4, decimal_places=1, label=nice_label)

self.fields [entry] = forms.DecimalField(max_digits = 4,decimal_places = 1,label = nice_label)

entry is a model instance. But fields are keyed by field names (strings). Try something like:

entry是一个模型实例。但字段由字段名称(字符串)键入。尝试类似的东西:

self.fields[entry.entry_name] = forms.Decimal(...)

self.fields [entry.entry_name] = forms.Decimal(...)

(substitute appropriate for "entry_name").

(替换为“entry_name”)。