Django+xadmin实现后台和表单上传图片

简单的演示下,Djang+xadmin上传图片的步骤

前提:请自行创建Django项目和配置xadmin

完整的代码路径:https://github.com/ylpxzx/Django_imageupload

这里我们采用StdImageField来实现图片上传

  • 创建好Django app应用,这里我创建的是名为project的项目和名为password的应用

以下是目录结构

Django+xadmin实现后台和表单上传图片_第1张图片

  • 在project目录下创建media目录,用于存放上传的图片,再在media中创建image目录

Django+xadmin实现后台和表单上传图片_第2张图片

  • 创建好media目录结构后,在setting.py文件中配置media路径
MEDIA_URL="/media/"
MEDIA_ROOT=os.path.join(BASE_DIR,"media")
CKEDITOR_UPLOAD_PATH="article_images"
  • 定义password应用的模型文件(models.py)
from django.db import models
from stdimage.models import StdImageField
# Create your models here.
class Password(models.Model):
    appname=models.CharField(max_length=25,verbose_name="备注")
    user=models.CharField(max_length=30,verbose_name="用户名")
    email=models.EmailField(verbose_name="Email")
    phone=models.CharField(max_length=12,verbose_name="手机号")
    password=models.CharField(max_length=50,verbose_name="密码")
    created_time=models.DateTimeField(auto_now_add=True,editable=False,verbose_name="创建时间")
    image1 = StdImageField(
        upload_to='image/%Y/%m', variations={'thumbnail': {'width': 100, 'height': 75}},
        verbose_name=u"图片",
        )

    class Meta:
        verbose_name=verbose_name_plural="密码管理"

    def image_img1(self):
        if self.image1:
            return str('' % self.image1.thumbnail.url)
        else:
            return '上传图片'

    image_img1.short_description = '图片'
    image_img1.allow_tags = True  # 列表页显示图片

 

  • 在setting.py文件的INSTALLED_APPS中分别添加’password‘和’stdimage‘
INSTALLED_APPS = [
    'project',
    'password',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'xadmin',
    'crispy_forms',
    'stdimage',
]
  • 在setting.py中配置mysql数据库(记得要提前在MySQL中创建好ibm_project1数据库)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ibm_project1',
        'USER': 'root',
        'PASSWORD': '自己数据库的密码',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8', },
    }
}
  • 在主url.py中(和setting.py同路径)添加

url(r'media/(?P.*)$', serve, {"document_root": MEDIA_ROOT}),

如下所示


from project.settings import MEDIA_ROOT
import xadmin
from django.conf import settings
from django.views.static import serve
from django.contrib import admin
from django.conf.urls import url
from django.urls import path
from password.views import Password_list,Password_detail,Password_forms,index
urlpatterns = [
    url(r'^$', index, name='index'),
    url(r'^password/$', Password_list, name='password'),
    url(r'^password/(?P\d+)/$', Password_detail, name="detail_password"),
    url(r'^xadmin/', xadmin.site.urls, name='xadmin'),
    url(r'media/(?P.*)$', serve, {"document_root": MEDIA_ROOT}),
    url(r'^password_form/$', Password_forms, name='password_form'),
]
  • 接下来就是配置adminx文件(配置password应用的adminx.py文件,这里的adminx.py文件是配置成功xadmin后的文件)
import xadmin
from .models import Password
from xadmin.layout import Row,Fieldset
# Register your models here.

@xadmin.sites.register(Password)
class PasswordAdmin(object):
    save_on_top = True

    actions_on_top = True
    actions_on_bottom = True

    form_layout=(
        Fieldset(
            '密码信息',
            'appname',
            Row("user", "password"),
            Row ('email','phone'),
        ),
    )
    list_display = ('appname', 'user', 'email', 'phone', 'password', 'created_time','image_img1')
    list_filter = ['appname', 'created_time']

    def has_delete_permission(self, *args, **kwargs):
        return True
  • 最后记得进行数据迁移(终端执行python manage.py makemigrations和python manage.py migrate命令)
  • 结果:

Django+xadmin实现后台和表单上传图片_第3张图片

点击增加密码管理,就可以进行图片的上传了

Django+xadmin实现后台和表单上传图片_第4张图片


以上的就是后台上传图片

下面我们来实现表单上传图片

  • 在password中创建forms.py文件
from django import forms
from .models import Password

class PasswordForm(forms.ModelForm):
    def clean_phone(self):
        cleaned_data=self.cleaned_data['phone']
        if not cleaned_data.isdigit():
            raise forms.ValidationError('必须是数字!')
        return int(cleaned_data)
    class Meta:
        model=Password
        fields=(
            'appname','user','email','phone','password','image1'
        )
  • 接下来就是视图(views.py)的配置
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import PasswordForm
from .models import Password
from django.shortcuts import get_object_or_404
# Create your views here.


def index(request):
    return render(request,'index.html')


def Password_list(request):
    password=Password.objects.all()
    return render(request, 'password.html', context={'passwords':password})


def Password_detail(request,password_id):
    detail_passwords=get_object_or_404(Password,pk=password_id)
    return render(request,'password_detail.html',context={'detail_passwords':detail_passwords})


def Password_forms(request):
    password = Password.objects.all()
    if request.method == 'POST':
        form = PasswordForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/password/')
    else:
        form = PasswordForm()
    context = {
        'passwords': password,
        'form': form,
    }
    return render(request, 'password_form.html', context=context)
  • 配置url
from project.settings import MEDIA_ROOT
import xadmin
from django.conf import settings
from django.views.static import serve
from django.conf.urls import url
from password.views import Password_list,Password_detail,Password_forms,index
urlpatterns = [
    url(r'^$', index, name='index'),
    url(r'^password/$', Password_list, name='password'),
    url(r'^password/(?P\d+)/$', Password_detail, name="detail_password"),
    url(r'^xadmin/', xadmin.site.urls, name='xadmin'),
    url(r'media/(?P.*)$', serve, {"document_root": MEDIA_ROOT}),
    url(r'^password_form/$', Password_forms, name='password_form'),
]
  • 结果:

 

你可能感兴趣的:(python,Django)