Alan Tingey
Alan Tingey

Reputation: 961

Django: Set initial Value with a Passed Variable

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.

Upvotes: 0

Views: 293

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

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

Upvotes: 1

Related Questions