我需要在我的主页底部嵌入一个联系表单,这是一个单页面应用程序。我按照几个关于如何在另一个页面(例如,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
contact_form.html
{% extends 'portfolio/base.html' %}
{% block contact %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
{% endblock %}
现在contact_form.html会像这样进入portfolio / base.html:
base.html文件
{# {% include "contact_form/contact_form.html" %}#}
{% block contact %}{% endblock %}
在这种情况下,没有任何显示。但是,如果我注释掉第二行并从第一行删除注释,则会出现提交按钮。
现在我意识到我假设django-contact-form将会选择这个表单并知道如何处理它,就像在myportflio.com/contact场景中可以访问它一样。但是,我知道以前曾经通过urls.py文件引用/ contact,但是在嵌入base.html文件的情况下,不再有引用。
我可以在HompePage视图中以某种方式添加表单,类似于将模型数据添加到上下文中吗?
答案 0 :(得分:3)
你所遵循的教程并不是最新的(它写于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)
你的app中的urls.py看起来像是:
urlpatterns = [
url(r'mainPage',views.HomePage, name='HomePage'),
]
如果你想保留一切,请试试这个:
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
但我不确定如何在通用TemplateView中进行这样的验证。无论如何,因为你声明了“form”变量,它应该在你的模板中可见。
答案 1 :(得分:0)
我在 view.py
中解决这个问题的方法是:
from contact_form.forms import ContactForm
def index(request):
if request.method == 'POST':
form = ContactForm(request.POST or None, request=request)
if form.is_valid(): # checking if the form input is valid
form.save()
return render(request, 'myapp/index.html')
它适用于 django-contact-form 1.8.2 和 django 3.0.8。 无论如何,我已经在项目仓库中打开了 a ticket。