I will summarize about file upload with django (versino3.1 in this article). By reading this article 1 Upload text 2 Upload image 3 Audio upload You can find out how to do it. This article is primarily aimed at django and programming beginners, but assumes that you already know the basics of the django architecture as a whole.
Also, in this article, 1 Start the project with the following command under the post_file directory.
$ django-admin startproject post_file .
2 After that, create template, static, and media directories, and assume that the directory structure is as follows.
$ project/(Project directory)
.
│── config/(Setting directory)
│ │── __init__.py
│ │── settings.py
│ │── urls.py
│ │── wsgi.py
│── post_file_app/(Application directory)
│ │── __initi__.py
│ │── admin.py
│ │── apps.py
│ │── migrations
│ │ │── __init__.py
│ │── models.py
│ │── test.py
│ │── views.py
│── manage.py
│── template/
│── static/
│── media/
│ │──image/
│ │──audio/
Regarding file upload, 1 Upload from the administrator screen (by the site administrator) 2 Upload from the user form (by the site user) There are two possibilities, so we will classify them below.
project/config/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'post_file_app',#Add this
'media',#Add this
]
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent#Add this
MEDIA_ROOT = os.path.join(BASE_DIR,'media')#Add this
MEDIA_URL = '/media/'#Add this
Instead of storing uploaded images and audio files directly in the database, django stores them in a pre-prepared file and retrieves the file from that path when needed. In the above, the directory to store is specified by MEDIA_ROOT.
In addition, MEDIA_URL is a setting that assigns a url called / media / <file_name> when displaying a file.
project/post_file_app/model.py
class PostFile(models.Model):
usersname = models.CharField(max_length=50)#Text upload
image =models.ImageField(upload_to='images/',verbose_name='image',null=True,blank=True)#Image upload
audio = models.FileField(default='', upload_to='audio/')#Audio upload
def __str__(self):
return self.usersname
Note that CharField, ImageField, and FileField are used properly depending on what you upload. Don't forget to migrate the model with the following two commands.
$ python manage.py makemigrations
$ python manage.py migrate
You cannot upload from the administrator screen just by defining the PostFile class in model.py. By adding to admin.py as shown below, you can upload from the administrator screen.
project/post_file_app/admin.py
from .models import PostFile
admin.site.register(PostFile)
In this case, in addition to uploading from the administrator screen, a new one 1 Create input form (html file creation, form.py creation) 2 Implementation of validation of uploaded file (logic is described in views.py) (However, I will not write validation myself in this article, so I will write a little code).
First, prepare an html file. Create a post.html file in the project / template / directory and write it as follows.
project/template/post.html
<!doctype html>
<html lang="en">
<head>
</head>
<body >
<form method="POST" action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form.username }}
{{ form.image }}
{{ form.audio }}
</body>
</html>
First of all, encenctype ='multipart / form-data' must be described in the html form tag when uploading an image or audio file. If you omit this, django will not be able to retrieve images and audio files later.
Also, {% csrf_token%} is like a spell and is required when uploading files.
In addition, username, image, audio must match the variable names (username, image, audio) already mentioned in project / post_file_app / model.py.
Next, create a new form.py in post_file_app and add the following to create an input form.
project/post_file_app/form.py
from django import forms
from .models import PostFile
class PostFileForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].widget.attrs.update({'placeholder':'text'})
self.fields['image'].widget.attrs.update({'placehodler':'image upload'})
self.fields['audio'].widget.attrs.update({'placehodler':'audio upload'})
class Meta:
model = TestPost
fields = ('text','image','audio')
To display the last created form, create a view in views.py and assign a url to the view in urls.py.
project/post_file_app/views.py
from django.shortcuts import render,redirect
from django.views.generic import CreateView
from .forms import PostFileForm
class PostFileView(CreateView):
def post(self,request,*args,**kwargs):
form = PostFileForm(request.POST,request.FILES)
content_dict={
'form':form
}
if not form.is_valid():#Check if the file is entered correctly (validation)
return render(request,'error.html')#error.html is not created in the article, but please prepare it yourself.
form.save()
return redirect('success_page')
def get(self,request,*args,**kwargs):
form = PostFileForm(data=request.GET)
return render(request,'post.html',{'form':form,})
Here, there is a variable called form, but please match it with the form.username, form.image, and form.audio of post.html mentioned above. Also, there are request.POST and request.FILES as arguments of PostFileForm (). The former is what django needs to get text, and the latter to get images and audio files.
project/post_file_app/urls.py
from django.urls import path
from .views import Register,LoginView,LogoutView
from mystudio.views import RenderPostedSong
from .views import PostSongView,TestPostView,TestPostView,RenderTestPost
urlpatterns = [
path('post_file_view/',PostFileView.as_view(),name='post_file_view'),
path('success/',success,name='success_page',#View is not defined in this article
path('error/',error,name='error_page',#View is not defined in this article
]
that's all. You can now upload text, images, and audio files in django.
Recommended Posts