【问题标题】:Django views.py request and queryDjango views.py 请求和查询
【发布时间】:2017-06-24 19:51:33
【问题描述】:

我的网站有一个联系页面。联系表单正在工作,但我想向此页面添加背景图片(保存在数据库中)。但是如何结合我的电子邮件(请求)和查询来获取图片?

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'),
]

【问题讨论】:

    标签: python django django-models django-forms


    【解决方案1】:

    您可以检索视图上的图像:

    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 %}>
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 2014-04-14
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多