Django upload files simplest and most official way

1. The media path configuration

In settings.pyadd the following code:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

2. Define Data Sheet

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

Here upload_to function will automatically modify the name of the file name date type, will not be the same name.

3. Add form form

forms.pyfile

from django import forms

from .models import Quote


class QuoteForm(forms.ModelForm):
    class Meta:
        model = Quote
        fields = '__all__'

4. Preparation of view code

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. Write the code html template

<form action="{% url 'quote:add_quote' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">save</button>
</form>

6. Add the url mappings

In the catalog of the app urls.pyto add

from django.urls import path

from quotes.views import add_quote

app_name = 'quote'
urlpatterns = [
    path('add/', add_quote, name='add_quote')
]

In the project directory urls.pyAdd File

from django.urls import path, include

urlpatterns = [
    path('quotes/', include('quotes.urls', namespace='quote'))
]

Renderings

Guess you like

Origin www.cnblogs.com/PyKK2019/p/11119574.html