python - Pass an Object through Django Forms -
i'm trying pass object through form, not working me. in models, subscription model has customer model reference, , time want create or update subscription, need include customer associated it.
class subscription(stripeobject): sub_user = models.foreignkey(customer) creation_date = models.datetimefield(auto_now_add=true)
in view, getting need, , in template, trying pass customer object view 1 of form input fields.
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 card if subscription 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
{% cus=customer %} <input type="hidden" id="sub_user" name="sub_user" value="{{cus}}"> {% endwith %}
form:
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)
the form apparently not valid. i've tried using modelchoicefield, did not work, , can confirm both subscription , customer objects i'm working exist. ideas? has seen problem before? how can pass foreignkey customer object through form?
you're passing python object template, django attempts render html , pass in http post. however, neither html nor http have knowledge of customer object is; you'd string representation of object.
you fix passing customer id instead, there absolutely no point. don't need pass customer , form @ all; request when instantiate form on get, can same on post.
Comments
Post a Comment