Esempio n. 1
0
 def save(self, *args, **kwargs):
     if self._state.adding:
         self.created_by = get_current_user().username
     else:
         self.modified = datetime.now()
         self.modified_by = get_current_user().username
     super(CommonStruct, self).save(*args, **kwargs)
Esempio n. 2
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['negative'].queryset = Negative.objects.filter(
         owner=get_current_user())
     self.fields['print'].queryset = Print.objects.filter(
         owner=get_current_user())
     self.helper = FormHelper(self)
     self.helper.layout = Layout('negative', 'print', 'filename', 'date',
                                 FormActionButtons)
Esempio n. 3
0
def students_list():
    user = get_current_user()
    if user.is_superuser or user.is_superadmin or user.is_principal:
        return StudentsMarks.objects.all()
    elif user.is_hod:
        department = Department.objects.get(assign_hod_id=user.id)
        user_department = department.id
        return StudentsMarks.objects.filter(department=user_department)
    elif User.is_staff:
        return StudentsMarks.objects.filter(created_by=get_current_user())
    elif user.is_student:
        return StudentsMarks.objects.filter(student_name=user)
Esempio n. 4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['negative'].queryset = Negative.objects.filter(
            owner=get_current_user())
        self.fields['print'].queryset = Print.objects.filter(
            owner=get_current_user())
        self.fields['recipient'].queryset = Person.objects.filter(
            owner=get_current_user())

        self.helper = FormHelper(self)
        self.helper.layout = Layout('negative', AppendedText('width', '"'),
                                    AppendedText('height',
                                                 '"'), 'added', 'printed',
                                    'print', 'recipient', FormActionButtons)
Esempio n. 5
0
def update_workflow(sender, instance, created, **kwargs):
    if instance.has_inventory:
        if created:
            wf_object = Workflow.objects.create(source=instance, last_modified=instance.modification_timestamp)
            Work_log.objects.create(source=wf_object, event='Source created', timestamp=wf_object.last_modified)
        else:
            wf_object = Workflow.objects.get_or_create(source=instance, defaults={
                'last_modified': timezone.now(),
                'last_user': get_current_user()
            })
            if type(wf_object) is tuple:
                wf_object[0].last_modified = timezone.now()
                wf_object[0].last_user = get_current_user()
                wf_object[0].save()
Esempio n. 6
0
    def test__local_thread_var_is_set_to_logged_in_user(self):
        _set_current_user(None)
        self.assertIsNone(get_current_user())

        self.login_and_go_to_homepage(username="******", password="******")
        self.assertEqual(self.user1, get_current_user())
        self.client.logout()

        self.login_and_go_to_homepage(username="******", password="******")
        self.assertEqual(self.user2, get_current_user())
        self.client.logout()

        self.client.get("/")
        current_user = get_current_user()
        assert_that(current_user, instance_of(AnonymousUser))
Esempio n. 7
0
 def save(self,
          force_insert=False,
          force_update=False,
          using=None,
          update_fields=None):
     if not self.created_by or not self.created_at:
         self.created_by = get_current_user()
         self.created_at = timezone.now()
     else:
         self.update_by = get_current_user()
         self.update_at = timezone.now()
     super(BaseModel, self).save(force_insert=False,
                                 force_update=False,
                                 using=None,
                                 update_fields=None)
Esempio n. 8
0
 def save(self,
          force_insert=False,
          force_update=False,
          using=None,
          update_fields=None):
     if not self.criado_por or not self.criado_em:
         self.criado_por = get_current_user()
         self.criado_em = timezone.now()
     else:
         self.modificado_por = get_current_user()
         self.modificado_em = timezone.now()
     super(BaseModel, self).save(force_insert=False,
                                 force_update=False,
                                 using=None,
                                 update_fields=None)
Esempio n. 9
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['bulk_film'].queryset = BulkFilm.objects.filter(
         owner=get_current_user(), finished=False)
     self.helper = FormHelper(self)
     self.helper.layout = Layout(
         Fieldset(
             'Add a new film to your collection',
             'filmstock',
             'format',
             'frames',
             Div(
                 TabHolder(
                     Tab(
                         'Single film',
                         HTML(
                             "<p>Choose Single Film for regular roll or sheet films</p>"
                         ),
                         'film_batch',
                         'expiry_date',
                         'purchase_date',
                         'price',
                     ),
                     Tab(
                         'Bulk film',
                         HTML(
                             "<p>Choose Bulk Film for film that has been cut from a bulk roll</p>"
                         ),
                         'bulk_film',
                         'bulk_film_loaded',
                     ),
                 ),
                 css_class="border",
             ),
         ), Hidden('status', 'Available'), FormActionButtons)
