我有一个网站的联系页面。联系表单正在运行,但我想在此页面中添加背景图像(保存在数据库中)。但是,如何将我的电子邮件(请求)和查询结合起来以获取图像?
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import ContactForm
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('./success')
return render(request, "contact/email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
models.py
from django.db import models
class Background(models.Model):
name = models.CharField(max_length=200, null=False)
image = models.ImageField(upload_to='./background/', default=None)
def __str__(self):
return self.name
urls.py
from django.conf.urls import url
from . import views
app_name = 'contact'
urlpatterns = [
url(r'^$', views.email, name='email'),
url(r'^success/$', views.success, name='success'),
]
答案 0 :(得分:0)
首先,您必须在视图中检索图像:
def get_background():
try:
background = Background.objects.get(name="your image name") # add your filters where to get the image
if background.image and background.image.url:
return background.image.url
except Background.DoesNotExist:
return
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
...
...
# add the background to context
return render(request, "contact/email.html", {'form': form, 'background_img': get_background()})
在你的HTML中(注意这只是一个例子,使用CSS来设置你的页面样式):
...
<div {% if background_img %}style="background: url('{{background_img}}') center no-repeat;"{% endif %}>
...
抱歉,我的英文不好哈哈