如何上传图片并在博客文章中使用图片作为背景图片?

时间:2016-10-23 13:11:59

标签: python django image

好的,所以我希望能够在管理面板的“添加帖子”部分中写博客条目时上传图像,并将该图像用作该帖子链接的背景图像。锚链接在主页上。

哪种字段类型最适合这种情况?我需要写一个额外的视图吗?

博客/ urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
    url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]

博客/ views.py

from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, "blog/post_list.html", {"posts": posts})

def post_detail(request, pk):
  post = get_object_or_404(Post, pk=pk)
  return render(request, 'blog/post_detail.html', {'post': post})

博客/ models.py

from django.db import models
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)


    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

0 个答案:

没有答案