如何将初始参数传递给django的ModelForm实例? [英] How to pass initial parameter to django's ModelForm instance?
问题描述
我有一个交易模型,字段来自的 ,
至
(均为 ForeignKey
s至 auth.User
模型)和金额
。以我的形式,我想提供用户2个字段填写:金额
和从
( to
将自动设置为视图功能中的当前用户)。
显示 ForeignKey
是一个选择框。但是我想要到达的地方是将选择限制在 user.peers
queryset成员中(所以人们只能注册与对等体的交易,并且不会被淹没所有系统用户)。
我尝试将ModelForm更改为这样:
class AddTransaction(forms.ModelForm):
from = ModelChoiceField(user.peers)
amount = forms.CharField(label ='How much?')
class Meta:
model = models.Transaction
但是,似乎我必须通过 ModelChoiceField
的选项的查询器,在这里 - 我无法访问网络 request.user
对象。
如何将表单中的选项限制为依赖用户的选项?
使用以下方法(希望足够清楚):
class BackupForm(ModelForm):
pre>
添加和编辑备份的表单。
def __init __(self,* args,* * kwargs)
systemid = kwargs.pop('systemid')
super(BackupForm,self).__ init __(* args,** kwargs)
self.fields ['units'] = forms.ModelMultipleChoiceField(
required = False,
queryset = Unit.objects.filter(system__id = systemid),
widget = forms.SelectMultiple(attrs = {'title':_添加单元)}))
class Meta:
model = Backup
exclude =('system',)
创建如下表单:
form_backup = BackupForm .POST,
instance = Backup,
systemid = system.id)
form_backup = BackupForm(ini tial = form_backup_defaults,
systemid = system.id)
希望有帮助!如果您需要我深入解释,请通知我。
The particular case I have is like this:
I have a Transaction model, with fields:
from
,to
(both areForeignKey
s toauth.User
model) andamount
. In my form, I'd like to present the user 2 fields to fill in:amount
andfrom
(to
will be automaticly set to current user in a view function).Default widget to present a
ForeignKey
is a select-box. But what I want to get there, is limit the choices to theuser.peers
queryset members only (so people can only register transactions with their peers and don't get flooded with all system users).I tried to change the ModelForm to something like this:
class AddTransaction(forms.ModelForm): from = ModelChoiceField(user.peers) amount = forms.CharField(label = 'How much?') class Meta: model = models.Transaction
But it seems I have to pass the queryset of choices for
ModelChoiceField
right here - where I don't have an access to the webrequest.user
object.How can I limit the choices in a form to the user-dependent ones?
解决方案Use the following method (hopefully it's clear enough):
class BackupForm(ModelForm): """Form for adding and editing backups.""" def __init__(self, *args, **kwargs): systemid = kwargs.pop('systemid') super(BackupForm, self).__init__(*args, **kwargs) self.fields['units'] = forms.ModelMultipleChoiceField( required=False, queryset=Unit.objects.filter(system__id=systemid), widget=forms.SelectMultiple(attrs={'title': _("Add unit")})) class Meta: model = Backup exclude = ('system',)
Create forms like this:
form_backup = BackupForm(request.POST, instance=Backup, systemid=system.id) form_backup = BackupForm(initial=form_backup_defaults, systemid=system.id)
Hope that helps! Let me know if you need me to explain more in depth.
这篇关于如何将初始参数传递给django的ModelForm实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!