Esempio n. 10
0
 def __init__(self, *args, **kwargs):
     super(SubmitExchangeRequestReplacingOfficerForm,
           self).__init__(*args, **kwargs)
     #initial_arguments = kwargs.get('initial', None)
     user_as_simpleLazyObject = get_current_user()
     user = Account.objects.get(pk=user_as_simpleLazyObject.id)
     user_roster_side = user.roster_side
     todays_date = datetime.date.today()
     #self.fields exchange officer, date, shift, notes, replacing officer?? <all disabled>
     replacers_roster = Roster.objects.filter(
         roster_officer_id=user).filter(roster_due_on=True).filter(
             roster_shift_date__gt=todays_date)
     replacers_roster_choices = [('', 'select date')] + [
         (id.roster_shift_date.strftime("%Y-%m-%d"),
          id.roster_shift_date.strftime("%Y-%m-%d"))
         for id in replacers_roster
     ]
     self.fields['replacing_req_date'] = forms.ChoiceField(
         label="Please select the date you wish to have replaced:",
         widget=forms.Select,
         choices=replacers_roster_choices)
     self.fields['replacing_req_officer_notes'] = forms.CharField(
         label="Enter a message to the Exchanging Officer if you wish:",
         required=False,
         widget=forms.Textarea())
     self.fields['ro_proceed_with_swap'] = forms.BooleanField(
         label="Please confirm that you wish to take part in this exchange:",
         required=False,
         widget=forms.CheckboxInput)
Esempio n. 11
0
def update_source_modification(sender, instance, created, **kwargs):
    if instance.source_pages.all().exists():
        source_id = instance.source_pages.all().first().source.id
        source = Source.objects.get(pk=source_id)
        source.modification_timestamp = timezone.now()
        source.modification_user = get_current_user()
        source.save()
Esempio n. 12
0
 def user(self):
     with connection.cursor() as cursor:
         cursor.execute(
             "select id, username from users where users.id = %s ",
             [get_current_user().id])
         rev = dictfetchall(cursor)
     return rev
Esempio n. 13
0
class BaseModel(models.Model):
    created_at = models.DateTimeField(blank=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
                                   on_delete=models.DO_NOTHING,
                                   related_name='%(class)s_created_by',
                                   blank=True,
                                   null=True,
                                   default=get_current_user())
    updated_at = models.DateTimeField(blank=True, null=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,
                                   on_delete=models.DO_NOTHING,
                                   related_name='%(class)s_update_by',
                                   blank=True,
                                   null=True)

    class Meta:
        abstract = True

    def save(self,
             force_insert=False,
             force_update=False,
             using=None,
             update_fields=None):
        if not self.created_by or not self.created_at:
            self.created_by = get_current_user()
            self.created_at = timezone.now()
        else:
            self.update_by = get_current_user()
            self.update_at = timezone.now()
        super(BaseModel, self).save(force_insert=False,
                                    force_update=False,
                                    using=None,
                                    update_fields=None)
Esempio n. 14
0
    def __init__(self, *args, **kwargs):
        super(SubmitExchangeRequestExchangingOfficerForm,
              self).__init__(*args, **kwargs)
        user_as_simpleLazyObject = get_current_user()
        user = Account.objects.get(pk=user_as_simpleLazyObject.id)
        user_roster_side = user.roster_side
        todays_date = datetime.date.today()
        exchangers_roster = Roster.objects.filter(
            roster_officer_id=user).filter(roster_due_on=True).filter(
                roster_shift_date__gt=todays_date)
        exchangers_roster_choices = [('', 'select date')] + [
            (id.roster_shift_date.strftime("%Y-%m-%d"),
             id.roster_shift_date.strftime("%Y-%m-%d"))
            for id in exchangers_roster
        ]
        self.fields['exchange_req_date'] = forms.ChoiceField(
            label="Please select the date you wish to exchange:",
            widget=forms.Select,
            choices=exchangers_roster_choices)
        if user_roster_side == "A":
            self.fields['replacing_req_officer'] = forms.ModelChoiceField(
                label="Please select the person you are exchanging with:",
                widget=forms.Select,
                queryset=Account.objects.filter(roster_side="B"))
        else:
            self.fields['replacing_req_officer'] = forms.ModelChoiceField(
                label="Please select the person you are exchanging with:",
                widget=forms.Select,
                queryset=Account.objects.filter(roster_side="A"))

        self.fields['exchanging_req_officer_notes'] = forms.CharField(
            label="Enter a message to the Replacing Officer if you wish:",
            required=False,
            widget=forms.Textarea())
Esempio n. 15
0
 def save(self,
          force_insert=False,
          force_update=False,
          using=None,
          update_fields=None):
     self.modified_by = get_current_user()
     super().save(force_insert, force_update, using, update_fields)
