在 django 中从数据库中一起呈现联系表单和 header 标题时出错
getting error while rendering contact form and header title from database together in django
在 forms.py
中,我想将数据与附加的联系表一起呈现到我的数据库,但是当我尝试这样做时,它给出了一个 html 页面而不是我的索引模板
def home(request):
base = BaseHeader.objects.all()
if request.method == 'GET':
form = contactForm()
else:
form = contactForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data['name']
email = form.cleaned_data['email']
Phonenumber = form.cleaned_data['Phonenumber']
try:
send_mail(
'Subject here',
'Here is the message.',
'from@gmail.com',
['to@gmail.com'],
fail_silently=False,)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('home')
return render(request, 'index.html', {'form': form},{'menu_titles': base})
您在 return
语句中出错,您将第 3 个参数 context
传递给 render
函数的方式错误,应该如下所示:
def home(request):
[..]
context = {
'form': form,
'menu_titles': base
}
return render(request, 'index.html', context)
参考https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render
备注
django 期望 forms.py
而不是 form.py
来保存所有表格 类(我已经更新了你的问题)
在 forms.py
中,我想将数据与附加的联系表一起呈现到我的数据库,但是当我尝试这样做时,它给出了一个 html 页面而不是我的索引模板
def home(request):
base = BaseHeader.objects.all()
if request.method == 'GET':
form = contactForm()
else:
form = contactForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data['name']
email = form.cleaned_data['email']
Phonenumber = form.cleaned_data['Phonenumber']
try:
send_mail(
'Subject here',
'Here is the message.',
'from@gmail.com',
['to@gmail.com'],
fail_silently=False,)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('home')
return render(request, 'index.html', {'form': form},{'menu_titles': base})
您在 return
语句中出错,您将第 3 个参数 context
传递给 render
函数的方式错误,应该如下所示:
def home(request):
[..]
context = {
'form': form,
'menu_titles': base
}
return render(request, 'index.html', context)
参考https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render
备注
django 期望 forms.py
而不是 form.py
来保存所有表格 类(我已经更新了你的问题)