0
我想通過窗體傳遞一個對象,但它不適合我。在模型中,我的訂閱模型有一個客戶模型參考,任何時候我想要創建或更新訂閱,我都需要包含與之相關的客戶。通過Django形式傳遞對象
class Subscription(StripeObject):
sub_user = models.ForeignKey(Customer)
creation_date = models.DateTimeField(auto_now_add=True)
在我看來,我得到我需要的一切,在我的模板,我想從我的表單輸入字段的一個視圖通過客戶對象。
def profile(request):
user = request.user.get_full_name()
menu_group = Recipes.objects.filter(today=True).order_by('-price')
apartments = Apartment.objects.order_by('apartment')
plans = Plan.objects.order_by('amount')
try:
customer = Customer.objects.get(user=user)
except Customer.DoesNotExist:
customer = Customer(stripe_id=user, user=user, account_balance=0, currency="usd")
customer.save()
customer = Customer.objects.get(user=user)
try:
subscription = Subscription.objects.get(sub_user=customer)
except Subscription.DoesNotExist:
subscription = None
try:
charge_id = Subscribe.objects.get(user=user)
except Subscribe.DoesNotExist:
charge_id = None
if request.method == "POST":
form = AddSubscription(request.POST)
if form.is_valid(): # charges the card
if subscription is None:
form.save()
return HttpResponseRedirect('/subscription/charge/')
elif subscription.sub_change(form.cleaned_data['weekly_plan']):
form.save()
subscription.checked_out = True
return HttpResponseRedirect('/profile/')
else:
form.save()
subscription.checked_out = False
return HttpResponseRedirect('/subscription/charge/')
else:
return HttpResponseRedirect('/profile/error/')
else:
form = AddSubscription()
return render_to_response("profile.html", {'customer': customer, 'menu_group_list': menu_group, 'subscription': subscription, 'charge_id': charge_id, 'apartments': apartments, 'plans': plans}, context_instance=RequestContext(request))
模板:profile.html
{% with cus=customer %}
<input type="hidden" id="sub_user" name="sub_user" value="{{cus}}">
{% endwith %}
形式:
class AddSubscription(forms.ModelForm):
sub_user = forms.ModelChoiceField(queryset=Customer.objects.none())
class Meta:
model = Subscription
fields = ['sub_user']
def __init__(self, *args, **kwargs):
super(AddSubscription, self).__init__(*args, **kwargs)
形式顯然是無效的。我已經嘗試過使用ModelChoiceField,但沒有工作,我可以確認我正在使用的Subscription和Customer對象是存在的。有任何想法嗎?有沒有人見過這個問題?我如何通過表單傳遞ForeignKey Customer對象?
所以讓我確定我明白了。我停止通過HTML傳遞對象,並從表單中刪除ModelChoiceField。相反,我在我的視圖中獲取客戶對象,並在POST上設置form.field ['sub_user'] = customer。正確?我需要用GET做什麼? – acs254
謝謝你的幫助 - 我根據你上面的評論找出了它。 – acs254