In one of my django project I am trying to upload files. Files can be video files and can be big as 20 MB. I am trying to upload it with celery
and upload_file_handler
method given in django docs.
What I did is it.
class MyVideo(models.Model):
user = models.ForeignKey(User)
video = models.FileField(null=True, blank=True, upload_to="video")
def __unicode__(self):
return self.user.username
In forms.py
class VideoForm(forms.ModelForm):
video = forms.FileField(required=False)
class Meta:
model = MyVideo
exclude = ['user']
def clean_video(self):
video = self.cleaned_data['video']
if video and video._size > (10 * 1024 * 1024):
raise forms.ValidationError("only 10 MB video is allowed")
return self.cleaned_data['video']
In View.py
class CreateDigitalAssetsView(LoginRequiredMixin, CreateView):
template_name = "video_create.html"
form_class = VideoForm
def get_success_url(self):
return reverse("video_url")
def form_valid(self, form):
user = self.request.user
video = form.cleaned_data['video']
if video:
handle_uploaded_file(video)
# stuck here what to do next.
def handle_uploaded_file(f):
filename, extension = os.path.splitext(video.name)
with open('media/video/'+filename, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
I am stuck here what to do next after calling handled_uploaded_file
. Please guide me how can i use this written file using hanldle_uploaded_file
to save in django model.
You'll need to return the path of the created file (relative to the /media root) from your handle_uploaded_file function, and then save that to the model's video field.
So something like:
def handle_uploaded_file(f):
filename, extension = os.path.splitext(video.name)
relative_path = "video/%s" % filename
full_path = "media/%s" % relative_path
with open(full_path, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return relative_path
def form_valid(self, form):
...
if video:
relative_path = handle_uploaded_file(video)
form.instance.video = relative_path
form.instance.save()