Gra*_*tel 1 django django-templates django-forms django-email contact-form
我需要在我的主页底部嵌入一个联系表单,这是一个单页应用程序。我遵循了几个关于如何在另一个页面(例如,myportfolio.com/contact)上创建自己的联系表单的教程,这些教程很成功。不幸的是,我无法调整这些结果或找到其他教程,了解如何使该联系表单在显示所有其他模型数据的同一页面上可见并起作用(例如,myportfolio.com)。
我遵循了本教程:https://atsoftware.de/2015/02/django-contact-form-full-tutorial-custom-example-in-django-1-7。我只创建了一个应用程序。
我觉得这应该是一件很常见的事情,这让我觉得我忽略了一些显而易见的事情。
应用程序中的views.py
from django.views.generic import TemplateView
from portfolio.models import Experience
class HomePage(TemplateView):
template_name = 'portfolio/base.html'
def get_context_data(self, *args, **kwargs):
context = super(HomePage, self).get_context_data(*args, **kwargs)
context['experience_list'] = Experience.objects.order_by('-start_date')
return context
Run Code Online (Sandbox Code Playgroud)
contact_form.html
{% extends 'portfolio/base.html' %}
{% block contact %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
现在 contact_form.html 进入portfolio/base.html,如下所示:
基本.html
{# {% include "contact_form/contact_form.html" %}#}
{% block contact %}{% endblock %}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,什么也没有显示。但是,如果我注释掉第二行并删除第一行中的注释,则会出现提交按钮。
现在我意识到我假设 django-contact-form 将获取此表单并知道如何处理它,就像在 myportflio.com/contact 场景中可以访问它一样。但是,我知道之前曾通过 urls.py 文件引用 /contact,但在嵌入到 base.html 文件中时,不再有引用。
我可以在 HompePage 视图中以类似于将模型数据添加到上下文的方式添加表单吗?
您正在遵循的教程并不是最新的(它是在 1.7 中编写的)。因此,您通常在views.py 中执行的操作(以及函数中缺少的操作)是声明表单。
我向您展示我将如何做到这一点,所有这些都与您的代码有点不同,但在我看来更容易理解,这就像标准方式。
from appName.forms import formName #dont forget to import the form
from django.views.generic import TemplateView
from portfolio.models import Experience
def HomePage(request):
form = formName(request.POST or None) #here you tell django what form you are talking about
if form.is_valid(): #checking if the form input is valid
....
form.save()
#messages.success(request, 'form was posted') #this is optional but good for the user
context = {
'form': form, #here you are passing the variable "form" to the template so you can use it like "{{form.as_p}}"
'experience_list' = Experience.objects.order_by('-start_date')
#other context variables
}
return render(request, "appName/MainPage.html", context)
Run Code Online (Sandbox Code Playgroud)
应用程序中的 urls.py 如下所示:
urlpatterns = [
url(r'mainPage',views.HomePage, name='HomePage'),
]
Run Code Online (Sandbox Code Playgroud)
如果你想保持一切原样,请尝试以下操作:
def get_context_data(self, *args, **kwargs):
context = super(HomePage, self).get_context_data(*args, **kwargs)
context['experience_list'] = Experience.objects.order_by('-start_date') #maybe you have to put a "," here but I'm not sure
context['form'] = formName
return context
Run Code Online (Sandbox Code Playgroud)
但我不确定如何在通用 TemplateView 中进行这样的验证。无论如何,既然您声明了“form”变量,它应该在您的模板中可见。
| 归档时间: |
|
| 查看次数: |
2031 次 |
| 最近记录: |