• Django上传文件最简单最官方的方法


    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'))
    ]
    

    效果图

  • 相关阅读:
    算法训练——整数平均值
    算法训练——字符删除
    算法训练——最大的算式
    flask_sqlalchemy查询时将date类型修改为datetime类型
    mysql更改时区
    python 省略号 三个点...的含义
    ubuntu系统安装gedit
    python操作hdfs总结
    流式上传下载
    python将文件夹打包
  • 原文地址:https://www.cnblogs.com/PyKK2019/p/11119574.html
Copyright © 2020-2023  润新知