Note that there are some explanatory texts on larger screens.

plurals
  1. POrequest.user in Django Form
    primarykey
    data
    text
    <p>I'm having a problem accessing a Django Form POST data.</p> <p>I need to pass request.user to the form, so:</p> <pre><code>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() </code></pre> <p>and then call it using:</p> <pre><code>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) </code></pre> <p>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:</p> <pre><code>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' </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload