Commit f6fd9f5d authored by fred's avatar fred

add track upload form

parent f347780c
from django import forms
def get_nonstop_zones():
from emissions.models import Nonstop
return [('', '')] + [(x.id, x.title) for x in Nonstop.objects.all()]
class UploadTracksForm(forms.Form):
tracks = forms.FileField(widget=forms.ClearableFileInput(
attrs={'multiple': True, 'accept': 'audio/*'}))
nonstop_zone = forms.ChoiceField(choices=get_nonstop_zones)
import os
import mutagen
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
......@@ -50,7 +54,7 @@ class Track(models.Model):
class NonstopFile(models.Model):
filepath = models.CharField(_('Filepath'), max_length=255)
filename = models.CharField(_('Filename'), max_length=255, null=True, unique=True)
filename = models.CharField(_('Filename'), max_length=255, null=True)
creation_timestamp = models.DateTimeField(auto_now_add=True, null=True)
track = models.ForeignKey(Track, null=True)
......@@ -58,6 +62,9 @@ class NonstopFile(models.Model):
def short(self):
return self.filepath[len(REMOTE_BASE_PATH):]
def set_track_filepath(self, filepath):
self.filepath = os.path.join(REMOTE_BASE_PATH, 'Tracks', filepath)
class SomaLogLine(models.Model):
class Meta:
......
{% extends "base.html" %}
{% load i18n %}
{% block appbar %}
<h2>Nonstop - {% trans "Upload" %}</h2>
{% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="buttons">
<button class="submit-button">{% trans "Upload" %}</button>
<a class="cancel" href="...">{% trans "Cancel" %}</a>
</div>
</form>
{% endblock %}
from django.conf.urls import url
from .views import SomaDayArchiveView, SomaDayArchiveCsvView, RedirectTodayView, TrackDetailView, ArtistDetailView, ArtistListView, StatisticsView
from .views import SomaDayArchiveView, SomaDayArchiveCsvView, RedirectTodayView, TrackDetailView, ArtistDetailView, ArtistListView, StatisticsView, UploadTracksView
urlpatterns = [
# Example: /2012/nov/10/
......@@ -15,4 +15,6 @@ urlpatterns = [
url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/(?P<day>[0-9]+)/csv$',
SomaDayArchiveCsvView.as_view(),
name="archive_day_csv"),
url(r'^upload/$', UploadTracksView.as_view(), name='nonstop-upload-tracks'),
]
import csv
import datetime
from cStringIO import StringIO
import os
import mutagen
from django.core.files.storage import default_storage
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
from django.views.generic.base import RedirectView, TemplateView
from django.views.generic.dates import DayArchiveView
from django.views.generic.detail import DetailView
from django.views.generic.edit import FormView
from django.views.generic.list import ListView
from .models import SomaLogLine, Track, Artist
from .forms import UploadTracksForm
from .models import SomaLogLine, Track, Artist, NonstopFile
from emissions.models import Nonstop
class SomaDayArchiveView(DayArchiveView):
......@@ -136,3 +144,46 @@ class StatisticsView(TemplateView):
for zone in context['zones']:
zone.stats = ZoneStats(zone, **kwargs)
return context
class UploadTracksView(FormView):
form_class = UploadTracksForm
template_name = 'nonstop/upload.html'
success_url = '.'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
tracks = request.FILES.getlist('tracks')
if not form.is_valid():
return self.form_invalid(form)
missing_metadata = []
metadatas = {}
for f in tracks:
metadata = mutagen.File(f, easy=True)
f.seek(0)
if not metadata or not metadata.get('artist') or not metadata.get('title'):
missing_metadata.append(f.name)
else:
metadatas[f.name] = metadata
if missing_metadata:
form.add_error('tracks', _('Missing metadata in: ') + ', '.join(missing_metadata))
return self.form_invalid(form)
for f in tracks:
monthdir = datetime.datetime.today().strftime('%Y-%m')
filepath = '%s/%s' % (monthdir, f.name)
default_storage.save(os.path.join('nonstop', 'tracks', filepath), content=f)
nonstop_file = NonstopFile()
nonstop_file.set_track_filepath(filepath)
metadata = metadatas[f.name]
artist, created = Artist.objects.get_or_create(name=metadata.get('artist')[0])
track, created = Track.objects.get_or_create(title=metadata.get('title')[0], artist=artist)
nonstop_file.track = track
nonstop_file.save()
if request.POST.get('nonstop_zone'):
track.nonstop_zones.add(
Nonstop.objects.get(id=request.POST.get('nonstop_zone')))
messages.info(self.request, '%d new track(s)' % len(tracks))
return self.form_valid(form)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment