需求如图:¶
方法:¶
models.py
#-*- coding: UTF-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,unique=True,verbose_name=_('user'),related_name='my_profile')
one_card=models.FileField(u'一卡通',null=True,blank=True,upload_to='onecard')
#########################关键是如下函数
def image_img(self):
if self.one_card:
return str('<img src="%s" />' % self.one_card.url)
else:
return u'上传头像'
image_img.short_description = '头像'
image_img.allow_tags = True
adminx.py
#-*- coding: UTF-8 -*-
# Register your models here.
import xadmin
from models import MyProfile
class MyProfileAdmin(object):
list_display = ('user','favourite_snack','image_img')
list_display_links = ('user','image_img')
xadmin.site.register(MyProfile,MyProfileAdmin)
效果图如下:¶
很显然,该控制一下上传的图片了¶
使用django-stdimage解决此问题
安装¶
得有PIL哦¶
pip install django-stdimage
添加‘stdimage’至‘INSTALLED_APPS’
使用¶
models.py
¶
#-*- coding: UTF-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
#########################关键StdImageField()
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,unique=True,verbose_name=_('user'),related_name='my_profile')
one_card=StdImageField(upload_to='onecard', variations={'thumbnail': (100, 75)}) # creates a thumbnail resized to maximum size to fit a 100x75 area
#########################关键self.one_card.thumbnail.url
def image_img(self):
if self.one_card:
return str('<img src="%s" />' % self.one_card.thumbnail.url)
else:
return u'上传头像'
image_img.short_description = '头像'
image_img.allow_tags = True