0

I am passing the agent id through to my forms. Question is, how do I take that agent id, grab the id, then make the dropdown field default selection the agent id that I passed through?

Passing the variable

<input type="button" name="chargeback" value="Submit Chargeback" href="{% url commissions-chargebacks_insert agent.id %}" />

My views.py

def insert(request, agent=None, investment=None, chargeback=None, *args, **kwargs):
from commissions.forms import ChargebackForm
context = {}
selected_agent_id = kwargs['agent_id']
if request.POST:
    form = ChargebackForm(selected_agent_id, request.POST)
    if form.is_valid():
        chargeback = form.save(commit=False)
        chargeback.total_branch_commission = str(float("-0%s" % chargeback.amount))
        chargeback.save()
        return HttpResponseRedirect(reverse('commissions-chargebacks_browse'))
    else:
        request.user.message_set.create(message='Please correct errors and try submitting again.')
else:
    form = ChargebackForm(selected_agent_id)

context['form'] = form
return render_to_response('commissions/admin/chargebacks/insert.html', RequestContext(request, context))

forms.py

class ChargebackForm(forms.ModelForm):
def __init__(self, selected_agent_id, *args, **kwargs):
    super(ChargebackForm, self).__init__(*args, **kwargs)
    self.fields['agent'].queryset = Agent.objects.all().filter(agent_id = selected_agent_id)

class Meta:
    model = Chargeback

    fields = ('agent', 'amount','description','policy_num')
4

1 回答 1

0

如果您使用的是 1.4,则可以在视图中使用initial参数 on :ChargebackForm

if request.method == 'POST':
    form = ChargebackForm(
        selected_agent_id, request.POST, initial={'agent':selected_agent_id})
else:
    form = ChargebackForm(selected_agent_id, initial={'agent':selected_agent_id})
于 2012-12-12T01:11:04.287 回答