import datetime from django.contrib.gis.db import models from django import forms from django.urls import reverse from django.apps import apps from utils.util import render_images, markdown_to_html from locations.models import Location, CheckIn def get_upload_path(self, filename): return "audio/%s/%s" % (datetime.datetime.today().strftime("%Y"), filename) class Audio(models.Model): title = models.CharField(max_length=200) subtitle = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique_for_date='pub_date', blank=True) body_html = models.TextField(blank=True) body_markdown = models.TextField(blank=True) pub_date = models.DateTimeField(default=datetime.datetime.now) mp3 = models.FileField(blank=True, null=True, upload_to=get_upload_path) ogg = models.FileField(blank=True, null=True, upload_to=get_upload_path) point = models.PointField(blank=True, null=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True) class Meta: ordering = ('-pub_date',) get_latest_by = 'pub_date' def __str__(self): return self.title def get_absolute_url(self): return reverse("prompt:detail", kwargs={"slug": self.slug}) @property def get_previous_published(self): return self.get_previous_by_pub_date(status__exact=1) @property def get_previous_admin_url(self): n = self.get_previous_by_pub_date() return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[n.id]) @property def get_next_published(self): return self.get_next_by_pub_date(status__exact=1) @property def get_next_admin_url(self): model = apps.get_model(app_label=self._meta.app_label, model_name=self._meta.model_name) try: return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.get_next_by_pub_date().pk]) except model.DoesNotExist: return '' def get_type(self): return str(self.__class__.__name__) def save(self, *args, **kwargs): md = render_images(self.body_markdown) self.body_html = markdown_to_html(md) if not self.point: self.point = CheckIn.objects.latest().point try: self.location = Location.objects.filter(geometry__contains=self.point).get() except Location.DoesNotExist: raise forms.ValidationError("There is no location associated with that point, add it: %sadmin/locations/location/add/" % (settings.BASE_URL)) super(Audio, self).save(*args, **kwargs)