Django note 4

8 HTML customization (web app file)

Static files are required to achieve a variety of designs.

There are two types of static files in Django. The first is pre-uploaded Static Files like JavaScript, CSS, Image. The second is user-uploaded MP4s and PDFs. Such files are called Media Files.

8.1 Static Files Put Static Files in a static folder inside each APP.

For example:

mysite/
    manage.py
    mysite/
        static/
            css/
                bootstrap.min.css
            js/
                bootstrap.min.js
        __init__.py
        settings.py
        urls.py
        wsgi.py
    myapp/
        static/
            css/
                bootstrap.min.css
            js/
                bootstrap.min.js
        templates/
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
        urls.py
        views.py

When using with Template: {% static 'file PATH' %}

index.html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    {% load static %}
  </head>
  <body>
    <p>Test Page</p>
    <script src="{% static 'js/bootstrap.min.js' %}"/>
  </body>
</html>

STATIC_URL can be specified in settings.py for static files folder.

e.g.

#STATIC FILES file access PATH
STATIC_URL = '/static/'
#STATIC FILES File save PATH
STATIC_ROOT = '/static/'

8.2 Media Files

Specify the MEDIA_ROOT parameter in settings.py. e.g.

#Media file storage PATH
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#Media file access PATH
MEDIA_URL = '/media/'

models.py How to write:

models.py


        ...
class File(models.Model):
    filedata = models.FileField(upload_to='files')
    filepic = models.ImageField(null=True, upload_to='pics')
    uploadtime = models.DateTimeField('updated time', default = timezone.now)
        ...

The FileFiled upload_to parameter specifies a subfolder. For MEDIA_ROOT = os.path.join (BASE_DIR,'media'), FileField (upload_to ='files'): The uploaded file is saved in ./media/files/.

views.py How to write: When uploading:

      ...
def play(request, id):
    f = File.objects.get(id=id)
    data = {'video': f}
    #Use url value
    data['url'] = f.filedata.url
    return render(request, 'player.html', data)
      ...

File usage:

views.py


      ...
def uploadfile(request):
    if request.method != 'POST':
        return render(request, 'upload.html')

    if not form.is_valid():
        return render(request, 'upload.html')

    if 'filedata' in request.FILES:
        filedata = request.FILES['filedata']
    else:
        return render(request, 'upload.html')

    if 'filepic' in request.FILES:
        filepic = request.FILES['filepic']
    else:
        filepic = None

    try:
        f = File(filedata=filedata, filepic=filepic)
        f.save()
        return render(request, 'success.html')
    except:
        return render(request, 'upload.html')
      ...

Template How to write:

player.html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    {% load static %}
  </head>
  <body>
    <video src={{ url }} width="640" height="480" preload="none" autoplay class="videoPlayer" controls="controls">
        Your browser does not support the video tag.
    </video>
    <script src="{% static 'js/bootstrap.min.js' %}"/>
  </body>
</html>

How to write project urls.py:

urls.py


from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^play/(?P<id>\d+)/$', views.play, name='play'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

If you want to delete the file:

Don't forget to delete files in Database, not just objects:

views.py


        ...
try:
    existfileObj = File.objects.get(filename=filename)
    os.remove(existfileObj.filedata.path)
    existfileObj.delete()
except File.DoesNotExist:
    print('File in not exist.')
    existfileObj = None
else:
    #use the path value
    os.remove(existfileObj.filedata.path)
    os.remove(existfileObj.filepic.path)
    existfileObj.delete()
        ...

Recommended Posts

Django note 4
Django Note 5
Django Note 1
Django note 3
Django note 2
Note
Django
Note
Note
Django Girls Tutorial Note
(Note) Django in Vagrant environment
[Note] [For myself] Django command
django update
pyenv note
[Note] Django project creation and terminology
Django memorandum
django search
Django installation
GroupBy Note
Django Summary
Django test
Django # 2 (template)
argparse note
Django hands-on
Note: Python
Touch django
django notes
Django Summary
Django basics
Django Shoho
Django defaults
Ansible Note
Django + Docker
Django Glossary
Python note
Django search
Install Django
[Note] Run Django on Amazon Linux 2
Django: References
Note: Send an email with Django
direnv note
Django startup
Django notes
[Note] RepresenterError
Django NullCharField
Deploy Django api on heroku (personal note)
(Note) Template file search order in Django
A note on enabling PostgreSQL with Django
DJango Note: From the beginning (form processing)
Django environment construction
[Note] Image resizing
Python study note_002
Django ~ settings.py edition ~
Note: Python Decorator
Python programming note
Django Heroku Deploy 1
[Python] Learning Note 1
Django HTML Template # 2
Django Contact Form 2
Django begins part 1
Django model: ManyToManyField