我将代理ID传递给我的表单。问题是,如何获取该代理ID,获取ID,然后将下拉字段默认选择为我通过的代理ID?
传递变量
<input type="button" name="chargeback" value="Submit Chargeback" href="{% url commissions-chargebacks_insert agent.id %}" />
我的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')
答案 0 :(得分:0)
如果您使用的是1.4,则可以在视图中使用ChargebackForm
上的initial
参数:
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})