Django Forms:传递参数以形成

编程入门 行业动态 更新时间:2024-10-25 12:20:35
本文介绍了Django Forms:传递参数以形成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何将参数传递给我的表单?

How do I pass a parameter to my form?

someView().. form = StylesForm(data_dict) # I also want to pass in site_id here. class StylesForm(forms.Form): # I want access to site_id here

根据以下答案编辑:

someView().. form = StylesForm(data_dict, site_id = 1) class StylesForm(forms.Form): def __init__(self,*args,**kwargs): self.site_id = kwargs.pop('site_id') super(StylesForm,self).__init__(*args,**kwargs) height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))

推荐答案

你应该定义__init__您的表单的方法,如下所示:

You should define the __init__ method of your form, like that:

class StylesForm(forms.Form): def __init__(self,*args,**kwargs): self.site_id = kwargs.pop('site_id') super(StylesForm,self).__init__(*args,**kwargs)

当然,您无法访问self.site_id直到对象被创建,所以行:

of course you cannot access self.site_id until the object has been created, so the line:

height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))

没有任何意义。您必须在窗体创建后将该属性添加到窗口小部件。尝试这样的东西:

makes no sense. You have to add the attribute to the widget after the form has been created. Try something like this:

class StylesForm(forms.Form): def __init__(self,*args,**kwargs): self.site_id = kwargs.pop('site_id') super(StylesForm,self).__init__(*args,**kwargs) self.fields['height'].widget = forms.TextInput(attrs={'size':site_id}) height = forms.CharField()

(未测试)

更多推荐

Django Forms:传递参数以形成

本文发布于:2023-10-12 01:29:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   Django   Forms

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!