将初始值传递给 django 中的模型表单

发布于 2024-12-06 07:51:36 字数 728 浏览 0 评论 0原文

如何将字段的初始值传递给模型表单。我有类似下面的代码

class ScreeningForm(forms.ModelForm):
    class Meta:
        model = Screening

    def __init__(self, *args, **kwargs):
        super(ScreeningForm, self).__init__(*args, **kwargs)
        self.fields['blood_screen_type'] =  CommaSeparatedCharField(
            label=self.fields['blood_screen_type'].label,
            initial=self.fields['blood_screen_type'].initial,
            required=False,
            widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES)
        )

class ScreeningAdmin(admin.ModelAdmin):
    #form = ScreeningForm
    form = ScreeningForm(initial={'log_user':get_current_user()})

现在我想传递 Person 类的字段的初始值。我怎样才能做到这一点?

How can I pass an initial value for a field to a model form. I have something like the following code

class ScreeningForm(forms.ModelForm):
    class Meta:
        model = Screening

    def __init__(self, *args, **kwargs):
        super(ScreeningForm, self).__init__(*args, **kwargs)
        self.fields['blood_screen_type'] =  CommaSeparatedCharField(
            label=self.fields['blood_screen_type'].label,
            initial=self.fields['blood_screen_type'].initial,
            required=False,
            widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES)
        )

class ScreeningAdmin(admin.ModelAdmin):
    #form = ScreeningForm
    form = ScreeningForm(initial={'log_user':get_current_user()})

Now I want to pass an initial value for a field of the Person class. How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七秒鱼° 2024-12-13 07:51:36

您可以将初始值传递给 ModelForm,如下所示:

form = PersonForm(initial={'fieldname': value})

例如,如果您想将初始 age 设置为 24,将 name 设置为 “John Doe”

form = PersonForm(initial={'age': 24, 'name': 'John Doe'})

更新

我认为这解决了您的实际问题:

def my_form_factory(user_object):
    class PersonForm(forms.ModelForm):
        # however you define your form field, you can pass the initial here
        log_user = models.ChoiceField(choices=SOME_CHOICES, initial=user_object)
        ...
    return PersonForm

class PersonAdmin(admin.ModelAdmin):
    form = my_form_factory(get_current_user())

You can pass initial value to a ModelForm like this:

form = PersonForm(initial={'fieldname': value})

For example, if you wanted to set initial age to 24 and name to "John Doe":

form = PersonForm(initial={'age': 24, 'name': 'John Doe'})

Update

I think this addresses your actual question:

def my_form_factory(user_object):
    class PersonForm(forms.ModelForm):
        # however you define your form field, you can pass the initial here
        log_user = models.ChoiceField(choices=SOME_CHOICES, initial=user_object)
        ...
    return PersonForm

class PersonAdmin(admin.ModelAdmin):
    form = my_form_factory(get_current_user())
爱本泡沫多脆弱 2024-12-13 07:51:36

如果有人仍然想知道,可以通过以下方法为管理表单设置初始值:

class PersonAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(PersonAdmin, self).get_form(request, obj=obj, **kwargs)
        form.base_fields['log_user'].initial = get_current_user()
        return form

请注意,您还可以通过 URL 参数设置初始值:例如 /admin/person/add?log_user=me

In case anyone is still wondering, the following works to set initial values for an Admin form:

class PersonAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(PersonAdmin, self).get_form(request, obj=obj, **kwargs)
        form.base_fields['log_user'].initial = get_current_user()
        return form

Note that you can also set initial values via URL parameters: e.g. /admin/person/add?log_user=me

尝蛊 2024-12-13 07:51:36

由于您的 ModelForm 绑定到 Person-Model,您可以传递 Person-Instance:

form = PersonForm(instance=Person.objects.get(foo=bar)

或覆盖 ModelForm 的 init-method:

class PersonForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super(PersonForm, self).__init__(*args, **kwargs)
       self.fields['foo'].value = 'bar'

    class Meta:
        model = Person
        exclude = ['name']

这是未经测试的。我不确定“值”是否正确,我这里没有 Django 安装,但基本上这就是它的工作方式。

As your ModelForm is bound to the Person-Model, you could either pass a Person-Instance:

form = PersonForm(instance=Person.objects.get(foo=bar)

or overwrite the ModelForm's init-method:

class PersonForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super(PersonForm, self).__init__(*args, **kwargs)
       self.fields['foo'].value = 'bar'

    class Meta:
        model = Person
        exclude = ['name']

This is untested. I'm not sure whether "value" is correct, I'm not having a Django-Installation here, but basically this is the way it works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文