通过 Django Forms 传递一个对象

Pass an Object through Django Forms

我正在尝试通过表单传递对象,但它对我不起作用。在模型中,我的订阅模型有一个客户模型引用,任何时候我想创建或更新订阅,我都需要包括与之关联的客户。

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

您正在将 Python 对象传递给模板,Django 会尝试将其呈现给 HTML 并在 HTTP post 中将其传回。但是,HTML 和 HTTP 都不知道客户对象是什么;你得到的只是对象的字符串表示。

您可以通过传递客户 ID 来解决此问题,但是绝对没有意义。您根本不需要将 Customer 传入和传出表单;当您在 GET 上实例化表单时,您成功地从请求中获取了它,您可以在 POST.

上执行完全相同的操作