Django 1.11. Контекст TypeError должен быть скорее диктантом, чем контекстом.
Только что получил Sentry ошибку TypeError context must be a dict rather than Context.
на одной из моих форм. Я знаю, что это как-то связано с Django 1.11, но я не уверен, что изменить, чтобы это исправить.
Оскорбляющая линия
message = get_template('email_forms/direct_donation_form_email.html').render(Context(ctx))
Весь вид
def donation_application(request):
if request.method == 'POST':
form = DirectDonationForm(data=request.POST)
if form.is_valid():
stripe.api_key = settings.STRIPE_SECRET_KEY
name = request.POST.get('name', '')
address = request.POST.get('address', '')
city = request.POST.get('city', '')
state = request.POST.get('state', '')
zip = request.POST.get('zip', '')
phone_number = request.POST.get('phone_number', '')
support = request.POST.get('support', '')
agree = request.POST.get('agree', '')
email_address = request.POST.get('email_address', '')
number = request.POST.get('number', '')
cvc = request.POST.get('cvc', '')
exp = request.POST.get('exp', '')
# token = form.cleaned_data['stripe_token'],
# exp_m = int(request.POST.get('exp_month', ''))
# exp_y = int(request.POST.get('exp_year', ''))
exp_month = exp[0:2]
exp_year = exp[5:9]
subject = 'New Donation'
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = ['deniselarkins@/////\\\\\.com',
'charles@/////\\\\\.net',
'marcmunic@/////\\\\\.com',
]
token = stripe.Token.create(
card={
'number': number,
'exp_month': exp_month,
'exp_year': exp_year,
'cvc': cvc
},
)
customer = stripe.Customer.create(
email=email_address,
source=token,
)
total_support = decimal.Decimal(support) / 100
total_charge = decimal.Decimal(int(support)) / 100
# Charge the user's card:
charge = stripe.Charge.create(
amount=total_charge,
currency='usd',
description='Donation',
customer=customer.id
)
ctx = {
'name': name,
'address': address,
'city': city,
'state': state,
'zip': zip,
'phone_number': phone_number,
'email_address': email_address,
'agree': agree,
'charge': charge,
'customer': customer,
'total_support': total_support,
'total_charge': total_charge
}
message = get_template('email_forms/direct_donation_form_email.html').render(Context(ctx))
msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list)
msg.content_subtype = 'html'
msg.send(fail_silently=True)
return redirect(
'/contribute/donation-support-thank-you/?name=' + name +
'&address=' + address +
'&state=' + state +
'&city=' + city +
'&zip=' + zip +
'&phone_number=' + phone_number +
'&email_address=' + email_address +
'&total_support=' + str(total_support) +
'&total_charge=' + str(total_charge)
)
context = {
'title': 'Donation Pledge',
}
return render(request, 'contribute/_donation-application.html', context)
4 ответа
В Django 1.8+ шаблонов render
Метод принимает словарь для context
параметр. Поддержка прохождения Context
Экземпляр устарел и выдает ошибку в Django 1.10+.
В вашем случае просто используйте обычный dict
вместо Context
пример:
message = get_template('email_forms/direct_donation_form_email.html').render(ctx)
Вы можете предпочесть использовать render_to_string
ярлык:
from django.template.loader import render_to_string
message = render_to_string('email_forms/direct_donation_form_email.html', ctx)
Мигрировал с Джанго 1.8 до Джанго 1.11.6
Где бы у меня ни был класс RequestContext, есть метод flatten (), который возвращает результат в виде dict.
Так что, если класс это RequestContext....
return t.render(context)
становится
return t.render(context.flatten())
А в случае, если контекст обернут Context(), просто удалите его. Потому что Context() устарела.
return t.render(Context(ctx))
становится
return t.render(ctx)
Для django 1.11 и после контекст должен быть dict. Вы можете использовать:
context_dict = get_context_dict(context)
return t.render(context_dict)
или же
context_dict = context.flatten()
return t.render(context_dict)
Я попал сюда, потому что у меня была такая же проблема. Я изучаю Django с Django Unleashed Эндрю Пинкхэмом. Это книга 2015 года.
Я обнаружил в официальной документации, что словарь должен быть передан параметру контекста, а не экземпляру контекста (из django.template.Context).
@Alasdair предложил использовать render_to_string, но, по крайней мере, в Django 3.2 метод рендеринга внутренне использует метод render_to_string.
def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Return a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
так что использование только метода рендеринга может быть лучше. Я даю этот ответ, потому что это тот, который я искал, и он может помочь кому-то достичь этого вопроса о переполнении стека.