通过Django Forms传递一个对象

时间:2016-01-21 03:55:32

标签: python django forms models

我试图通过表单传递一个对象,但它对我不起作用。在模型中,我的订阅模型具有客户模型参考,每当我想要创建或更新订阅时,我都需要包含与之关联的客户。

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))

Template: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对象?

1 个答案:

答案 0 :(得分:1)

您将Python对象传递给模板,Django尝试将其呈现为HTML并将其传回HTTP帖子。但是,HTML和HTTP都不知道Customer对象是什么;所有你得到的将是对象的字符串表示。

您可以通过传递Customer ID来解决此问题,但绝对没有要点。您根本不需要将客户传递给表单;当您在GET上实例化表单时,您已成功从请求中获取它,您可以在POST上执行完全相同的操作。