class EventPaths(models.Model): objects = EventsPathManager() path = models.CharField(max_length=2000) registered = models.BooleanField() request = MySQLJSONField(null=True) \ if is_mysql else PostgresJSONField(null=True) response = MySQLJSONField(null=True) \ if is_mysql else PostgresJSONField(null=True)
class JsonEvents(models.Model): objects = JsonEventsManager() def request(self, param=None, default='Undefined'): try: return json.loads(self.request_dict['body']).get(param, default)\ if param else json.loads(self.request_dict['body']) except Exception: return { 'error': 'Could not get request body : {}'.format(self.response_dict) } def response(self, param=None, default='Undefined'): try: return json.loads(self.response_dict.get('body', {})).get('data', {}).get(param, default)\ if param else json.loads(self.response_dict['body']).get('data', {}) except Exception: return { 'error': 'Could not get request body : {}'.format(self.response_dict) } def headers(self, param, default='Undefined'): return self.request_dict.get('headers', {}).get(param, default) if param \ else self.request_dict.get('headers', {}) def path(self): return self.request_dict.get('path', 'Undefined') def code(self): return self.response_dict.get('statusCode', '-1') def string_params(self, param, default='Undefined'): return self.request_dict.get('queryStringParameters', {}).get(param, default) \ if param and self.request_dict.get('queryStringParameters') is not None \ else default timestamp = models.DateTimeField() request_dict = MySQLJSONField() \ if is_mysql else PostgresJSONField() response_dict = MySQLJSONField() \ if is_mysql else PostgresJSONField() inserted_at = models.DateTimeField(default=utc_now) identifier = models.CharField(max_length=100) class Meta: indexes = [models.Index(fields=['timestamp'])]
class SearchQueryTemplate(models.Model): """ Model class to save the input search query by user. """ # Query definition. queryJson = PostgresJSONField(default={"Keywords": []})
class CosinnusConferenceApplication(models.Model): conference = models.ForeignKey(settings.COSINNUS_GROUP_OBJECT_MODEL, verbose_name=_('Confernence Application'), related_name='conference_applications', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_applications', on_delete=models.CASCADE) status = models.PositiveSmallIntegerField(choices=APPLICATION_STATES, default=APPLICATION_SUBMITTED) options = PostgresJSONField(default=list, blank=True, null=True) priorities = PostgresJSONField(_('Priorities'), default=dict, blank=True, null=True) information = models.TextField(_('Motivation for applying'), blank=True) contact_email = models.EmailField(_('Contact E-Mail Address'), blank=True, null=True) contact_phone = PhoneNumberField(('Contact Phone Number'), blank=True, null=True) reason_for_rejection = models.TextField(blank=True) created = models.DateTimeField(verbose_name=_('Created'), editable=False, auto_now_add=True) last_modified = models.DateTimeField(verbose_name=_('Last modified'), editable=False, auto_now=True) objects = CosinnusConferenceApplicationQuerySet.as_manager() class Meta(object): ordering = ('created', ) verbose_name = _('Cosinnus conference application') verbose_name_plural = _('Cosinnus conference applications') @property def first_priorities(self): from cosinnus_event.models import Event # noqa return [ Event.objects.get(id=int(key)) for key, value in self.priorities.items() if value == 1 ] @property def second_priorities(self): from cosinnus_event.models import Event # noqa return [ Event.objects.get(id=int(key)) for key, value in self.priorities.items() if value == 2 ] @property def first_priorities_string(self): return ', '.join(event.title for event in self.first_priorities) @property def second_priorities_string(self): return ', '.join(event.title for event in self.second_priorities) @property def application_status_string(self): for message in APPLICATION_STATES_MESSAGES: if message[0] == self.status: return message[1] def get_icon(self): """ Returns the icon depending on the status of the application """ for icon in APPLICATION_STATES_ICONS: if icon[0] == self.status: return icon[1] @property def email_notification_body(self): """ The description text for a notification email for this application for the application's user. The body text of the notification item that the user receives when their application is accepted/declined/waitlisted. """ reason_markdown = '' if self.status in [APPLICATION_WAITLIST, APPLICATION_DECLINED ] and self.reason_for_rejection: note_string = _('Note from the organizers') reason_markdown = f'**{note_string}:**\n\n{self.reason_for_rejection}' return reason_markdown or self.conference.description_long or self.conference.description or '' @property def group(self): """ Needed for notifications to know the group of this item """ return self.conference def grant_extra_read_permissions(self, user): return self.user == user or check_user_superuser(user) def special_alert_check(self, user): """ Users want alerts for conference they applied to """ return self.user == user def user_email(self): """ Needed for django-admin """ return self.user.email
class ParticipationManagement(models.Model): participants_limit = models.IntegerField(blank=True, null=True) application_start = models.DateTimeField(blank=True, null=True) application_end = models.DateTimeField(blank=True, null=True) application_conditions = models.TextField(blank=True) application_conditions_upload = models.FileField( _("Conditiions for participation"), help_text= _('Shown as a download link near the checkbox to accept the conditions.' ), null=True, blank=True, upload_to=get_conference_conditions_filename, max_length=250) application_options = PostgresJSONField(default=list, blank=True, null=True) conference = models.ForeignKey(settings.COSINNUS_GROUP_OBJECT_MODEL, verbose_name=_('Participation Management'), related_name='participation_management', on_delete=models.CASCADE) information_field_enabled = models.BooleanField( _('Request user information'), default=True) information_field_initial_text = models.TextField( _('Pre-filled content for the information field'), blank=True, null=True) priority_choice_enabled = models.BooleanField( _('Priority choice enabled'), default=settings.COSINNUS_CONFERENCE_PRIORITY_CHOICE_DEFAULT) @property def applications_are_active(self): if self.application_start and self.application_end: now = timezone.now() return now >= self.application_start and now <= self.application_end return True @property def application_time_string(self): if self.applications_are_active: return _('Participation applications are open.') else: now = timezone.now() if now < self.application_start: return _('Participation application has not started yet.') elif now > self.application_end: return _('Participation application is over.') @property def has_conditions(self): return bool(self.application_conditions_upload or self.application_conditions) @property def from_date(self): return self.application_start @property def to_date(self): return self.application_end
class Person(models.Model): gender = models.CharField(max_length=1, choices=GENDER_CHOICES) # Jards Macalé is an amazing brazilian musician! =] enjoy_jards_macale = models.BooleanField(default=True) like_metal_music = models.BooleanField(default=False) name = models.CharField(max_length=30) nickname = models.SlugField(max_length=36) age = models.IntegerField() bio = models.TextField() birthday = models.DateField() birth_time = models.TimeField() appointment = models.DateTimeField() blog = models.URLField() occupation = models.CharField(max_length=10, choices=OCCUPATION_CHOICES) uuid = models.UUIDField(primary_key=False) name_hash = models.BinaryField(max_length=16) days_since_last_login = models.BigIntegerField() duration_of_sleep = models.DurationField() email = models.EmailField() id_document = models.CharField(unique=True, max_length=10) try: from django.db.models import JSONField data = JSONField() except ImportError: # Skip JSONField-related fields pass try: from django.contrib.postgres.fields import ArrayField, HStoreField from django.contrib.postgres.fields import JSONField as PostgresJSONField from django.contrib.postgres.fields.citext import ( CICharField, CIEmailField, CITextField, ) from django.contrib.postgres.fields.ranges import ( BigIntegerRangeField, DateRangeField, DateTimeRangeField, IntegerRangeField, ) if settings.USING_POSTGRES: acquaintances = ArrayField(models.IntegerField()) postgres_data = PostgresJSONField() hstore_data = HStoreField() ci_char = CICharField(max_length=30) ci_email = CIEmailField() ci_text = CITextField() int_range = IntegerRangeField() bigint_range = BigIntegerRangeField() date_range = DateRangeField() datetime_range = DateTimeRangeField() except ImportError: # Skip PostgreSQL-related fields pass try: from django.contrib.postgres.fields.ranges import FloatRangeField if settings.USING_POSTGRES: float_range = FloatRangeField() except ImportError: # Django version greater or equal than 3.1 pass try: from django.contrib.postgres.fields.ranges import DecimalRangeField if settings.USING_POSTGRES: decimal_range = DecimalRangeField() except ImportError: # Django version lower than 2.2 pass if BAKER_GIS: geom = models.GeometryField() point = models.PointField() line_string = models.LineStringField() polygon = models.PolygonField() multi_point = models.MultiPointField() multi_line_string = models.MultiLineStringField() multi_polygon = models.MultiPolygonField() geom_collection = models.GeometryCollectionField()
class BaseUserProfile(IndexingUtilsMixin, FacebookIntegrationUserProfileMixin, LikeableObjectMixin, CosinnusManagedTagAssignmentModelMixin, models.Model): """ This is a base user profile used within cosinnus. To use it, create your own model inheriting from this model. .. code-block:: python from django.db import models from cosinnus.models.profile import BaseUserProfile class MyUserProfile(BaseUserProfile): myfield = models.CharField('myfield', max_length=10) Additionally set the settings variable ``COSINNUS_USER_PROFILE_MODEL`` to the dotted model path (myapp.MyUserProfile). This works the same way as Django's custom user model. To get a user's profile e.g in a view use the ``get_for_user()`` method on the manager: .. code-block:: python from myapp.models import MyUserProfile def myview(request): user = request.user profile = MyUserProfile.objects.get_for_user(user) """ # if this or any extending profile models define additional username fields, # such as middle name, list the field names here ADDITIONAL_USERNAME_FIELDS = [] user = models.OneToOneField(settings.AUTH_USER_MODEL, editable=False, related_name='cosinnus_profile', on_delete=models.CASCADE) avatar = models.ImageField(_("Avatar"), null=True, blank=True, upload_to=get_avatar_filename) description = models.TextField(verbose_name=_('Description'), blank=True, null=True) media_tag = models.OneToOneField(settings.COSINNUS_TAG_OBJECT_MODEL, blank=True, null=True, editable=False, on_delete=models.SET_NULL) website = models.URLField(_('Website'), max_length=100, blank=True, null=True) language = models.CharField(_('Language'), max_length=2, choices=settings.LANGUAGES, default='de') # display and inclusion in forms is dependent on setting `COSINNUS_USER_SHOW_MAY_BE_CONTACTED_FIELD` may_be_contacted = models.BooleanField(_('May be contacted'), default=False) # UI and other preferences and extra settings for the user account settings = JSONField(default={}) extra_fields = JSONField( default={}, blank=True, help_text= 'NO LONGER USED! Extra userprofile fields for each portal, as defined in `settings.COSINNUS_USERPROFILE_EXTRA_FIELDS`' ) dynamic_fields = PostgresJSONField( default=dict, blank=True, verbose_name=_('Dynamic extra fields'), help_text= 'Extra userprofile fields for each portal, as defined in `settings.COSINNUS_USERPROFILE_EXTRA_FIELDS`', encoder=DjangoJSONEncoder) managed_tag_assignments = GenericRelation( 'cosinnus.CosinnusManagedTagAssignment') objects = BaseUserProfileManager() SKIP_FIELDS = ['id', 'user', 'user_id', 'media_tag', 'media_tag_id', 'settings', 'managed_tag_assignments', 'likes']\ + getattr(cosinnus_settings, 'COSINNUS_USER_PROFILE_ADDITIONAL_FORM_SKIP_FIELDS', []) # this indicates that objects of this model are in some way always visible by registered users # on the platform, no matter their visibility settings, and thus subject to moderation cosinnus_always_visible_by_users_moderator_flag = True _settings = None class Meta(object): abstract = True def __init__(self, *args, **kwargs): super(BaseUserProfile, self).__init__(*args, **kwargs) self._settings = copy.deepcopy(self.settings) self._dynamic_fields = copy.deepcopy(self.dynamic_fields) def __str__(self): return six.text_type(self.user) def get_icon(self): """ Returns the font-awesome icon specific to this object type """ return 'fa-user' def get_full_name(self): return self.user.get_full_name() def get_extended_full_name(self): """ Stub extended username, including possible titles, middle names, etc """ return self.get_full_name() def save(self, *args, **kwargs): created = bool(self.pk is None) # sanity check for missing media_tag: if not self.media_tag: from cosinnus.models.tagged import get_tag_object_model media_tag = get_tag_object_model()._default_manager.create() self.media_tag = media_tag try: existing = self._meta.model._default_manager.get(user=self.user) # workaround for http://goo.gl/4I8Ok self.id = existing.id # force update instead of insert except ObjectDoesNotExist: pass super(BaseUserProfile, self).save(*args, **kwargs) if created: # send creation signal signals.userprofile_created.send(sender=self, profile=self) # send a copy of the ToS to the User via email? if settings.COSINNUS_SEND_TOS_AFTER_USER_REGISTRATION and self.user and self.user.email: if self.settings.get( 'tos_accepted', False) and not self._settings.get('tos_accepted', False): tos_content = mark_safe( strip_tags( render_to_string('nutzungsbedingungen_content.html'))) data = { 'user': self.user, 'site_name': _(settings.COSINNUS_BASE_PAGE_TITLE_TRANS), 'domain_url': CosinnusPortal.get_current().get_domain(), 'tos_content': tos_content, } subj_user = '******' % (_('Terms of Service'), data['site_name']) send_mail_or_fail_threaded( get_newly_registered_user_email(self.user), subj_user, 'cosinnus/mail/user_terms_of_services.html', data) self._settings = copy.deepcopy(self.settings) self._dynamic_fields = copy.deepcopy(self.dynamic_fields) def get_absolute_url(self): return group_aware_reverse('cosinnus:profile-detail', kwargs={'username': self.user.username}) @classmethod def get_optional_fieldnames(cls): """ Iterates over all fields defined in the user profile and returns a list of field names. The list will only contain those fields not listed in ``SKIP_FIELDS``. """ return list( set([f.name for f in cls._meta.get_fields()]) - set(cls.SKIP_FIELDS)) def get_optional_fields(self): """ Iterates over all fields defined in the user profile and returns a list of dicts with the keys ``name`` and ``value``. The list will only contain those fields not listed in ``SKIP_FIELDS``. """ all_fields = [f.name for f in self._meta.get_fields()] optional_fields = [] for name in all_fields: if name in self.SKIP_FIELDS: continue value = getattr(self, name, None) if value: field = self._meta.get_field(name) optional_fields.append({ 'name': field.verbose_name, 'value': value, }) return optional_fields @property def cosinnus_groups(self): """ Returns all groups this user is a member or admin of """ return get_cosinnus_group_model().objects.get_for_user(self.user) @property def cosinnus_groups_pks(self): """ Returns all group ids this user is a member or admin of """ return get_cosinnus_group_model().objects.get_for_user_pks(self.user) @property def cosinnus_projects(self): """ Returns all projects this user is a member or admin of """ from cosinnus.models.group_extra import CosinnusProject return CosinnusProject.objects.get_for_user(self.user) @property def cosinnus_societies(self): """ Returns all societies this user is a member or admin of """ from cosinnus.models.group_extra import CosinnusSociety return CosinnusSociety.objects.get_for_user(self.user) def get_deactivated_groups(self): """ Returns a QS of all (untyped) deactivated groups for this user """ return get_cosinnus_group_model().objects.get_deactivated_for_user( self.user) @property def has_deactivated_groups(self): """ Returns True if the user has any deactivated groups they can re-activate """ return self.get_deactivated_groups().count() > 0 @property def avatar_url(self): return self.avatar.url if self.avatar else None def get_avatar_thumbnail(self, size=(80, 80)): return image_thumbnail(self.avatar, size) def get_avatar_thumbnail_url(self, size=(80, 80)): return image_thumbnail_url(self.avatar, size) or static('images/jane-doe-small.png') def get_image_field_for_icon(self): return self.avatar or static('images/jane-doe.png') def media_tag_object(self): key = '_media_tag_cache' if not hasattr(self, key): setattr(self, key, self.media_tag) return getattr(self, key) def add_redirect_on_next_page(self, resolved_url, message=None, priority=False): """ Adds a redirect-page to the user's settings redirect list. A middleware enforces that the user will be redirected to the first URL in the list on the next page hit. @param message: (optional) Can be a string, that will be displayed as success-message at redirect time. i18n u_gettext will be applied *later, at redirect time* to this string! @param priority: if set to `True`, will insert the redirect as first URL, so it will be the next one in queue """ redirects = self.settings.get(PROFILE_SETTING_REDIRECT_NEXT_VISIT, []) if not resolved_url in redirects: if priority: redirects.insert(0, (resolved_url, message)) else: redirects.append((resolved_url, message)) self.settings[PROFILE_SETTING_REDIRECT_NEXT_VISIT] = redirects self.save(update_fields=['settings']) def pop_next_redirect(self): """ Tries to remove the first redirect URL in the user's setting's redirect list, and return it. @return: A tuple (string resolved URL, message), or False if none existed. """ redirects = self.settings.get(PROFILE_SETTING_REDIRECT_NEXT_VISIT, []) if not redirects: return False next_redirect = redirects.pop(0) if next_redirect: self.settings[PROFILE_SETTING_REDIRECT_NEXT_VISIT] = redirects self.save(update_fields=['settings']) return next_redirect return False def get_new_rocket_username(self): """ Builds rocket username based upon first and last name (or ID if not given) """ user = self.user if user.first_name or user.last_name: username = '******'.join( filter(None, [slugify(user.first_name), slugify(user.last_name)])) else: username = str(user.id) def is_username_free(username): value = f'"{PROFILE_SETTING_ROCKET_CHAT_USERNAME}":"{username}"' queryset = get_user_profile_model().objects.filter( settings__contains=value) return queryset.count() == 0 i = 1 while True: if i == 1 and is_username_free(username): break else: new_username = f'{username}{i}' if is_username_free(new_username): username = new_username break i += 1 if i > 1000: raise Exception('Name is very popular') return username @property def rocket_username(self): """ Retrieves or creates rocket username """ username = self.settings.get(PROFILE_SETTING_ROCKET_CHAT_USERNAME, '') if not username: username = self.get_new_rocket_username() self.settings[PROFILE_SETTING_ROCKET_CHAT_USERNAME] = username get_user_profile_model().objects.filter(id=self.id).update( settings=self.settings) return username @rocket_username.setter def rocket_username(self, username): """ Sets new username for Rocket.Chat """ self.settings[PROFILE_SETTING_ROCKET_CHAT_USERNAME] = username @property def workshop_user_name(self): return self.settings.get(PROFILE_SETTING_WORKSHOP_PARTICIPANT_NAME) @property def readable_workshop_user_name(self): settings_name = self.settings.get( PROFILE_SETTING_WORKSHOP_PARTICIPANT_NAME) return settings_name.split('__')[-1] @property def is_workshop_participant(self): return self.settings.get(PROFILE_SETTING_WORKSHOP_PARTICIPANT, False) @property def get_last_login_token_sent(self): return self.settings.get(PROFILE_SETTING_LOGIN_TOKEN_SENT, None)
class PostgresParallelModel(models.Model): library_json = JSONField() postgres_json = PostgresJSONField() class Meta: app_label = 'jsonfield'