university.py 1.55 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
from rex.models.localization import Country
6
7

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
linting    
Florent Chehab committed
21
        validators=[MinValueValidator(-85.05112878),
Florent Chehab's avatar
Florent Chehab committed
22
                    MaxValueValidator(85.05112878)]
Florent Chehab's avatar
linting    
Florent Chehab committed
23
    )
24
    localization_lon = models.DecimalField(
Florent Chehab's avatar
Florent Chehab committed
25
        max_digits=10,
26
27
        decimal_places=6,
        validators=[MinValueValidator(-180), MaxValueValidator(180)]
Florent Chehab's avatar
linting    
Florent Chehab committed
28
    )
29
    country = models.ForeignKey(Country, on_delete='CASCADE')
Florent Chehab's avatar
linting    
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

    def save(self, *args, **kwargs):
        """
Florent Chehab's avatar
linting    
Florent Chehab committed
38
        Override traditional save function to make sure that
39
40
41
42
43
        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'])
Florent Chehab's avatar
linting    
Florent Chehab committed
44
        super(University, self).save(*args, **kwargs)