如何在views.py中返回两个词典

2024-05-16 10:00:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在views.py中返回信息和数据

我试过:

返回呈现(请求'index.html',{'infos':infos},数据)

返回呈现(请求'index.html',{'infos':infos,'data':data})

但什么都不管用


views.py

def contact(request):

   infos = Info.objects.all()
   if request.method == "POST":
       form = ContactForm(request.POST)
       if form.is_valid():
           messages.success(request, 'Success')
           admin_address = "mail"
           responder_address ="responder@site.pl"
           client_address = request.POST['email']
           message_for_admin = """
           name: %s;
           E-mail: %s;
           Subject: %s;
           Text: 
           %s;

           """ % (request.POST['name'], request.POST['email'], request.POST['subject'],    request.POST['message'])

           message_for_client = """
           text
           """

           try:
               send_mail(request.POST['subject'], message_for_admin, responder_address, [admin_address,])
               #send_mail(request.POST['subject'], responder_address, message_for_client, [client_address,])
           except BadHeaderError:
               print('wrong subject')
           data['form'] = form
           data['info'] = 'thanks for message'
       else:
           data['form'] = ContactForm()

   return render(request, 'index.html', {'infos':infos})

Tags: formclientmessagefordataindexadminaddress
2条回答
# you might have forgot to write else part for GET method

def contact(request):
   data = {}
   infos = Info.objects.all()
   form = ContactForm()
   if request.method == "POST":
       ....
       ....

   return render(request, 'index.html', {'infos':infos, 'data':data})   

render快捷方式采用单个上下文字典。你不能通过两本字典

例如,您可以将infos添加到数据字典中:

data['infos'] = infos

然后使用data呈现模板

return render(request, 'index.html', data)

相关问题 更多 >