Django:使用传递的变量设置初始值 [英] Django: Set initial Value with a Passed Variable

查看:90
本文介绍了Django:使用传递的变量设置初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django,并希望从视图传递变量以在表单内设置初始值。

I am using Django and want to pass a variable from a view to set an initial value within a form.

我有以下视图:

def change_chosenCharity(request):
    charityid=12
    form = updateCharity(charityid)
    return render(request, 'meta/changechosencharity.html', {'form': form})

形式:

class updateCharity(BootstrapForm):

    currentCharities = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1), empty_label=None,widget=forms.Select(attrs={"class": "select-format"}))
    currentCharities.label = "Charity Options"
    currentCharities.intial = charityid

这会产生以下错误: name'charityid'未定义

我知道它没有在表单中定义,但是我尝试了各种方法来定义它们,但均未成功。

I get that it is not defined within the form but I have tried various options to define it all without success.

我们将不胜感激。

推荐答案

您无需在表单定义中声明它;

You don't declare it in the form definition; that wouldn't make sense, since you need to set it dynamically.

相反,当您在视图中实例化表单时,可以这样做:

Instead, do it when you instantiate the form in the view:

form = updateCharity(initial={'currentCharities': charityid})

这篇关于Django:使用传递的变量设置初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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