Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Db Images video

How can I store Images, Videos and Audio via Django in a Mysql db?

I know I can either store the link to the image, video, audio, or the image, video, audio itself.

But how does this exactly work.

I know about the models and how they create tables via the manage.py. But is there a good tutorial on how to create an image (e.g. jpg, tiff etc) database via Django.

Thanks

L.

like image 674
MacPython Avatar asked Feb 26 '23 19:02

MacPython


2 Answers

The Model you need models.py

from django.db import models

class Video(models.Model):
    name= models.CharField(max_length=500)
    file= models.FileField(upload_to='videos/', null=True, verbose_name="")

Form class you need forms.py

from .models import Video

class VideoForm(forms.ModelForm):
    class Meta:
        model= Video
        fields= ["name", "file"]

inside views.py

from django.shortcuts import render
from .models import Video
from .forms import VideoForm

def showvideo(request):

    firstvideo= Video.objects.last()

    videofile= firstvideo.file.url


    form= VideoForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()

    context= {'file_url': videofile,
              'form': form
              }

    return render(request, 'videos.html', context)

And finally your template: videos.html

<body>

<h1>Video Uploader</h1>
<form enctype="multipart/form-data" method="POST" action="">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Upload"/>
</form>

<br>
<video width='600' controls>
    <source src='{{ file_url }}' type='video/mp4'>
    File not found.
</video>
<br>
</p>

</body>
like image 191
tshubham7 Avatar answered Mar 05 '23 16:03

tshubham7


Daniel is referring to the fact that storing large binary files in a DB is not efficient. Use the filesystem instead - take a look at FileField and ImageFileField, which are designed to handle file uploads:

http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield

The only thing stored in the DB is the path to the binary file.

like image 26
Chris Lawlor Avatar answered Mar 05 '23 17:03

Chris Lawlor