Django: Set initial Value with a Passed Variable

一世执手 提交于 2019-12-12 04:12:16

问题


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

I have the following view:

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

With the following 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

Which produces the following error: name 'charityid' is not defined.

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

Any help is appreciated.


回答1:


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})


来源:https://stackoverflow.com/questions/44260030/django-set-initial-value-with-a-passed-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!