Esempio n. 16
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['negative'].queryset = Negative.objects.filter(
         owner=get_current_user())
     self.fields['enlarger'].queryset = Enlarger.objects.filter(
         owner=get_current_user())
     self.fields['lens'].queryset = Lens.objects.filter(
         owner=get_current_user())
     self.fields['archive'].queryset = Archive.objects.filter(
         owner=get_current_user(), type='Print', sealed=False)
     self.fields['printer'].queryset = Person.objects.filter(
         owner=get_current_user())
     self.helper = FormHelper(self)
     self.helper.layout = Layout(
         Fieldset(
             'Summary',
             'negative',
             'date',
             'paper_stock',
             AppendedText('width', '"'),
             AppendedText('height', '"'),
             'fine',
         ),
         Fieldset(
             'Exposure',
             'enlarger',
             'lens',
             PrependedText('aperture', 'f/'),
             'exposure_time',
             'filtration_grade',
         ),
         Fieldset(
             'Development',
             'developer',
             'development_time',
             'toner',
             'notes',
             'printer',
         ),
         Fieldset(
             'Ownership',
             'own',
             'location',
             'sold_price',
             'archive',
         ), FormActionButtons)
 def check_enroll(self):
     try:
         registered = AssignCourses.objects.get(user=get_current_user(),
                                                post=self)
         if registered:
             return True
     except:
         return False
Esempio n. 18
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['camera'].queryset = Camera.objects.filter(
         owner=get_current_user())
     self.fields['bulk_film'].queryset = BulkFilm.objects.filter(
         owner=get_current_user())
     self.fields['processed_by'].queryset = Person.objects.filter(
         owner=get_current_user())
     self.fields['archive'].queryset = Archive.objects.filter(
         owner=get_current_user())
     self.fields['bulk_film'].queryset = BulkFilm.objects.filter(
         owner=get_current_user(), finished=False)
     self.helper = FormHelper(self)
     self.helper.layout = Layout(
         Fieldset(
             'Summary',
             'title',
             'status',
         ),
         Fieldset('Filmstock', 'filmstock', 'format', 'bulk_film',
                  'bulk_film_loaded', 'film_batch', 'expiry_date'),
         Fieldset(
             'Exposure',
             'camera',
             'date_loaded',
             'frames',
             'exposed_at',
         ),
         Fieldset(
             'Development',
             'developer',
             'date_processed',
             'developer_previous_uses',
             'development_time',
             AppendedText('development_temperature', '&deg;C'),
             PrependedText('development_compensation', 'N'),
             'development_notes',
             'processed_by',
         ), Fieldset(
             'Archive',
             'archive',
         ), Fieldset(
             'Ownership',
             'purchase_date',
             'price',
         ), FormActionButtons)
Esempio n. 19
0
def save(self,
         force_insert=False,
         force_update=False,
         using=None,
         update_fields=None):
    """"Overrides Group save method."""
    self.modified_by = get_current_user()
    super(Group, self).save(force_insert, force_update, using, update_fields)
Esempio n. 20
0
 def _decorator(self, *args, **kwargs):
     user_permission = 'poll.' + permission[0]
     user = get_current_user()
     mn = user.get_group_permissions()
     if user_permission in mn:
         return drf_custom_method(self, *args, **kwargs)
     else:
         raise PermissionDenied()
Esempio n. 21
0
 def user_status(self):
     u = get_current_user().id
     with connection.cursor() as cursor:
         cursor.execute(
             "SELECT status FROM books_user where books_user.book = %s and books_user.user = %s",
             [self.id, u])
         stat = cursor.fetchone()
     return stat
Esempio n. 22
0
 def user_id(self):
     u = get_current_user().id
     with connection.cursor() as cursor:
         cursor.execute(
             "select user from Ratings where ratings.book = %s and ratings.user = %s "
             "and value IS NOT NULL", [self.id, u])
         user_id = cursor.fetchone()
     return user_id
Esempio n. 23
0
 def user_rating(self):
     u = get_current_user().id
     with connection.cursor() as cursor:
         cursor.execute(
             "select avg(value) from Ratings where ratings.book = %s and ratings.user = %s",
             [self.id, u])
         rate = cursor.fetchone()
     return rate
Esempio n. 24
0
 def __init__(self, *args, **kwargs):
     super(UpdateUserConfigForm, self ).__init__(*args, **kwargs)
     self.fields['consumer_key'].widget.attrs['readonly'] = uc.objects.filter(user = get_current_user()).first().is_search
     self.fields['consumer_secret'].widget.attrs['readonly'] = uc.objects.filter(user = get_current_user()).first().is_search
     self.fields['access_token'].widget.attrs['readonly'] = uc.objects.filter(user = get_current_user()).first().is_search
     self.fields['access_token_secret'].widget.attrs['readonly'] = uc.objects.filter(user = get_current_user()).first().is_search
     self.fields['filter_key'].widget.attrs['readonly'] = uc.objects.filter(user = get_current_user()).first().is_search
     self.fields['is_search'].widget.attrs['readonly'] = uc.objects.filter(user = get_current_user()).first().is_search
