Вопрос:
Я испытываю ошибку: “Контекст должен быть dict, а не контекстом”. после подачи контактной формы. У меня есть догадка, что это связано с проблемами несовместимости с Django 1.11. Не слишком уверен, как найти обходной путь.
Вот что я получаю от трассы:
Environment: Request Method: POST Request URL: Django Version: 1.11.3 Python Version: 3.6.0 Installed Applications: [‘collection’, ‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.messages’, ‘django.contrib.staticfiles’, ‘django.contrib.humanize’, ‘registration’] Installed Middleware: [‘django.middleware.security.SecurityMiddleware’, ‘django.contrib.sessions.middleware.SessionMiddleware’, ‘django.middleware.common.CommonMiddleware’, ‘django.middleware.csrf.CsrfViewMiddleware’, ‘django.contrib.auth.middleware.AuthenticationMiddleware’, ‘django.contrib.messages.middleware.MessageMiddleware’, ‘django.middleware.clickjacking.XFrameOptionsMiddleware’] Traceback: File «/Users/billphan/Desktop/Projects/hello-web-app/venv/lib/python3.6/site-packages/django/core/handlers/exception.py» in inner 41. response = get_response(request) File «/Users/billphan/Desktop/Projects/hello-web-app/venv/lib/python3.6/site-packages/django/core/handlers/base.py» in _get_response 187. response = self.process_exception_by_middleware(e, request) File «/Users/billphan/Desktop/Projects/hello-web-app/venv/lib/python3.6/site-packages/django/core/handlers/base.py» in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File «/Users/billphan/Desktop/Projects/hello-web-app/collection/views.py» in contact 95. content = template.render(context) File «/Users/billphan/Desktop/Projects/hello-web-app/venv/lib/python3.6/site-packages/django/template/backends/django.py» in render 64. context = make_context(context, request, autoescape=self.backend.engine.autoescape) File «/Users/billphan/Desktop/Projects/hello-web-app/venv/lib/python3.6/site-packages/django/template/context.py» in make_context 287. raise TypeError(‘context must be a dict rather than %s.’ % context.__class__.__name__) Exception Type: TypeError at /contact/ Exception Value: context must be a dict rather than Context.
Здесь мой фрагмент кода для контактного маршрута в файле views.py:
def contact(request): form_class = ContactForm # new logic! if request.method == ‘POST’: form = form_class(data=request.POST) if form.is_valid(): contact_name = form.cleaned_data[‘contact_name’] contact_email = form.cleaned_data[‘contact_email’] form_content = form.cleaned_data[‘content’] # email the profile with the contact info template = get_template(‘contact_template.txt’) context = Context({ ‘contact_name’: contact_name, ‘contact_email’: contact_email, ‘form_content’: form_content, }) content = template.render(context) email = EmailMessage( ‘New contact form submission’, content, ‘Your website <[email protected]>’, [‘[email protected]’], headers = {‘Reply-To’: contact_email } ) email.send() return redirect(‘contact’) return render(request, ‘contact.html’, { ‘form’: form_class, })
Это, по-видимому, линия, вызывающая ошибку:
content = template.render(context)
Не так уверен, как обходиться с этим, ища какое-то руководство! Благодарю!
Лучший ответ:
Попробуйте заменить
context = Context({ ‘contact_name’: contact_name, ‘contact_email’: contact_email, ‘form_content’: form_content, })
с
context = { ‘contact_name’: contact_name, ‘contact_email’: contact_email, ‘form_content’: form_content, } Ответ №1
Когда вы создаете свой контекст, просто создайте словарь, а не объект Context.
context = { ‘contact_name’: contact_name, ‘contact_email’: contact_email, ‘form_content’: form_content, }