简体   繁体   English

Django形式与对象列表

[英]Django form with object list

I have a problem to get back an object from a django form after submission. 我有一个问题是在提交后从django表单中取回一个对象。

I have an object list (filled with MyObject , not a django model) filled by another python package. 我有一个由另一个python包填充的对象列表(用MyObject填充,而不是django模型)。

In models.py , I have : models.py ,我有:

class MyObjectForm(forms.Form):

    def __init__(self, *args, **kwargs):
        # Get the list
        myobjects = kwargs.pop('myobjects')
        super(MyObjectForm, self).__init__(*args, **kwargs)
        choices = [(o, o.name) for o in myobjects]
        self.fields["my_objects"] = forms.TypedChoiceField(choices=choices)

For information, the HTML looks OK. 有关信息,HTML看起来没问题。

In views.py , form.is_valid() is always False when I click on the submit button. views.py ,当我单击提交按钮时, form.is_valid()始终为False Is there a problem ? 有问题吗?

When I change models.py with : 当我更改models.py时:

self.fields["my_objects"] = forms.TypedChoiceField(choices=choices, required=False)

In views.py , form.is_valid() is True but I can't get back my objet MyObject (I get an empty value). views.pyform.is_valid()True但我无法取回我的objet MyObject (我得到一个空值)。 Is that possible ? 那可能吗 ? And if yes, how can I do that ? 如果是的话,我该怎么做?

Look at what you used as choices... MyObject instances, really ? 看看你用作选择的东西...... MyObject实例,真的吗? How is a MyObject instance supposed to be sent to a browser as part of a HTML form and then back to your server thru a POST request body ? 如何将MyObject实例作为HTML表单的一部分发送到浏览器,然后通过POST请求主体返回到服务器?

If you have some persistant unique identifier for each of your MyObject instances, use this for your choices, ie 如果您的每个MyObject实例都有一些持久的唯一标识符,请将其用于您的选择,即

choices = [(o.some_stable_and_unique_id, o.name) for o in myobjects]

Note that it won't solve all of your issues... You'll then have to subclass TypedChoiceField to retrieve the object based on its "id" etc. 请注意,它不会解决您的所有问题......然后您必须TypedChoiceField以根据其“id”等检索对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM