Exemplo n.º 1
0
class Neighbourhood(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    hood_name = models.CharField(max_length = 50)   
    location = LocationField(map_attrs={"center": [36.82, -1.29], "marker_color": "blue"})
    address = AddressAutoHiddenField(blank=True)
    occupants_count = models.IntegerField(default=1)
    admin = models.ForeignKey(Admin_Profile,on_delete=models.CASCADE)

    def __str__(self):
        return self.hood_name 

    def create_hood(self):
        self.save()

    def delete_hood(self):
        self.delete()

    def update_hood(self):
        self.save()


    @classmethod
    def find_neigborhood(cls, neigborhood_id):
        pass

    @classmethod
    def update_occupants(cls):
        pass
Exemplo n.º 2
0
class Map(models.Model):
    location = LocationField(
        map_attrs={
            "style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72",
            "center": (17.031645, 51.106715)
        })
    created_at = models.DateTimeField(auto_now_add=True)
    address = AddressAutoHiddenField()
Exemplo n.º 3
0
class Location(models.Model):
    location = LocationField(
        map_attrs={
            "style": "mapbox://styles/mapbox/outdoors-v11",
            "marker_color": "blue",
            "center": (17.031645, 51.106715)
        })
    create = models.DateTimeField(auto_now_add=True)
    address = AddressAutoHiddenField()
Exemplo n.º 4
0
class Neighbourhood(models.Model):
    name = models.CharField(max_length=80)
    admin = models.ForeignKey(Admin, on_delete=models.CASCADE)
    occupants = models.IntegerField(default=1)
    location = LocationField(map_attrs={
        "center": [36.82, -1.29],
        "marker_color": "blue"
    })
    address = AddressAutoHiddenField(blank=True)

    def __str__(self):
        return self.name
Exemplo n.º 5
0
class Location(models.Model):
    name = models.CharField(null=False, blank=False, max_length=255)

    description = models.TextField(null=False, blank=False)

    created_at = models.DateTimeField(auto_now_add=True)

    free = models.BooleanField(blank=False, null=False, default=False)

    coordinates = LocationField(
        map_attrs={
            "style": "mapbox://styles/mapbox/streets-v11",
            "center": (35.921637, -79.077887),
            "zoom": 5,
            "rotate": True,
            "navigation_buttons": True,
            "track_location_button": True,
            "id": "map",
        })  # this gets reversed when delivered with the api for some reason?

    address = AddressAutoHiddenField(map_id="map")

    class LocationTypeChoices(models.TextChoices):
        PARK = "PA", ("Dog Park")
        RESTAURANT = "RE", ("Restaurant")
        VET = "VE", ("Veterinarian")
        TRAIL = "TR", ("Trail")
        HOUSE = "HO", ("House")

    location_type = models.CharField(
        max_length=2,
        choices=LocationTypeChoices.choices,
        default=LocationTypeChoices.PARK,
        null=True,
        blank=True,
    )

    def __str__(self):
        def loc_type():
            if self.location_type == "HO":
                return "House"
            elif self.location_type == "PA":
                return "Park"
            elif self.location_type == "RE":
                return "Restaurant"
            elif self.location_type == "VE":
                return "Veterinarian"
            return "Trail"

        return f"{loc_type()} called '{self.name[:50]}'"
Exemplo n.º 6
0
class resources(models.Model):
    name = models.CharField(max_length=100)
    location = LocationField(map_attrs={
        "center": [0, 0],
        "marker_color": "blue"
    })
    address = AddressAutoHiddenField()
    pincode = models.CharField(max_length=50)
    work = models.CharField(max_length=100)
    email = models.EmailField()
    phone_number = models.CharField(max_length=12)

    def __str__(self):
        return "%s %s %s %s" % (self.name, self.work, self.location,
                                self.pincode)
Exemplo n.º 7
0
class User(AbstractUser):
    is_verified = models.BooleanField(default=False)
    is_alumni = models.BooleanField(default=False)
    is_faculty = models.BooleanField(default=False)
    profile_photo = models.ImageField(upload_to=upload_user_image_location)
    profile_complete = models.BooleanField(default=0)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    full_name = models.SlugField(editable=False)
    college = models.ForeignKey(College,
                                on_delete=models.SET_NULL,
                                null=True,
                                blank=True)
    course = models.ForeignKey(Course,
                               on_delete=models.SET_NULL,
                               null=True,
                               blank=True)
    department = models.ForeignKey(Department,
                                   on_delete=models.SET_NULL,
                                   null=True,
                                   blank=True)
    specialization = models.ForeignKey(Specialization,
                                       on_delete=models.SET_NULL,
                                       null=True,
                                       blank=True)
    dob = models.DateField(null=True, blank=True)
    system_date_joined = models.DateTimeField(verbose_name="Date Joined",
                                              auto_now=True)
    system_last_login = models.DateTimeField(verbose_name="Last Login",
                                             auto_now=True)
    email = models.EmailField(null=True, unique=True)
    facebook_profile = models.URLField(max_length=1000, null=True, blank=True)
    twitter_profile = models.URLField(max_length=1000, null=True, blank=True)
    linkedin_profile = models.URLField(max_length=1000, null=True, blank=True)
    location = LocationField(map_attrs={
        "center": (15.29, 74.12),
        "marker_color": "blue"
    })
    address = AddressAutoHiddenField()
    position = models.ForeignKey(Position,
                                 on_delete=models.SET_NULL,
                                 null=True,
                                 blank=True)
    phone = models.CharField(max_length=20, null=True, blank=True)
    about_me = models.TextField(null=True, blank=True)
Exemplo n.º 8
0
class Profile(models.Model):
    user = models.ForeignKey(Users,
                             related_name="user",
                             on_delete=models.CASCADE)
    profile_pic = models.CharField(max_length=255, null=True)
    location = LocationField(
        map_attrs={
            "style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72",
            "center": (-96.7969, 32.7763)
        })
    address = AddressAutoHiddenField()
    availability = models.CharField(max_length=50)
    deposit = models.IntegerField(default=0)
    walk_ins = models.BooleanField()
    is_apprentice = models.BooleanField()
    styles = models.ManyToManyField(Styles, related_name="artists_with_styles")
    followers = models.ManyToManyField(Users, related_name="favorite_artists")
    #users who follow artist profile
    #studios_joined = list of studios an artist has worked at.
    #contacts= list of contacts linked to a given profile
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
Exemplo n.º 9
0
class Impress(models.Model):
    """Модель описывающая впечатление"""
    name = models.CharField(max_length=255,
                            null=False,
                            verbose_name="Название воспоминания")
    info = models.TextField(null=True,
                            verbose_name="Инофрмация о воспоминании")
    date = models.DateTimeField(auto_now_add=True,
                                db_index=True,
                                verbose_name='Время')
    profile = models.ForeignKey(Profile,
                                on_delete=models.CASCADE,
                                verbose_name="Автор",
                                blank=True,
                                null=True)
    location = LocationField(map_attrs={
        "id": "unique_id_1",
        "center": [92.87172071992194, 56.00781904796429],
        "marker_color": "blue",
        "readonly ": True
    },
                             verbose_name="Место")
    address = AddressAutoHiddenField(map_id="unique_id_1")
Exemplo n.º 10
0
class Place(models.Model):
    GRIETA = 1
    NORMAL = 2
    MORTAL = 3
    Danger = [
        (GRIETA, 'Grieta'),
        (NORMAL, 'Normal'),
        (MORTAL, 'Mortal'),
    ]

    location = LocationField(
        map_attrs={
            "style": "mapbox://styles/mapbox/streets-v11",
            "center": (-76.51972, 3.44),
            "marker_color": "DodgerBlue"
        })
    created_at = models.DateTimeField(auto_now_add=True)
    address = AddressAutoHiddenField()
    name = models.CharField(max_length=8)
    level = models.IntegerField(choices=Danger)
    users = models.ManyToManyField('Profile',
                                   related_name='places',
                                   blank=True)
Exemplo n.º 11
0
 def test_form_field(self):
     instance = AddressAutoHiddenField()
     self.assertTrue(isinstance(instance.formfield(), FormAddressAutoHiddenField))
Exemplo n.º 12
0
 def test_field(self):
     instance = AddressAutoHiddenField()
     self.assertIsInstance(instance, AddressAutoHiddenField)
     name, path, args, kwargs = instance.deconstruct()
     new_instance = AddressAutoHiddenField(*args, **kwargs)
     self.assertEqual(instance.map_id, new_instance.map_id)
Exemplo n.º 13
0
class Advertise_with_Us(models.Model):
    Payments_Choices = (
        ('Cash', 'Cash'),
        ('Cheque', 'Cheque'),
        ('Credit Card / Debit Card', 'Credit Card / Debit Card'),
        ('NEFT/RTGS', 'NEFT/RTGS'),
        ('UPI', 'UPI'),
    )
    Added_by = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE)
    Business_Name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True, null=True, blank=True)
    Business_Category = models.ForeignKey(Category, on_delete=models.CASCADE)
    Business_Subcategory = models.ManyToManyField(Subcategory)
    Business_Services = models.ManyToManyField(Services)
    Business_Website = models.URLField(null=True, blank=True)
    Business_Facebook = models.URLField(null=True, blank=True)
    Business_Instagram = models.URLField(null=True, blank=True)
    Business_Twitter = models.URLField(null=True, blank=True)
    Business_Linkedin = models.URLField(null=True, blank=True)
    Business_Pinterest = models.URLField(null=True, blank=True)
    Business_Github = models.URLField(null=True, blank=True)
    Business_Email = models.EmailField(null=True, blank=True)
    # Business_Location = models.CharField(max_length=300)
    Business_Location = LocationField(null=True, blank=True)
    Address = AddressAutoHiddenField(null=True, blank=True)
    Business_Address = models.CharField(max_length=300)
    Business_Telephone = models.CharField(
        validators=[RegexValidator("0?[5-9]{1}\d{9}$")],
        max_length=15,
    )
    Business_WhatsApp = models.CharField(null=True, blank=True, max_length=15, validators=[RegexValidator("0?[5-9]{1}\d{9}$")])
    Business_Description = models.TextField()
    Business_Logo = models.ImageField(upload_to=advertise_logo_directory_path, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
    Business_Images = models.ImageField(upload_to=advertise_images_directory_path, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], verbose_name='Business Images',null=True, blank=True)
    Business_Established_Date = models.DateField()
    Added_at = models.DateTimeField(auto_now_add=True)
    tags = TaggableManager(verbose_name='Business Keywords', help_text='Tag your business here')
    view = models.PositiveIntegerField(default=0)
    Mode_Of_Payments = MultiSelectField(choices=Payments_Choices)
    title = models.CharField(max_length=200, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    keywords = models.TextField(null=True, blank=True, help_text='Comma separated keywords here')
    verified = models.BooleanField(default=False)

    def __str__(self):
        return self.Business_Name

    def get_absolute_url(self):
        return reverse("Advertise With Us")

    class Meta:
        verbose_name = "Advertise With Us"
        verbose_name_plural = "Advertise With Us"
        ordering = ('-id',)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.Business_Name)
        super(Advertise_with_Us, self).save(*args,**kwargs)

    def averagereview(self):
        reviews = AdvertiseComment.objects.filter(advertise=self).aggregate(average=Avg('rate'))
        avg = 0
        if reviews['average'] is not None:
            avg = float(reviews["average"])
        return avg

    def countreview(self):
        reviews = AdvertiseComment.objects.filter(advertise=self).aggregate(count=Count('id'))
        cnt = 0
        if reviews["count"] is not None:
            cnt = int(reviews["count"])
        return cnt
 def test_form_field(self):
     instance = AddressAutoHiddenField()
     self.assertEqual(instance.formfield().__class__,
                      FormAddressAutoHiddenField().__class__)
