如何将初始参数传递给django的ModelForm实例? [英] How to pass initial parameter to django's ModelForm instance?

查看:1281
本文介绍了如何将初始参数传递给django的ModelForm实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特殊的例子是这样的:



我有一个交易模型,字段来自的(均为 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):
添加和编辑备份的表单。

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',)
pre>

创建如下表单:

  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 are ForeignKeys to auth.User model) and amount. In my form, I'd like to present the user 2 fields to fill in: amount and from (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 the user.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 web request.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