通用视图(Generic View)实现图片的上传与显示

models.py

from django.db import models
from datetime import date
from django.urls import reverse
import os
import uuid


# 自定义动态上传路径和文件名
def path_and_rename(instance,filename):
    upload_to = 'mypicture'
    ext = filename.split('.')[-1]
    filename = '{}.{}'.format(uuid.uuid4().hex[:10],ext)
    return os.path.join(upload_to,filename)


class Picture(models.Model):
    title = models.CharField('标题',max_length=100,blank=True,default='')
    image = models.ImageField('图片',upload_to=path_and_rename,blank=True)
    date = models.DateField(default=date.today)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('pic:pic_detail',args=[str(self.pk)])

    # Django自带通用视图在完成对象编辑或创建后需要一个返回页面,
    # 所以必需在模型里定义一个返回链接get_absolute_url。

项目urls.py

from django.contrib import admin
from django.urls import path,include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('pic/',include('pic_upload.urls',namespace='pic')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

应用urls.py

from django.urls import path
from . import views

app_name = 'pic'
urlpatterns = [
    path('',views.PicList.as_view(),name='pic_list'),
    path('pic_upload/',views.PicUpload.as_view(),name='pic_upload'),
    path('pic_detail//',views.PicDetail.as_view(),name='pic_detail'),
]

# DetailView 需要URL提供访问某个对象的具体参数(如pk, slug值)

views.py

from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from .models import Picture

class PicList(ListView):
    model = Picture
    context_object_name = 'latest_picture_list'
    template_name = 'pic_upload/picture_list.html'

class PicDetail(DetailView):
    model = Picture
    context_object_name = 'picture'
    template_name = 'pic_upload/picture_detail.html'

class PicUpload(CreateView):
    model = Picture
    fields = ['title', 'image']
    context_object_name = 'form'
    template_name = 'pic_upload/picture_form.html'

picture_list.html

图片列表

    {% if latest_picture_list %} {% for picture in latest_picture_list%}
  • {{picture.title}}-{{picture.date | date:'Y-m-j'}}
  • {% endfor %} {% else %}
  • 还没有上传新的图片
  • {% endif %}

上传新图片

picture_detail.html

{{picture.title}}

{% if picture.image %}

{% endif %}

上传日期:{{picture.date | date:'Y-m-j'}}

查看所有图片 | 上传新图片

picture_form.html

上传图片

{% csrf_token %} {{ form.as_p }}

注意点

三个通用视图的导入方法

from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView

date过滤器

{{ picture.date | date:'Y-m-j' }}

Y: 年,4位数,如 '2018'
m:月,2位数字带前导零,'01'到'12'
j:日,没有前导零,'1'到'31'
d:日,带有前导零,'01'到'31'

你可能感兴趣的:(通用视图(Generic View)实现图片的上传与显示)