问题描述
我有一个Django管理表单。
现在我想用基于我的模型的数据填充它的初始字段。因此,我尝试了以下操作:
I have a Django admin form.And now I want to fill it's initial field with data based on my model. So I tried this:
class OrderForm(forms.ModelForm):
class Meta:
model = Order
email = CharField(initial="null", widget=Textarea(attrs={'rows': 30, 'cols': 100}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
products = kwargs['instance'].products.all()
self.message = purchase_message % (
"".join(["<li>" + p.name + ": " + str(p.price) + "</li>" for p in products]),
reduce(lambda x, y:x + y.price, products, 0)
)
# and here I have a message in self.message variable
super(OrderForm, self).__init__(*args, **kwargs)
此时,我不知道如何在呈现小部件之前访问电子邮件字段来设置其初始值。我该怎么办?
At this point i don't know how to access email field to set it's initial value before widget is rendered. How can i do this?
推荐答案
我不太确定要将电子邮件设置为什么,但是您可以设置许多地方的初始值。
I'm not too sure what you need to set email to, but You can set the initial values in lots of different places.
您的函数 def init()缩进不正确,我猜这是一个错字?另外,为什么要专门为电子邮件表单字段提供 TextInput ?默认情况下,它已经呈现了此小部件
Your function def init() isn't indented correctly which i guess is a typo? Also, why are you specifically giving the email form field a TextInput? It already renders this widget by default
您可以在表单的初始化后设置电子邮件的初始值( def __ init __(self))
You can set the email's initial value in your form's initialized (def __ init __(self))
(self.fields['email'].widget).initial_value = "something"
或在模型中。py
email = models.CharField(default="something")
或您在form.py
or as you have in forms.py
email = models.CharField(initial="something")
这篇关于Django AdminForm字段默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!