Django的choicefield初始值

发布于 2024-12-11 16:15:28 字数 1493 浏览 0 评论 0原文

我遇到一个奇怪的问题,我似乎无法在 django 中的表单中设置其中一个字段的初始值。

我的模型字段是:

section = models.CharField(max_length=255, choices=(('Application', 'Application'),('Properly Made', 'Properly Made'), ('Changes Application', 'Changes Application'), ('Changes Approval', 'Changes Approval'), ('Changes Withdrawal', 'Changes Withdrawal'), ('Changes Extension', 'Changes Extension')))

我的表单代码是:

class FeeChargeForm(forms.ModelForm):
    class Meta:
        model = FeeCharge
        # exclude = [] # uncomment this line and specify any field to exclude it from the form

    def __init__(self, *args, **kwargs):
        super(FeeChargeForm, self).__init__(*args, **kwargs)
        self.fields['received_date'] = forms.DateField(('%d/%m/%Y',), widget=forms.DateTimeInput(format='%d/%m/%Y', attrs={'class': 'date'}))
        self.fields['comments'].widget.attrs['class']='html'
        self.fields['infrastructure_comments'].widget.attrs['class']='html'

我的视图代码是:

form = FeeChargeForm(request.POST or None)
form.fields['section'].initial = section

其中部分是传递给函数的 url 变量。我已经尝试过:

form.fields['section'].initial = [(section,section)]

也没有运气:(

有什么想法我做错了吗,或者有没有更好的方法来从 url var 设置此选择字段的默认值(在表单提交之前)?

提前致谢!

<强>更新:这似乎与URL变量有关..如果我使用:

form.fields['section'].initial = "Changes Approval"

它可以工作np..如果我HttpResponse(section)它输出正确。

I'm having a strange problem where I can't seem to set the initial value of one of the fields in my forms in django.

My model field is:

section = models.CharField(max_length=255, choices=(('Application', 'Application'),('Properly Made', 'Properly Made'), ('Changes Application', 'Changes Application'), ('Changes Approval', 'Changes Approval'), ('Changes Withdrawal', 'Changes Withdrawal'), ('Changes Extension', 'Changes Extension')))

My form code is:

class FeeChargeForm(forms.ModelForm):
    class Meta:
        model = FeeCharge
        # exclude = [] # uncomment this line and specify any field to exclude it from the form

    def __init__(self, *args, **kwargs):
        super(FeeChargeForm, self).__init__(*args, **kwargs)
        self.fields['received_date'] = forms.DateField(('%d/%m/%Y',), widget=forms.DateTimeInput(format='%d/%m/%Y', attrs={'class': 'date'}))
        self.fields['comments'].widget.attrs['class']='html'
        self.fields['infrastructure_comments'].widget.attrs['class']='html'

My view code is:

form = FeeChargeForm(request.POST or None)
form.fields['section'].initial = section

Where section is a url var passed to the function. I've tried:

form.fields['section'].initial = [(section,section)]

With no luck either :(

Any ideas what I'm doing wrong or is there a better way to set the default value (before a form submit) of this choice field from a url var?

Thanks in advance!

Update: It seems to be something to do with the URL variable.. If I use:

form.fields['section'].initial = "Changes Approval"

It works np.. If I HttpResponse(section) it's outputs correctly tho.

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

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

发布评论

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

评论(2

丿*梦醉红颜 2024-12-18 16:15:29

问题是一起使用 request.POSTinitial={'section':section_instance.id}) 。发生这种情况是因为 request.POST 的值总是覆盖参数 initial 的值,因此我们必须将其分开。我的解决方案是使用这种方式。

在views.py中:

if request.method == "POST":
    form=FeeChargeForm(request.POST) 
else:
    form=FeeChargeForm() 

在forms.py中:

class FeeChargeForm(ModelForm):
    section_instance = ... #get instance desired from Model
    name= ModelChoiceField(queryset=OtherModel.objects.all(), initial={'section': section_instance.id})

---------- 或 ----------

在views.py中:

if request.method == "POST":
    form=FeeChargeForm(request.POST) 
else:
    section_instance = ... #get instance desired from Model
    form=FeeChargeForm(initial={'section': section_instance.id}) 

在forms.py中:

class FeeChargeForm(ModelForm):
    name= ModelChoiceField(queryset=OtherModel.objects.all())

The problem is use request.POST and initial={'section': section_instance.id}) together. This happens because the values of request.POST always override the values of parameter initial, so we have to put it separated. My solution was to use this way.

In views.py:

if request.method == "POST":
    form=FeeChargeForm(request.POST) 
else:
    form=FeeChargeForm() 

In forms.py:

class FeeChargeForm(ModelForm):
    section_instance = ... #get instance desired from Model
    name= ModelChoiceField(queryset=OtherModel.objects.all(), initial={'section': section_instance.id})

---------- or ----------

In views.py:

if request.method == "POST":
    form=FeeChargeForm(request.POST) 
else:
    section_instance = ... #get instance desired from Model
    form=FeeChargeForm(initial={'section': section_instance.id}) 

In forms.py:

class FeeChargeForm(ModelForm):
    name= ModelChoiceField(queryset=OtherModel.objects.all())
乱了心跳 2024-12-18 16:15:29

更新
尝试转义您的网址。以下答案和文章应该会有所帮助:

如何对 URL 进行百分比编码Python 中的参数?

http://www.saltycrane.com/blog/2008/10/how-escape-percent-encode-url-python/

尝试按如下方式设置该字段的初始值,看看是否有效:

form = FeeChargeForm(initial={'section': section})

我假设当用户发布表单时您将做很多其他事情,因此您可以使用以下内容将 POST 表单与标准表单分开:

if request.method == 'POST':
    form = FeeChargeForm(request.POST)
form = FeeChargeForm(initial={'section': section})

UPDATE
Try escaping your url. The following SO answer and article should be helpful:

How to percent-encode URL parameters in Python?

http://www.saltycrane.com/blog/2008/10/how-escape-percent-encode-url-python/

Try setting the initial value for that field as follows and see if that works:

form = FeeChargeForm(initial={'section': section})

I assume you're going to be doing a lot of other things when the user posts the form, so you could separate the POST form from the standard form using something like:

if request.method == 'POST':
    form = FeeChargeForm(request.POST)
form = FeeChargeForm(initial={'section': section})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文