Linux下开发python django程序(设置admin后台管理上传文件和前台上传文件保存数据库)

1.项目创建相关工作参考前面

2.在models.py文件中定义数据库结构

import django.db import models
class RegisterUser(models.Model):
username=models.CharField(max_length=30)
headImg = models.FileField(upload_to='./upload/')
def __unicode__(self):
return self.username

3.生成数据库

python manage.py syncdb

4运行开发服务器 访问管理员界面

二.前台上传文件保存到数据库

1.生成项目和APP 过程同参考前面

2.设置models.py,urls.py参考前面文章设置

from django.db import models

# Create your models here.

class RegisterUser(models.Model):
username=models.CharField(max_length=30)
headImg = models.FileField(upload_to='./upload/')
def __unicode__(self):
return self.username

3.views.py定义冲界面取得POST的值和生成上传文件并且保存于数据库中

from django.http import HttpResponse
from django.template import loader,Context,Template
from django.shortcuts import render_to_response
from app1.models import User,Author,Book,RegisterUser
from django import forms def register(req):
if req.method == 'POST':
form = UserForm(req.POST,req.FILES)
if form.is_valid():
print form.cleaned_data
paths='./upload/'+form.cleaned_data['img'].name
paths1 = paths.encode('utf-8')
username = form.cleaned_data["name"]
print paths1
fp=file(paths,'wb')
s=form.cleaned_data['img'].read()
fp.write(s)
fp.close()
ruser = RegisterUser()
ruser.username = username
ruser.headImg = paths
ruser.save()
return HttpResponse('ok') else:
form = UserForm()
return render_to_response('register.html',{'form':form})
上一篇:orchestrator HTTP接口forget-cluster误下线集群问题


下一篇:【HDU - 4341】Gold miner(分组背包)