1.配置media路径
在settings.py
中添加如下代码:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
2.定义数据表
import os
from django.db import models
from django.utils.timezone import now as timezone_now
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return f'quotes/{now:%Y/%m/%Y%m%d%H%M%S}{ext}'
class Quote(models.Model):
class Meta:
verbose_name = 'quote'
verbose_name_plural = verbose_name
author = models.CharField('author', max_length=200)
quote = models.TextField('quote')
picture = models.ImageField('picture', upload_to=upload_to, blank=True, null=True)
def __str__(self):
return self.quote
这里的upload_to函数会自动把文件的名称修改为日期型的名称,不会重名。
3.添加form表单
forms.py
文件
from django import forms
from .models import Quote
class QuoteForm(forms.ModelForm):
class Meta:
model = Quote
fields = '__all__'
4.编写视图代码
from django.shortcuts import render, redirect
from .forms import QuoteForm
def add_quote(request):
form = QuoteForm()
if request.method == 'POST':
form = QuoteForm(
data=request.POST,
files=request.FILES
)
if form.is_valid():
form.save()
return redirect('quote:add_quote')
else:
return render(request, 'quotes/add_quote.html', {
'form': form
})
5.编写模板html代码
<form action="{% url 'quote:add_quote' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">save</button>
</form>
6.添加url映射
在app的目录的urls.py
添加
from django.urls import path
from quotes.views import add_quote
app_name = 'quote'
urlpatterns = [
path('add/', add_quote, name='add_quote')
]
在项目目录的urls.py
文件添加
from django.urls import path, include
urlpatterns = [
path('quotes/', include('quotes.urls', namespace='quote'))
]