前提:请自行创建Django项目和配置xadmin
完整的代码路径:https://github.com/ylpxzx/Django_imageupload
以下是目录结构
MEDIA_URL="/media/"
MEDIA_ROOT=os.path.join(BASE_DIR,"media")
CKEDITOR_UPLOAD_PATH="article_images"
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 # 列表页显示图片
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',
]
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(r'media/(?P
如下所示
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'),
]
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
点击增加密码管理,就可以进行图片的上传了
以上的就是后台上传图片
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'
)
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)
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'),
]