新建工程和建立app就不用貼出來了,我這裏是測試圖片上傳的功能可否實現,因此項目都是新的,正常在以有的app下就能夠html
from django.dbimport models
# Create your models here.
class User(models.Model):
name= models.CharField(max_length=50)
# upload_to 指定上傳文件位置
# 這裏指定存放在img/ 目錄下
headimg = models.FileField(upload_to="img/")
# 返回名稱
def__str__(self):
returnself.namepython
(mypy3) ➜ BBS python manage.py makemigrations數據庫
Migrations for 'app01':django
app01/migrations/0001_initial.pysession
- Create model Userapp
(mypy3) ➜ BBS python manage.py migrate ide
Operations to perform:post
Apply all migrations: admin, app01, auth, contenttypes, sessions測試
MEDIA_ROOT= os.path.join(BASE_DIR, 'media').replace("\\", "/")
MEDIA_URL = '/media/'url
from django.conf.urlsimport url
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^regsiter/', views.regsiter),
# url(r'', TemplateView.as_view(template_name="app01/index.html")),
path('app01/', include('app01.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.urlsimport path
from . import views
app_name = 'app01'
urlpatterns = [
path('add/', views.add, name='add'),
# path('index/', views.index, name='index'),
]
TEMPLATES= [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
數據須要校驗的狀況下,若是你不想校驗,這個能夠忽略
from django import forms
# 表單類用以生成表單
class AddForm(forms.Form):
name = forms.CharField()
headimg = forms.FileField()
from django.shortcutsimport render
from .models import User
from .forms import AddForm
# Create your views here.
def add(request):
# 判斷是否爲post 方法提交
ifrequest.method == "POST":
af = AddForm(request.POST, request.FILES)
# 判斷表單值是否和法
ifaf.is_valid():
name = af.cleaned_data['name']
headimg = af.cleaned_data['headimg']
user = User(name=name, headimg=headimg)
user.save()
returnrender(request, 'app01/index.html', context={"user":user})
else:
af = AddForm()
returnrender(request, 'app01/add.html', context={"af":af})
上傳的html
<!-- templates/users/add.html -->
<!doctype html>
<html>
<head>
<title>Add</title>
<meta charset="utf-8">
</head>
<body>
<h1>Add!</h1>
<form method="post" enctype="multipart/form-data" action="{% url'app01:add' %}">
{%csrf_token %}
{{ af.as_p }}
<inputtype="submit" value="OK"/>
</form>
</body>
</html>
查看的html
<!-- templates/users/index.html -->
<!doctype html>
<html>
<head>
<title>Detail</title>
<meta charset="utf-8">
</head>
<body>
<p>{{user.name}}</p>
<img width="50%" height="50%"src="/media/{{ user.headimg }}"></body></html>