Django 与脆形式 VariableDoesNotExist

Django with Crispy-forms VariableDoesNotExist

我已经尝试将表单加载到模态中大约一个星期了,但我无法弄清楚我做错了什么。这是一个简单的表单,供某人向我发送电子邮件,我开始尝试将该表单模块化,现在只是尝试将其直接加载到 base.html.

我的模特:

from django.db import models

# Create your models here.

class EmailMe(models.Model):
    subject = models.CharField(max_length=63)
    body = models.TextField(max_length=2047)
    email = models.EmailField()

    def __str__(self):#shows object title when called from command line
        return self.name`

我的表格:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout

from emailme.models import EmailMe

class EmailMeForm(forms.ModelForm):

    subject = forms.CharField(max_length=63)
    body = forms.CharField(max_length=2047)
    email = forms.EmailField()

    class Meta:
        model = EmailMe
        fields = '__all__'

    def __str__(self):#shows object title when called from command line
        return self.name

    def __init__(self, *args, **kwargs):
        super(EmailMeForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'myModal'
        self.helper.form_class = 'form-horizontal'
        self.helper.form_action = 'emailme'
        self.helper.form_method = 'POST'
        self.helper.layout = Layout(
            Fields(
                'subject',
                'body',
                'email',
            ),
            FormActions(
                Submit('submit', 'submit')
            )
        )

我的看法:

from mysite.forms import EmailMeForm

def home(request):
    return render_to_response('base.html')

def emailme(request):
    if request.POST:
        form = EmailMeForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('home/')#reverse_lazy('home'))
    else:
        form = EmailMeForm()


    ctx = {}
    ctx.update(csrf(request))

    args['form'] = form
    return render_to_response('emailme_form.html',
              {'form': form},
              context_instance=ctx)

网址:

"""mysite URL Configuration

"""
from django.conf.urls import url, include
from django.contrib import admin

from mysite import views as mysite_views
from emailme import views as emailme_views

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^emailme/', emailme_views.emailme, name='emailme'),
url(r'^home/', mysite_views.home, name='home'),
]

base.html:

{% load crispy_forms_tags %}

<div class="modal-content">
      {% csrf_token %}
      {% crispy form form.helper %}
</div>

我正在使用 Django 1.9、crispy-forms 和 bootstrap。这是错误:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.9.8
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
  'emailme',
  'crispy_forms',
 'bootstrap3']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template /home/pi/Django-bootstrap/bin/mysite/templates/base.html, error at line 77
  Failed lookup for key [%s] in %r   67 :     
    68 :     
 69 :     
 70 :  <div class="container">
 71 :   <!-- Modal -->
 72 :   <div class="modal fade" id="myModal" role="dialog">
 73 :   <div class="modal-dialog">





74 :   <!-- Modal content-->
75 :     <div class="modal-content">
76 :       {% csrf_token %}
 77 :        {% crispy form form.helper %} 
78 :     </div>
79 : </div>
80 :   </div>
81 :  </div>
82 : 
83 : 
84 : 
85 :     <div class="container">
86 :       <!-- Example row of columns -->
87 :       <div class="row">   


Traceback:

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
883.                     current = current[bit]

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/context.py" in __getitem__
 77.         raise KeyError(key)

During handling of the above exception ('form'), another exception occurred:

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
 889.                         if isinstance(current, BaseContext) and getattr(type(current), bit):

During handling of the above exception (type object 'Context' has no attribute 'form'), another exception occurred:

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
898.                             current = current[int(bit)]

During handling of the above exception (invalid literal for int() with base 10: 'form'), another exception occurred:

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149.                     response = self.process_exception_by_middleware(e, request)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/pi/Django-bootstrap/bin/mysite/mysite/views.py" in home
13.     return render_to_response('base.html')

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/shortcuts.py" in render_to_response
39.         content = loader.render_to_string(template_name, context, using=using)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
97.         return template.render(context, request)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/backends/django.py" in render
95.             return self.template.render(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in render
206.                     return self._render(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _render
197.         return self.nodelist.render(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in render
992.                 bit = node.render_annotated(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in render_annotated
959.             return self.render(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/crispy_forms/templatetags/crispy_forms_tags.py" in render
214.         c = self.get_render(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/crispy_forms/templatetags/crispy_forms_tags.py" in get_render
107.         actual_form = form.resolve(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in resolve
850.             value = self._resolve_lookup(context)

File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
905.                                                        (bit, current))  # missing attribute

Exception Type: VariableDoesNotExist at /home/
Exception Value: Failed lookup for key [form] in "[{'False': False, 'None': None, 'True': True}]"

问题是您正试图在 base.html 中使用 form(对于所有视图)。但是表单只会添加到 emailme 视图中的上下文中。主页视图 (home) 不提供任何 form,因此当您尝试加载主页时出现错误。

您需要将表单添加到主页视图(以及任何其他使用 base.html 的视图):

def home(request):
    return render_to_response('base.html', {'form': EmailMeForm()})

或使用 context processor 将表单全局插入到模板上下文中。