这是我的代码。
在模型.py
class ChatUser(models.Model):
"""User Model"""
username = models.CharField(max_length=64)
password = models.CharField(max_length=64)
GENDER_CHOICES = (
(0, u'女'),
(1, u'男')
)
sex = models.IntegerField(default=0, choices=GENDER_CHOICES)
description = models.CharField(max_length = 256, blank=True, default=None)
headphoto = models.ImageField(upload_to='photos/users/' , blank=True, default=None)
class Meta:
db_table = 'user'
def __unicode__(self):
return "<ChatUser {'%s'}>" % self.username
在forms.py中
class UserForm(ModelForm):
class Meta:
model = ChatUser
fields = ( 'username' , 'password' , 'sex' , 'description', 'headphoto')
和views.py
@csrf_exempt
def index(request):
c = {}
if request.method == 'POST':
form = UserForm(request.POST , request.FILES)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = ChatUser.objects.filter( username = username, password = password )
if user:
print 'userhead ' , user[0].headphoto
path = settings.WEB_BASE_PATH + '/' + str(user[0].headphoto)
print path
import os
try:
os.remove( path )
except:
pass
import Image
uploaded = request.FILES['headphoto']
from django.core.files.base import ContentFile
file_content = ContentFile(uploaded.read())
user[0].headphoto.save( str(user[0].headphoto), file_content )
else:
form.save()
return HttpResponseRedirect('thanks.html')
else:
print 'error ' , form.errors
else:
form = UserForm(initial={'username':'watsy', 'password':'123123'})
c['form'] = form
return render_to_response('index.html', c)