如何重用django表单进行搜索?

时间:2023-01-24 11:00:53

I am programming an application in django, and I have a model where I defined some fields that are necessary to be filled. This way, when te user doesn't fill one of these fields, Django authomatically indicates to the user to fill it to create the specific object defined by the model.

我在django中编写应用程序,我有一个模型,我定义了一些必须填写的字段。这样,当用户没有填写其中一个字段时,Django会自动向用户指示填充它以创建模型定义的特定对象。

But myquestion comes here: I want to reuse the same form to search objects defined by that model. And in this case, all the fields that before were necessary, now are OPTIONAL. But, as I have already defined the model so that the fields are necessary, django doesn´t let me define those fields as optional.

但问题来自:我想重复使用相同的表单来搜索该模型定义的对象。在这种情况下,之前所有必需的字段现在都是可选的。但是,由于我已经定义了模型以便字段是必需的,所以django不允许我将这些字段定义为可选字段。

Is there any way to reuse that form where the fields are necessary, but making them OPTIONAL? Or I must create another different model or form in html? I know that creating another form manually in the html code the problem is solver, but I have curiosity to know if it can be reused.

有没有办法在需要字段的地方重用那个表单,但是让它们可选?或者我必须在html中创建另一个不同的模型或表单?我知道在html代码中手动创建另一个表单问题是求解器,但我有好奇心知道它是否可以重用。

Thank you so much!

非常感谢!

1 个解决方案

#1


1  

You can programmatically change properties of a field within a form using its fields dictionary. So you could create a new form class that is derived from your current form class and in its __init__ set the required property of the fields you desired to be optional to be False like so:

您可以使用其字段字典以编程方式更改表单中字段的属性。因此,您可以创建一个从当前表单类派生的新表单类,并在其__init__中设置您希望可选的字段的必需属性为False,如下所示:

self.fields['title'].required = False

#1


1  

You can programmatically change properties of a field within a form using its fields dictionary. So you could create a new form class that is derived from your current form class and in its __init__ set the required property of the fields you desired to be optional to be False like so:

您可以使用其字段字典以编程方式更改表单中字段的属性。因此,您可以创建一个从当前表单类派生的新表单类,并在其__init__中设置您希望可选的字段的必需属性为False,如下所示:

self.fields['title'].required = False