Exemplo n.º 15
0
class Segnalazione(TimeStampedModel):
    STATO = (
        ('INIZIALE', 'INIZIALE'),
        ('EMAIL_FALLITO', 'EMAIL_FALLITO'),
        ('EMAIL_INVIATO', 'EMAIL_INVIATO'),
        ('EMAIL_VALIDATO', 'EMAIL_VALIDATO'),
        ('CREATO_IN_REDMINE', 'CREATO_IN_REDMINE'),
    )
    '''
        stati:
            INIZIALE: appena creata, va inviato l'email; potrebbe essere stato già fatto qualche tentativo di invio
            EMAIL_FALLITO: dopo settings.MAX_EMAIL_ATTEMPTS tentativi falliti di invio
            EMAIL_INVIATO: L'email è stato inviato ma non è ancora arrivata la validazione
            EMAIL_VALIDATO: L'utente ha cliccato sul link di validazione nell'email
            CREATO_IN_REDMINE: Dopo la validazione è stato creato in redmine
            Altri stati dipendenti dal flusso che vogliono implementare in Redmine
            es: ACCETTATO: il ticket in Redmine è stato accettato in quanto sensato
                SCARTATO:  il ticket in Redmine è stato scartato
                COMPLETATO:
    '''
    redmine_id = models.PositiveIntegerField(blank=True,
                                             null=True,
                                             db_index=True)
    nome = models.CharField(max_length=100)
    cognome = models.CharField(max_length=100)
    token_validazione = models.CharField(max_length=100, db_index=True)
    token_lettura = models.CharField(max_length=100,
                                     db_index=True,
                                     blank=True,
                                     default='')
    token_foto = models.CharField(max_length=100,
                                  db_index=True,
                                  blank=True,
                                  default='')
    # token_foto usato come chiave per accedere alla foto dall'esterno
    email = models.EmailField()
    email_tentativo = models.IntegerField(default=0)
    # quanti tentativi sono stati fatti di invio email
    stato = models.CharField(max_length=50, default='INIZIALE', choices=STATO)

    cellulare = models.CharField("Numero di cellulare", max_length=15)
    location = LocationField(
        verbose_name='Posizione ed indirizzo',
        map_attrs={
            "style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72",
            "placeholder": "Seleziona la posizione nella mappa.",
            "center": (10.515822538661212, 43.72580949521296)
        },
        blank=True,
        null=True)
    address = AddressAutoHiddenField(blank=True, null=True)
    titolo = models.CharField(max_length=100)
    testo = models.TextField()
    foto = models.ImageField(upload_to='foto/%Y/%m/%d/', blank=True, null=True)
    categoria = models.ForeignKey(
        Categoria,
        on_delete=models.CASCADE,
        help_text='Seleziona la categoria e poi inserisci gli altri dati.')
    # https://docs.djangoproject.com/en/3.2/releases/3.1/#jsonfield-for-all-supported-database-backends
    extra_data = models.JSONField(blank=True, null=True)

    class Meta:
        verbose_name_plural = 'Segnalazioni'

    def __str__(self):
        return 'Segnalazione del %s, stato %s, inviata da %s %s: "%s"' % (
            self.created, self.stato,
            ('%s %s' % (self.nome, self.cognome)), self.email, self.titolo)

    def save(self,
             force_insert=False,
             force_update=False,
             using=None,
             update_fields=None):
        if not self.id:
            self.token_validazione = token_hex(settings.TOKEN_LENGTH)
            self.token_lettura = token_hex(settings.TOKEN_LENGTH)
            self.token_foto = token_hex(settings.TOKEN_LENGTH)
        super(Segnalazione, self).save(force_insert, force_update, using,
                                       update_fields)

    def invia_email_validazione(self):
        es = EmailSender('validazione')
        try:
            context = {'http_host': settings.HTTP_HOST, 'segnalazione': self}
            self.email_tentativo += 1
            es.send_mail(self.email,
                         'Comune di Calci, segnalazione %s' % self.id, context)
            self.stato = 'EMAIL_INVIATO'
            self.save()
        except Exception as ex:
            if self.email_tentativo > settings.MAX_EMAIL_ATTEMPTS:
                self.stato = 'EMAIL_FALLITO'
                logger_cron.warning(
                    'Superato in massimo numero di tentativi (%s) di invio email per la segnalazione %s'
                    ' all\'indirizzo %s: %s' % (settings.MAX_EMAIL_ATTEMPTS,
                                                self.id, self.email, str(ex)))
            self.save()

    def crea_in_redmine(self):
        try:
            redmine = Redmine(settings.REDMINE_ENDPOINT,
                              key=settings.REDMINE_KEY,
                              version=settings.REDMINE_VERSION)
            redmine_project = redmine.project.get(settings.REDMINE_PROJECT)
            red_issue = redmine.issue.create(
                subject=self.titolo,
                description='%s\n\n%s\n !%s!' %
                (self.testo, ('%s\n\n' % self.tag_mappa), self.foto_url),
                category_id=self.categoria.redmine_id,
                custom_fields=[{
                    'id': 1,
                    'value': self.nome
                }, {
                    'id': 2,
                    'value': self.cognome
                }, {
                    'id':
                    3,
                    'value':
                    'id=%s&t=%s' % (self.id, self.token_foto)
                }, {
                    'id':
                    4,
                    'value': (self.location[0] if self.location else '')
                }, {
                    'id':
                    5,
                    'value': (self.location[1] if self.location else '')
                }, {
                    'id': 6,
                    'value': self.address
                }, {
                    'id': 7,
                    'value': self.cellulare
                }],
                project_id=redmine_project.id)
            self.stato = 'CREATO_IN_REDMINE'
            self.redmine_id = red_issue.id
            self.save()
        except Exception as ex:
            logger_cron.error(
                'Errore creando in redmine la segnalazione %s: %s' %
                (self.id, str(ex)))

    @property
    def tag_mappa(self):
        if self.location:
            return '{{leaflet_map(%s, %s, 17)}}\n{{leaflet_marker(%s, %s, %s)}}' % \
                   (self.location[1], self.location[0], self.location[1], self.location[0], self.titolo)
        return ''

    @property
    def foto_url(self):
        if self.foto:
            return '%s%s?id=%s&t=%s' % (settings.HTTP_HOST, reverse('i'),
                                        self.id, self.token_foto)
        return ''

    @classmethod
    def cron_notifiche_validazione(cls):
        for s in Segnalazione.objects.filter(
                stato='INIZIALE',
                email_tentativo__lt=settings.MAX_EMAIL_ATTEMPTS):
            s.invia_email_validazione()

    @classmethod
    def cron_crea_redmine(cls):
        for s in Segnalazione.objects.filter(stato='EMAIL_VALIDATO'):
            s.crea_in_redmine()