university.py 1.53 KB
Newer Older
1
from django.db import models
2
3
from django.core.validators import MinValueValidator, MaxValueValidator

4
from rex.utils.friendly_path import friendly_path
5
6
7
from rex.models.country import Country

import reverse_geocoder as rg
8

Florent Chehab's avatar
Florent Chehab committed
9
10
path_and_rename = friendly_path("uploads/universities/logos/", 'name')

11
12

class University(models.Model):
13
14
15
    """
    Model storing information about universities
    """
16
    name = models.CharField(max_length=200)
17
    acronym = models.CharField(max_length=20)
18
    localization_lat = models.DecimalField(
Florent Chehab's avatar
Florent Chehab committed
19
        max_digits=10,
20
        decimal_places=6,
Florent Chehab's avatar
Florent Chehab committed
21
22
        validators=[MinValueValidator(-85.05112878), 
                    MaxValueValidator(85.05112878)]
23
24
        )
    localization_lon = models.DecimalField(
Florent Chehab's avatar
Florent Chehab committed
25
        max_digits=10,
26
27
28
29
        decimal_places=6,
        validators=[MinValueValidator(-180), MaxValueValidator(180)]
        )
    country = models.ForeignKey(Country, on_delete='CASCADE')
Florent Chehab's avatar
Florent Chehab committed
30
31
    logo = models.ImageField(upload_to=path_and_rename, max_length=250, 
        default='path/to/my/default/image.jpg') # TODO CHANGE !
32
33

    def localization(self):
Florent Chehab's avatar
Florent Chehab committed
34
        return {'lat': self.localization_lat, 'lon': self.localization_lon}
35
36
37
38
39
40
41
42
43
44

    def save(self, *args, **kwargs):
        """
        Override traditional save function to make sure that 
        the Country is coherent with given lat / lon
        """
        coord = (self.localization_lat, self.localization_lon)
        res = rg.search(coord, verbose=False)
        self.country = Country.objects.get(pk=res[0]['cc'])
        super(University, self).save(*args, **kwargs)