Django choicefield的初始值

5 投票
2 回答
15218 浏览
提问于 2025-04-17 04:52

我遇到了一个奇怪的问题,无法在我的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

这里的section是传递给函数的一个网址变量。我尝试过:

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

但都没有成功 :(

有没有人知道我哪里做错了,或者有没有更好的方法可以通过网址变量在表单提交之前设置这个选择字段的默认值?

提前谢谢大家!

更新:看起来问题和网址变量有关.. 如果我使用:

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

就能正常工作.. 如果我用HttpResponse(section),输出也是正确的。

2 个回答

4

问题在于同时使用 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())
1

更新

试着对你的网址进行转义处理。下面的StackOverflow回答和文章应该会对你有帮助:

如何在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})

撰写回答