Django ---uploads files

python manage.py startproject   mysite

python mange.py startapp uploads

 setting 配置

INSTALLED_APPS中加入app name 'uploads',

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')


根URL 配置
from django.conf.urls import include, url,re_path
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    re_path('uploads/',include('uploads.urls'))
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

 



MODEL 配置

from django.db import models

class User(models.Model):
    gender_choices = (
        ('0', '男'),
        ('1', '女'),
        ('2', '人妖')
    )

    name = models.CharField('用户名', max_length=256)

    sex = models.CharField(max_length=16, choices=gender_choices, default='0')

    img = models.ImageField(upload_to='images/', verbose_name='用户头像')

    introduce = models.FileField(verbose_name='用户简历', upload_to='introduce/')


    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"

 


执行python manage.py makemigrations,migrate 创建数据库

admin 配置

from django.contrib import admin
from . import models
admin.site.register(models.User)

 



URL 配置

from django.urls import path
from . import views

urlpatterns = [
    path('add/',views.add),
    path('detail/',views.detail),
]

 

 
View 配置

from django.shortcuts import render
from .models import User


def add(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        img = request.FILES.get('img')
        introduce = request.FILES.get('introduce')
        user = User(name=username, img=img, introduce=introduce)
        user.save()
        return render(request, 'uploads/add.html', locals())
    return render(request, 'uploads/add.html', locals())

def detail(request):
    user_list = User.objects.all()
    return render(request, 'uploads/detail.html', locals())

 

 
创建templates/uploads/add.html  &  detail.html 文件
add.html
<h1>创建新用户</h1>
<form action="/uploads/add/" enctype="multipart/form-data" method="post">
{#    #使用post方法必须使用下面这句代码#}
    {% csrf_token %}
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username" /><br /><br />
    <label for="img">头像:</label>
    <input type="file" id='img' name="img" /><br /><br />
    <label for="introduce">简历:</label>
    <input type="file" id='introduce' name="introduce" /><br /><br />

    <input type="submit" value="提交">

</form>

 

detail.html
{% for user in user_list %}

<h1>{{ user.name }}</h1>
<img src="{{ user.img.url }}" />
    <p>{{ user.img.name }}</p>
    <p>{{ user.img.size }}</p>
<br />
<br />

{% for line in user.introduce.readlines %}
    <p>{{ line.decode }}</p>
{% endfor %}

<br />
<br />


{% endfor %}

 


DONE


 





posted @ 2018-10-18 23:17  Magicking  阅读(230)  评论(0编辑  收藏  举报