Ani*_*war 1 django django-forms django-views
我在context_processors.py中有这个代码
class ContactFormView(FormView):
form_class = ContactForm
template_name = "blog/contact.html"
success_url = "/contact/"
def form_valid(self,form):
contact_name = form.cleaned_data.get('contact_name')
contact_email = form.cleaned_data.get('contact_email')
form_content = form.cleaned_data.get('content','')
try:
send_mail(contact_name,form_content,contact_email,[settings.EMAIL_HOST_USER], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid Header Found')
return super(ContactFormView,self).form_valid(form)
Run Code Online (Sandbox Code Playgroud)
我希望通过使用上下文处理器将其包含在所有视图中.我收到此错误:
TypeError at /
__init__() takes exactly 1 argument (2 given)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.8.7
Exception Type: TypeError
Exception Value:
__init__() takes exactly 1 argument (2 given)
Exception Location: C:\Python27\lib\site-packages\django-1.8.7-py2.7.egg\django\template\context.py in bind_template, line 241
Python Executable: C:\Python27\python.exe
Python Version: 2.7.10
Run Code Online (Sandbox Code Playgroud)
如何在所有模板中传递此表单?
我不认为你理解上下文处理器的概念.这些是简单的函数,将内容添加到上下文中,该上下文是由django管理并发送到每个模板的字典.
上下文处理器允许您将自己的键和值添加到此词典中,然后可以在所有模板中使用.
在上下文处理器中,您只需返回包含自定义键/值对的字典 - 仅此而已,例如:
from someapp.forms import ContactForm
def ctx_contact_form(request):
return {'contact-form': ContactForm()}
Run Code Online (Sandbox Code Playgroud)
现在,在所有模板中,您都可以{{ contact-form }}使用.请记住,您仍然需要在模板中编写周围的HTML:
<form method="post" action="{% url 'your-view' %}">
{{ contact-form }}
<input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
如果您甚至想要为您编写该部分{{ contact-form }},那么您需要在模板中输入所有内容,然后您需要编写自定义模板标记,其中包含几个步骤.
首先,创建一个简单的模板,比如说_formtag.html,并包含上面的HTML:
<form method="post" action="{% url 'your-view' %}">
{{ contact-form }}
<input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
接下来,创建一个templatetags在您的应用程序中调用的目录,在其中创建一个名为的空文件__init__.py,然后创建另一个文件调用它app_form_tags.py; 在此app_form_tags.py文件中,添加以下代码:
from django import template
from yourapp.forms import ContactForm
register = template.Library()
@register.inclusion_tag('_formtag.html')
def contact_form():
return {'contact-form': ContactForm()}
Run Code Online (Sandbox Code Playgroud)
最后,无论您想在哪里显示该表单(在模板中),只需添加即可
{% load app_form_tags %}
Run Code Online (Sandbox Code Playgroud)
在文件的顶部,然后{% contact_form %}在您希望表单的位置.
您的其余代码(即处理表单)必须正常地在视图中编写.
| 归档时间: |
|
| 查看次数: |
943 次 |
| 最近记录: |