First of all, it looks like this to accept file registration with a Web service.
File registration ↓ File display
In particular, Django has a class called ** File Field **, which is dedicated to saving files. Since there are classes called ** upload form ** and ** model ** I think it's pretty easy to do.
The upload side is awkward to write, so the official document may be okay. (File Upload) Roughly speaking, it looks like this
Classes supported by Django | function |
---|---|
File field | Receive file information from the request and record the binary data in the directory and the file address in the DB |
Upload form | Set a value in the field of the model (entity in Java) |
model | It has a field of model (entity in Java). Django's model comes standard with an ORM feature, and DBs and fields are always migrated and synchronized. In addition, save to the model()The method is installed. Auto persistence unit(´ ・ ω ・ `) |
First, to set the media file Set the root directory for media files.
Set setting.py as usual.
setting.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #← Add this
MEDIA_URL = '/media/'
BASE_DIR is two above setting.py, that is, the root directory of the app with ** manage.py **. It means that. Therefore, the root directory of the media file is set to the media directory ** in the same directory as ** manage.py. And I set the URL to access the media file to ** / media / **.
Actually, in this state, even if Django side is OK, Nginx side that receives access Because it gives an error such as "File is too big!".
I'll send you a big image file. I have to write the setting. Let's open the config file
% sudo vim /etc/nginx/conf.d/site.conf $Location of Nginx settings for Ubuntu. If you're a CentOS sect, try a different file
site.conf
server {
listen 80;
listen [::]:80;
server_name sample;
client_max_body_size 20M; #add to. Set the maximum size of request transmission to 20 Mbytes
location /static {
alias /home/The user name you set/App root/static;
}
location /media { #add to. Set media file and URL
alias /home/The user name you set/App root/media;
}
location / {
proxy_pass http://127.0.0.1:8000;
}
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
}
Let's make sure that location and Django's media root point to the same location like this (^-^)
This completes the server settings!
It's annoying, so I'll break it down and explain (´ ・ ω ・ `) The file field is used by incorporating it into the model like this.
fileModel.py
from django.core.validators import FileExtensionValidator
from django.db import models
'''
Image model
@author Nozawa
'''
class Picture(models.Model):
id = models.BigAutoField(primary_key=True,unique=True)
name = models.CharField(max_length=200)
image = models.FileField(upload_to='upload_pict/%Y/%m/%d/',
verbose_name='Uploaded image',
validators=[FileExtensionValidator(['jpg','png','gif', ])],
) #upload_Select the save destination directory with to Select the extension with validators. Verbosity_Set how to display on the management screen with name
uploader = models.CharField(max_length=200)
uploadDate = models.DateField()
updateDate = models.DateField()
deleteFlg = models.BooleanField()
def __str__(self):
return '<Picture:id' + str(self.id) + ', ' + \
self.name + '(' + str(self.uploader) + ')>'
The upload form is used like this.
PictUploadForm.py
'''
Model form for image upload
'''
class PictUploadForm(forms.ModelForm):
class Meta:
model = Picture
fields = ['name', 'image']
pictureService.py
def createPicutre(self, request):
pict:PictUploadForm = PictUploadForm(request.POST, request.FILES, instance=pictObj)
pict.errors
if pict.is_valid():
#Check if the value is correct(Validation)
pict.save()
#Register value in DB
In fact, the upload form is a function that omits the original way of writing file uploads. The upload form is by entering the model instance and request. ** A convenient class that automatically sets values for your model **!
Originally, as the official document says, it is written like this
sample.py
instance = ModelWithFileField(file_field=request.FILES['file']) #The field name is specified in the constructor and set.
instance.save()
Finally, the upload side display screen will be displayed.
UploadView.py
class UploadView(TemplateView):
#Initialization process
def __init__(self):
self.params = {
'form': PictUploadForm.PictUploadForm(),
}
#Display image form
def get(self, request):
#Substitute image object
return render(request, 'memFrame/Upload screen.html', self.params)
Upload screen.html
<form action="{% url 'pictUpload' %}" method="post" enctype="multipart/form-data"> <!--Set up a multipart and prepare for file upload-->
{% csrf_token %}
{{ form.name }}
{{ form.image }}
<tr>
<td>
<input type="submit" value="Upload an image!"/>
</td>
</tr>
</form>
ViewingView.py
class ViewingView(TemplateView):
#Image service class
pictService:PictService = PictService.PictService()
#Display image form
def get(self, request):
#Substitute image object
pictList:list = self.pictService.findAll()
self.params = {
'picts':pictList,
}
print(pictList)
return render(request, 'myapplication/Display screen.html', self.params)
Display screen.html
{% for pict in picts %}
<h2>{{ pict.name }}</h2>
<img src='{{pict.image.url}}' width=200> #Specify the URL of the file field in the image tag
{% endfor %}
I was able to display the uploaded image ヾ (.> ﹏ <.) ノ ✧ *.