I’m having a problem accessing a Django Form POST data.
I need to pass request.user to the form, so:
class TradeForForm(forms.Form):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
else:
request = kwargs.pop('request')
super(TradeForForm, self).__init__(*args, **kwargs)
#Obtain items for user
if user:
print user
items = Item.objects.filter(user=user)
choices = []
for i in range(len(items)):
choices.append([i,items[i].name])
self.fields['item_to_be_traded_for'].choices = choices
trade_type = forms.ChoiceField(
widget=RadioSelect(),
choices = [
['0','Item'],
['1','Money offer'],
]
)
item_to_be_traded_for = forms.ChoiceField()
and then call it using:
def trade_for(request, item_id):
item = Item.objects.get(id=item_id)
if request.method == 'POST':
form = TradeForForm(request.POST)
if form.is_valid():
pass
else:
form = TradeForForm(user=request.user)
variables = RequestContext(request, {
'form': form,
'item': item,
})
return render_to_response('trade_for.html', variables)
Now the problem is, when doing GET to access the empty form, it works just fine. But when I post it, I received an error:
KeyError at /trade_for/1/
'user'
Request Method: POST
Request URL: http://localhost:8000/trade_for/1/
Django Version: 1.3.1
Exception Type: KeyError
Exception Value:
'user'
Now how can this be fixed? I assume it’s because the user variable is not passed to the form when creating it using the request.POST data, but I want to be able to create the form with the user parameter and without it, both working.
you should probably pass the user to the form creator even with
POSTdata so the choices can be validated properly, soif you don’t want this, you need to change
user = kwargs.pop('user')to something like