Esempio n. 25
0
def scrapy_log_saved(sender, instance, created, **kwargs):
    def __runtasks(instance, log):

        command = ''
        if instance.sites_new is None or not instance.sites_new.strip():
            command = '{venv} && cd {dir} && SCRAPYER_ENV={env} scrapy crawl {spider_name} -a recreate={recreate} -a start_date={start_date} -a end_date={end_date} -t csv --loglevel=INFO --logfile=/var/apps/a/data-scrapyer/shared/log/{logfile}.log'.format(
                env=instance.enviroment,
                dir=instance.project_dir,
                spider_name=instance.spider_name,
                recreate=instance.recreate,
                start_date=instance.start.strftime('%Y-%m-%d'),
                end_date=instance.end.strftime('%Y-%m-%d'),
                venv=instance.virtualenv,
                logfile=instance.spider_name + instance.start.strftime('%Y%m'))
        else:
            command = '{venv} && cd {dir} && SCRAPYER_ENV={env} scrapy crawl {spider_name} -a recreate={recreate} -a sites_new={sites_new} -a start_date={start_date} -a end_date={end_date} -t csv --loglevel=INFO --logfile=/var/apps/a/data-scrapyer/shared/log/{logfile}.log '.format(
                env=instance.enviroment,
                dir=instance.project_dir,
                spider_name=instance.spider_name,
                sites_new=instance.sites_new,
                recreate=instance.recreate,
                start_date=instance.start.strftime('%Y-%m-%d'),
                end_date=instance.end.strftime('%Y-%m-%d'),
                venv=instance.virtualenv,
                logfile=instance.spider_name + instance.start.strftime('%Y%m'))

        data = subprocess.run(command,
                              shell=True,
                              check=False,
                              stderr=PIPE,
                              stdout=PIPE,
                              executable='/bin/bash')

        if data.returncode == 0:
            log.success = True
            log.running = False
            log.traceback = data.stderr.splitlines(
            )[-10:] + data.stdout.splitlines()[-10:]
        else:
            log.success = False
            log.running = False
            log.error_message = data.stderr.splitlines()[-10:]
            log.traceback = data.stdout.splitlines()[-10:]
        log.save()

    if instance.run_script:
        # __runtasks(instance)
        log = ScrapyLog(start=timezone.now(),
                        script=instance,
                        running=True,
                        scrapylog_name=instance.spider_name + "_" +
                        str(instance.start.strftime('%Y%m')) + "_" +
                        str(timezone.now().strftime('%Y%m')),
                        created_by=get_current_user().username)
        log.save()

        t = Thread(target=__runtasks, args=(instance, log), daemon=True)
        t.start()
Esempio n. 26
0
 def save(self, *args, **kwargs):
     req_user = get_current_user()
     if self.pk is None:
         self.created_at = datetime.datetime.now()
         self.created_by = req_user
     else:
         self.updated_at = datetime.datetime.now()
         self.updated_by = req_user
     super(CustomModel, self).save(*args, **kwargs)
Esempio n. 27
0
 def followers(self):
     with connection.cursor() as cursor:
         cursor.execute(
             "select users.username, followers.created_at, avg(value) as avg from users, followers, "
             "ratings where followers.follower_id = %s and users.id = followers.following_id and "
             "ratings.user = users.id group by users.id",
             [get_current_user().id])
         rev = dictfetchall(cursor)
     return rev
Esempio n. 28
0
 def get_assignment_user(self):
     owner_item = None
     if self.assignment_type == 1:
         print(get_current_user())
         assignment_user, n = AssignmentUser.objects.get_or_create(assignment=self, owner=get_current_user())
     elif self.assignment_type == 2:
         csu = get_object_or_404(CourseScheduleUser, course_schedule=self.course_schedule, user = get_current_user())
         assignment_user, n = AssignmentUser.objects.get_or_create(assignment=self, team_owner=csu.team)
     return assignment_user
Esempio n. 29
0
def theme_next():
    if get_current_authenticated_user():
        if EdcsTheme.objects.filter(
                user_id=get_current_user().id).first().theme == 'light':
            theme = 'dark'
        else:
            theme = 'light'
    else:
        theme = settings.EDC_THEME
    return theme
Esempio n. 30
0
def theme_name():
    if get_current_authenticated_user():
        if EdcsTheme.objects.filter(
                user_id=get_current_user().id).first().theme == 'dark':
            theme = 'Light Mode'
        else:
            theme = 'Dark Mode'
    else:
        theme = settings.EDC_THEME_MODE
    return theme