コード例 #1
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
    def __init__(self, *args, **kwargs):
        super(JobForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            #self.fields['pricing'].initial = JobPricing.objects.filter(duration=self.instance.requested_duration)[0]
            if is_admin(self.user):
                self.fields['status_detail'].choices = STATUS_DETAIL_CHOICES
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0
            
        self.fields['pricing'].choices = pricing_choices(self.user)

        if 'payment_method' in self.fields:
            self.fields['payment_method'].widget = forms.RadioSelect(choices=get_payment_method_choices(self.user))
        
        # adjust fields depending on user status
        fields_to_pop = []
        if not self.user.is_authenticated():
            fields_to_pop += [
                'entity',
                'allow_anonymous_view',
                'user_perms',
                'group_perms',
                'member_perms',
                'post_dt',
                'activation_dt',
                'expiration_dt',
                'syndicate',
                'status',
                'status_detail'
            ]
        else:
            fields_to_pop += [
               'captcha'
            ]

        if not is_admin(self.user):
            fields_to_pop += [
                'slug',
                'entity',
                'allow_anonymous_view',
                'user_perms',
                'member_perms',
                'group_perms',
                'post_dt',
                'activation_dt',
                'expiration_dt',
                'syndicate',
                'status',
                'status_detail'
            ]

        if not is_developer(self.user):
            fields_to_pop += [
               'status'
            ]

        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)
コード例 #2
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
    def __init__(self, *args, **kwargs):
        if 'user_this' in kwargs:
            self.user_this = kwargs.pop('user_this', None)
        else:
            self.user_this = None
            
        if 'user_current' in kwargs:
            self.user_current = kwargs.pop('user_current', None)
        else:
            self.user_current = None            

        if 'required_fields_list' in kwargs:
            self.required_fields_list = kwargs.pop('required_fields_list', None)
        else:
            self.required_fields_list = None      
                        
        super(ProfileForm, self).__init__(*args, **kwargs)
        
        if self.user_this:
            self.fields['first_name'].initial = self.user_this.first_name
            self.fields['last_name'].initial = self.user_this.last_name
            self.fields['username'].initial = self.user_this.username
            if self.user_this.is_superuser and self.user_this.is_staff:
                self.fields['security_level'].initial = "developer"
            elif self.user_this.is_staff:
                self.fields['security_level'].initial = "admin"
            else:
                self.fields['security_level'].initial = "user"
            if self.user_this.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0
                
            del self.fields['password1']
            del self.fields['password2']
            
            if not is_admin(self.user_current):
                del self.fields['admin_notes']
                del self.fields['security_level']
                del self.fields['status']
                del self.fields['status_detail']
        
        if is_admin(self.user_current) and not is_developer(self.user_current):
            self.fields['security_level'].choices=(('user','User'), ('admin','Admin'),)

        if not is_admin(self.user_current):
            if 'status' in self.fields: self.fields.pop('status')
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        # we make first_name, last_name, email, username and password as required field regardless
        # the rest of fields will be decided by the setting - UsersRequiredFields
        if self.required_fields_list:
            for field in self.required_fields_list:
                for myfield in self.fields:
                    if field == self.fields[myfield].label:
                        self.fields[myfield].required = True
                        continue
コード例 #3
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def details(request, slug=None, cv=None):
    """Staff plugin details view"""
    staff = get_object_or_404(Staff, slug=slug)

    # non-admin can not view the non-active content
    # status=0 has been taken care of in the has_perm function
    if (staff.status_detail).lower() <> 'active' and (not is_admin(request.user)):
        raise Http403

    if cv:
        template_name="staff/cv.html"
    else:
        template_name="staff/view.html"

    if has_view_perm(request.user, 'staff.view_staff', staff):
        log_defaults = {
            'event_id' : 1080500,
            'event_data': '%s (%d) viewed by %s' % (staff._meta.object_name, staff.pk, request.user),
            'description': '%s viewed' % staff._meta.object_name,
            'user': request.user,
            'request': request,
            'instance': staff,
        }
        EventLog.objects.log(**log_defaults)

        return render_to_response(template_name, {'staff': staff},
            context_instance=RequestContext(request))
    else:
        raise Http403
コード例 #4
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def details(request, slug=None):
    if not slug: return HttpResponseRedirect(reverse('speakers'))
    speaker = get_object_or_404(Speaker, slug=slug)

    # non-admin can not view the non-active content
    # status=0 has been taken care of in the has_perm function
    if (speaker.status_detail).lower() != 'active' and (not is_admin(request.user)):
        raise Http403

    template_name="speakers/view.html"
    
    log_defaults = {
        'event_id' : 1070500,
        'event_data': '%s (%d) viewed by %s' % (speaker._meta.object_name, speaker.pk, request.user),
        'description': '%s viewed' % speaker._meta.object_name,
        'user': request.user,
        'request': request,
        'instance': speaker,
    }
    EventLog.objects.log(**log_defaults)
    
    if has_perm(request.user, 'speaker.view_speaker', speaker):
        return render_to_response(template_name, {'speaker': speaker},
            context_instance=RequestContext(request))
    else:
        raise Http403
コード例 #5
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def membership_import_status(request, task_id, template_name = 'memberships/import-confirm.html'):
    """
    Checks if a membership import is completed.
    """
    if not is_admin(request.user):
        raise Http403
        
    try:
        task = TaskMeta.objects.get(task_id=task_id)
    except TaskMeta.DoesNotExist:
        #tasks database entries are not created at once.
        task = None
    
    if task and task.status == "SUCCESS":
        
        memberships, stats = task.result
        
        return render_to_response(template_name, {
            'memberships': memberships,
            'stats':stats,
            'datetime': datetime,
        }, context_instance=RequestContext(request))
    else:
        return render_to_response('memberships/import-status.html', {
            'task': task,
            'datetime': datetime,
        }, context_instance=RequestContext(request))
コード例 #6
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def membership_import_confirm(request, id):
    """
    Confirm the membership import and continue with the process.
    This can only be accessed via a hidden post form from the preview page.
    That will hold the original mappings selected by the user.
    """
    if not is_admin(request.user):
        raise Http403
    
    memport = get_object_or_404(MembershipImport, pk=id)
    
    if request.method == "POST":
        form = ImportMapForm(request.POST, memport=memport)
        
        if form.is_valid():
            cleaned_data = form.cleaned_data
            app = memport.app
            file_path = os.path.join(settings.MEDIA_ROOT, memport.get_file().file.name)
            
            if not settings.CELERY_IS_ACTIVE:
                # if celery server is not present 
                # evaluate the result and render the results page
                result = ImportMembershipsTask()
                memberships, stats = result.run(app, file_path, cleaned_data)
                return render_to_response('memberships/import-confirm.html', {
                    'memberships': memberships,
                    'stats': stats,
                    'datetime': datetime,
                }, context_instance=RequestContext(request))
            else:
                result = ImportMembershipsTask.delay(app, file_path, cleaned_data)
            
            return redirect('membership_import_status', result.task_id)
    else:
        return redirect('membership_import_preview', memport.id)
コード例 #7
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def entry_delete(request, id=0, template_name="memberships/entries/delete.html"):
    """
    Delete membership application entry.
    """
    entry = get_object_or_404(AppEntry, id=id)  # exists
    
    if not is_admin(request.user):
        raise Http303  # not permitted

    if request.method == "POST":
        # log entry delete
        EventLog.objects.log(**{
            'event_id' : 1080000,
            'event_data': '%s (%d) viewed by %s' % (entry._meta.object_name, entry.pk, request.user),
            'description': '%s viewed' % entry._meta.object_name,
            'user': request.user,
            'request': request,
            'instance': entry,
        })
        messages.add_message(request, messages.INFO, "Deleted %s" % entry)
        entry.delete()
        
        return redirect("membership.application_entries_search")
    
    return render_to_response(template_name, {
        'entry':entry,
    }, context_instance=RequestContext(request))
コード例 #8
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def photoset_zip(request, id, template_name="photos/photo-set/zip.html"):
    """ Generate zip file for the entire photo set
    for admins only.
    """
    
    photo_set = get_object_or_404(PhotoSet, id=id)
    
    #admin only
    if not is_admin(request.user):
        raise Http403
    
    file_path = ""
    task_id = ""
    if not settings.CELERY_IS_ACTIVE:
        task = ZipPhotoSetTask()
        file_path = task.run(photo_set)        
    else:
        task = ZipPhotoSetTask.delay(photo_set)
        task_id = task.task_id
    
    return render_to_response(template_name, {
        "photo_set": photo_set,
        "task_id":task_id,
        "file_path":file_path,
    }, context_instance=RequestContext(request))
コード例 #9
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
    def __init__(self, *args, **kwargs):
        super(ModelSearchForm, self).__init__(*args, **kwargs)

        # Check to see if users should be included in global search
        include_users = False

        if is_admin(kwargs['user']) or get_setting('module', 'users', 'allowanonymoususersearchuser') \
        or (kwargs['user'].is_authenticated() and get_setting('module', 'users', 'allowusersearch')):
            include_users = True

        if include_users:
            for app in registered_apps:
                if app['verbose_name'].lower() == 'user':
                    registered_apps_models.append(app['model'])
                    registered_apps_names.append(app['model']._meta.module_name)
        else:
            for app in registered_apps:
                if app['verbose_name'].lower() == 'user':
                    try:
                        models_index = registered_apps_models.index(app['model'])
                        registered_apps_models.pop(models_index)
                        names_index = registered_apps_names.index(app['model']._meta.module_name)
                        registered_apps_names.pop(names_index)
                    except Exception as e:
                        pass

        self.models = registered_apps_models
        self.fields['models'] = forms.MultipleChoiceField(choices=model_choices(), required=False, label=_('Search In'), widget=forms.CheckboxSelectMultiple)
コード例 #10
0
ファイル: utils.py プロジェクト: BakethemPie/tendenci
def get_corporate_membership_type_choices(user, corpapp, renew=False):
    cmt_list = []
    corporate_membership_types = corpapp.corp_memb_type.all()
    
    if not is_admin(user):
        corporate_membership_types = corporate_membership_types.filter(admin_only=False)
    currency_symbol = get_setting("site", "global", "currencysymbol")
    
    for cmt in corporate_membership_types:
        if not renew:
            price_display = '%s - %s%0.2f' % (cmt.name, currency_symbol, cmt.price)
        else:
            indiv_renewal_price = cmt.membership_type.renewal_price
            if not indiv_renewal_price:
                indiv_renewal_price = 'Free<span class="type-ind-price"></span>'
            else:
                indiv_renewal_price = '%s<span class="type-ind-price">%0.2f</span>' % (currency_symbol, indiv_renewal_price)
            if not cmt.renewal_price:
                cmt.renewal_price = 0
            
            price_display = """%s - <b>%s<span class="type-corp-price">%0.2f</span></b> 
                            (individual members renewal: 
                            <b>%s</b>)""" % (cmt.name, 
                                            currency_symbol, 
                                            cmt.renewal_price,
                                            indiv_renewal_price)
        price_display = mark_safe(price_display)
        cmt_list.append((cmt.id, price_display))
            
    return cmt_list 
コード例 #11
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def index(request, slug=None, template_name="pages/view.html"):
    if not slug: return HttpResponseRedirect(reverse('page.search'))
    page = get_object_or_404(Page, slug=slug)
    
    # non-admin can not view the non-active content
    # status=0 has been taken care of in the has_perm function
    if (page.status_detail).lower() <> 'active' and (not is_admin(request.user)):
        raise Http403

    if not page.template or not check_template(page.template):
        page.template = "pages/base.html"

    if has_perm(request.user,'pages.view_page',page):
        log_defaults = {
            'event_id' : 585000,
            'event_data': '%s (%d) viewed by %s' % (page._meta.object_name, page.pk, request.user),
            'description': '%s viewed' % page._meta.object_name,
            'user': request.user,
            'request': request,
            'instance': page,
        }
        EventLog.objects.log(**log_defaults)        
        
        return render_to_response(template_name, {'page': page}, 
            context_instance=RequestContext(request))
    else:
        raise Http403
コード例 #12
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def detail(request, id, template_name="invoices/detail.html"):
    invoice = get_object_or_404(Invoice, pk=id)
    
    if not is_admin(request.user): raise Http403
    
    from accountings.models import AcctEntry
    acct_entries = AcctEntry.objects.filter(object_id=id)
    # to be calculated in accounts_tags
    total_debit = 0
    total_credit = 0
    
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("""
                SELECT DISTINCT account_number, description, sum(amount) as total 
                FROM accountings_acct 
                INNER JOIN accountings_accttran on accountings_accttran.account_id =accountings_acct.id 
                INNER JOIN accountings_acctentry on accountings_acctentry.id =accountings_accttran.acct_entry_id 
                WHERE accountings_acctentry.object_id = %d 
                GROUP BY account_number 
                ORDER BY account_number  """ % (invoice.id)) 
    account_numbers = []
    for row in cursor.fetchall():
        account_numbers.append({"account_number":row[0],
                                "description":row[1],
                                "total":abs(row[2])})
    
    return render_to_response(template_name, {'invoice': invoice,
                                              'account_numbers': account_numbers,
                                              'acct_entries':acct_entries,
                                              'total_debit':total_debit,
                                              'total_credit':total_credit}, 
                                              context_instance=RequestContext(request))
コード例 #13
0
ファイル: managers.py プロジェクト: neopunisher/tendenci
    def search_filter(self, filters=None, *args, **kwargs):
        sqs = SearchQuerySet()
        user = kwargs.get("user", None)
        groups = []
        if user and user.is_authenticated():
            groups = [g.pk for g in user.group_set.all()]
        admin = is_admin(user)

        # permission filters
        if user:
            if not admin:
                if not user.is_anonymous():
                    # (status+status_detail+(anon OR user)) OR (who_can_view__exact)
                    anon_query = Q(allow_anonymous_view=True)
                    user_query = Q(allow_user_view=True)
                    sec1_query = Q(status=True, status_detail="active")
                    user_perm_q = Q(users_can_view__in=[user.pk])
                    group_perm_q = Q(groups_can_view__in=groups)

                    query = reduce(operator.or_, [anon_query, user_query])
                    query = reduce(operator.and_, [sec1_query, query])
                    query = reduce(operator.or_, [query, user_perm_q, group_perm_q])
                else:
                    sqs = sqs.filter(allow_anonymous_view=True)
        else:
            sqs = sqs.filter(allow_anonymous_view=True)

        # custom filters
        for filter in filters:
            sqs = sqs.filter(content='"%s"' % filter)

        return sqs.models(self.model)
コード例 #14
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
 def __init__(self, event, user, *args, **kwargs):
     """
     event: instance of Event model
     user: request.user
     reg_count: used for discount validation (discounts have usage limits)
     """
     self.event = event
     self.user = user
     self.reg_count = kwargs.pop('reg_count', 0)
     
     super(RegistrationForm, self).__init__(*args, **kwargs)
     
     # no need for captcha if logged in
     if user.is_authenticated():
         self.fields.pop('captcha')
     
     # admin only price override field
     if not is_admin(user):
         self.fields.pop('amount_for_admin')
     
     reg_conf =  event.registration_configuration
     if reg_conf.can_pay_online:
         payment_methods = reg_conf.payment_method.all()
     else:
         payment_methods = reg_conf.payment_method.exclude(
             machine_name='credit card').order_by('pk')
     self.fields['payment_method'].queryset = payment_methods
コード例 #15
0
ファイル: managers.py プロジェクト: BakethemPie/tendenci
    def search(self, query=None, *args, **kwargs):
        # """
        # Uses haystack to query articles.
        # Returns a SearchQuerySet
        # """
        # # update what the status detail should be instead of active
        # kwargs.update({'status_detail': 'published'})
        # return super(MemberAppManager, self).search(query=query, *args, **kwargs)

        """
        Use Django Haystack search index
        Returns a SearchQuerySet object
        """
        sqs = SearchQuerySet()
        user = kwargs.get('user', AnonymousUser())
        user = impersonation(user)

        if query:
            sqs = sqs.auto_query(sqs.query.clean(query))

        if is_admin(user):
            sqs = sqs.all()  # admin
        else:
            if user.is_anonymous():
                sqs = anon2_sqs(sqs)  # anonymous
            else:
                pass
                sqs = user2_sqs(sqs, user=user)  # user

        return sqs.models(self.model)
コード例 #16
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
    def __init__(self, *args, **kwargs):
        from base.http import Http403
        from site_settings.utils import get_setting
        from perms.utils import is_member, is_admin
        from memberships.models import Membership

        self.user = kwargs.pop('user', None)
        super(ExportForm, self).__init__(*args, **kwargs)

        who_can_export = get_setting('module','memberships','memberexport')

        if who_can_export == 'admin-only':
            if not is_admin(self.user):
                raise Http403
        elif who_can_export == 'membership-of-same-type':
            if not is_member(self.user):
                raise Http403
            membership_types = self.user.memberships.values_list('membership_type').distinct()
            self.fields['app'].queryset = App.objects.filter(membership_types__in=membership_types)
        elif who_can_export == 'members':
            if not is_member(self.user):
                raise Http403
        elif who_can_export == 'users':
            if not self.user.is_authenticated():
                raise Http403
コード例 #17
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def index(request, template_name="reports/index.html"):

    if not is_admin(request.user) and is_developer(request.user):
        raise Http403

    return render_to_response(template_name, {}, 
        context_instance=RequestContext(request))
コード例 #18
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
    def __init__(self, event, price, event_price, *args, **kwargs):
        """
        event: instance of Event model
        price: instance of RegConfPricing model
        event_price: integer of the event amount
        """
        user = kwargs.pop('user', None)
        self.count = kwargs.pop('count', 0)
        self.free_event = event_price <= 0
        super(RegistrationForm, self).__init__(*args, **kwargs)

        if not self.free_event:
            reg_conf =  event.registration_configuration

            if reg_conf.can_pay_online:
                payment_methods = reg_conf.payment_method.all()
            else:
                payment_methods = reg_conf.payment_method.exclude(
                    machine_name='credit card').order_by('pk')

            self.fields['payment_method'] = forms.ModelChoiceField(
                empty_label=None, queryset=payment_methods, widget=forms.RadioSelect(), initial=1, required=True)

            if user and is_admin(user):
                self.fields['amount_for_admin'] = forms.DecimalField(decimal_places=2, initial=event_price)
コード例 #19
0
ファイル: views.py プロジェクト: neopunisher/tendenci
def index(request, slug=None, template_name="news/view.html"):
    if not slug:
        return HttpResponseRedirect(reverse("news.search"))
    news = get_object_or_404(News, slug=slug)

    # non-admin can not view the non-active content
    # status=0 has been taken care of in the has_perm function
    if (news.status_detail).lower() <> "active" and (not is_admin(request.user)):
        raise Http403

    # check permission
    if not has_perm(request.user, "news.view_news", news):
        raise Http403

    log_defaults = {
        "event_id": 305500,
        "event_data": "%s (%d) viewed by %s" % (news._meta.object_name, news.pk, request.user),
        "description": "%s viewed" % news._meta.object_name,
        "user": request.user,
        "request": request,
        "instance": news,
    }
    EventLog.objects.log(**log_defaults)

    return render_to_response(template_name, {"news": news}, context_instance=RequestContext(request))
コード例 #20
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def approve(request, id, template_name="resumes/approve.html"):
    if not is_admin(request.user):
        raise Http403
    resume = get_object_or_404(Resume, pk=id)

    if request.method == "POST":
        resume.activation_dt = now_localized()
        resume.allow_anonymous_view = True
        resume.status = True
        resume.status_detail = 'active'

        if not resume.creator:
            resume.creator = request.user
            resume.creator_username = request.user.username

        if not resume.owner:
            resume.owner = request.user
            resume.owner_username = request.user.username

        resume.save()

        messages.add_message(request, messages.SUCCESS, 'Successfully approved %s' % resume)

        return HttpResponseRedirect(reverse('resume', args=[resume.slug]))

    return render_to_response(template_name, {'resume': resume},
            context_instance=RequestContext(request))
コード例 #21
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def subscribers_import_status(request, group_slug, task_id, template_name='user_groups/import_status.html'):
    """
    Checks if a subscriber import is completed.
    """
    group = get_object_or_404(Group, slug=group_slug)
    
    if not is_admin(request.user):
        raise Http403
    
    try:
        task = TaskMeta.objects.get(task_id=task_id)
    except TaskMeta.DoesNotExist:
        #tasks database entries are not created at once.
        task = None
    
    if task and task.status == "SUCCESS":
        subs = task.result
        return render_to_response('user_groups/import_subscribers_result.html', {
            'group':group,
            'subs':subs,
        }, context_instance=RequestContext(request))
    else:
        return render_to_response(template_name, {
            'group':group,
            'task':task,
        }, context_instance=RequestContext(request))
コード例 #22
0
ファイル: forms.py プロジェクト: neopunisher/tendenci
    def __init__(self, *args, **kwargs):
        super(ServiceForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields["description"].widget.mce_attrs["app_instance_id"] = self.instance.pk
        else:
            self.fields["description"].widget.mce_attrs["app_instance_id"] = 0

        # adjust fields depending on user status
        fields_to_pop = []
        if not self.user.is_authenticated():
            fields_to_pop += [
                "allow_anonymous_view",
                "user_perms",
                "group_perms",
                "activation_dt",
                "expiration_dt",
                "syndicate",
                "status",
                "status_detail",
            ]
        else:
            fields_to_pop += ["captcha"]
        if not is_admin(self.user):
            fields_to_pop += ["status", "status_detail"]
        if not is_developer(self.user):
            fields_to_pop += ["status"]
        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)
コード例 #23
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def index(request, slug=None, template_name="case_studies/view.html"):
    if not slug: return HttpResponseRedirect(reverse('case_study'))
    case_study = get_object_or_404(CaseStudy, slug=slug)
    services = Service.objects.all()
    technologies = Technology.objects.all()

    # non-admin can not view the non-active content
    # status=0 has been taken care of in the has_perm function
    if (case_study.status_detail).lower() <> 'active' and (not is_admin(request.user)):
        raise Http403

    if has_view_perm(request.user, 'case_studies.view_casestudy', case_study):
        log_defaults = {
            'event_id' : 1000500,
            'event_data': '%s (%d) viewed by %s' % (case_study._meta.object_name, case_study.pk, request.user),
            'description': '%s viewed' % case_study._meta.object_name,
            'user': request.user,
            'request': request,
            'instance': case_study,
        }
        EventLog.objects.log(**log_defaults)
        return render_to_response(template_name, {'case_study': case_study, 'services': services, 'technologies': technologies},
            context_instance=RequestContext(request))
    else:
        raise Http403
コード例 #24
0
ファイル: managers.py プロジェクト: BakethemPie/tendenci
    def search(self, query=None, *args, **kwargs):
        """
        haystack to query corporate memberships.
        Returns a SearchQuerySet
        """
        from corporate_memberships.models import CorporateMembership
        from perms.utils import is_admin

        user = kwargs.get('user', None)
        if user.is_anonymous():
            return SearchQuerySet().models().none()

        is_an_admin = is_admin(user)

        sqs = SearchQuerySet().models(CorporateMembership)

        if query:
            sqs = sqs.filter(content=sqs.query.clean(query))
        else:
            sqs = sqs.all()

        if not is_an_admin:
            # reps__contain
            sqs = sqs.filter(Q(content='rep\:%s' % user.username) |
                             Q(creator=user) |
                             Q(owner=user)).filter(status_detail='active')

        return sqs
コード例 #25
0
ファイル: views.py プロジェクト: BakethemPie/tendenci
def user_membership_add(request, username, form_class=UserMembershipForm, template_name="profiles/add_membership.html"):
    user = get_object_or_404(User, username=username)
    
    try:
        profile = Profile.objects.get(user=user)
    except Profile.DoesNotExist:
        profile = Profile.objects.create_profile(user=user)
        
    if not is_admin(request.user):
        raise Http403
        
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            membership = form.save(commit=False)
            membership = update_perms_and_save(request, form, membership)
            messages.add_message(request, messages.SUCCESS, 'Successfully updated memberships for %s' % user.get_full_name())
            return HttpResponseRedirect("%s%s" % (reverse('profile', args=[user.username]),'#userview-memberships'))
    else:
        form = form_class(initial={'user':user})

    return render_to_response(template_name, {
                            'form': form,
                            'user_this': user,
                            }, context_instance=RequestContext(request))
コード例 #26
0
ファイル: managers.py プロジェクト: BakethemPie/tendenci
    def search(self, query=None, *args, **kwargs):
        """
            Uses haystack to query forms.
            Returns a SearchQuerySet
        """
        sqs = SearchQuerySet()
        user = kwargs.get('user', None)

        # check to see if there is impersonation
        if hasattr(user, 'impersonated_user'):
            if isinstance(user.impersonated_user, User):
                user = user.impersonated_user

        is_an_admin = is_admin(user)

        if query:
            sqs = sqs.auto_query(sqs.query.clean(query))
            if user:
                if not is_an_admin:
                    return []
        else:
            sqs = sqs.all()
            if user:
                if not is_an_admin:
                    return []

        return sqs.models(self.model).order_by('-create_dt')
コード例 #27
0
ファイル: decorators.py プロジェクト: BakethemPie/tendenci
    def decorator(request, *args, **kwargs):
        admin = is_admin(request.user)

        if not admin:
            raise Http403
        
        return view_method(request, *args, **kwargs)
コード例 #28
0
ファイル: views.py プロジェクト: neopunisher/tendenci
def notices(request):
    if not is_admin(request.user):
        raise Http403

    notice_types = NoticeType.objects.all()
    notices = Notice.objects.notices_for(request.user, on_site=True)
    settings_table = []
    for notice_type in notice_types:
        settings_row = []
        for medium_id, medium_display in NOTICE_MEDIA:
            form_label = "%s_%s" % (notice_type.label, medium_id)
            setting = get_notification_setting(request.user, notice_type, medium_id)
            if request.method == "POST":
                if request.POST.get(form_label) == "on":
                    setting.send = True
                else:
                    setting.send = False
                setting.save()
            settings_row.append((form_label, setting.send))
        settings_table.append({"notice_type": notice_type, "cells": settings_row})

    notice_settings = {
        "column_headers": [medium_display for medium_id, medium_display in NOTICE_MEDIA],
        "rows": settings_table,
    }

    return render_to_response(
        "notification/notices.html",
        {"notices": notices, "notice_types": notice_types, "notice_settings": notice_settings},
        context_instance=RequestContext(request),
    )
コード例 #29
0
ファイル: models.py プロジェクト: BakethemPie/tendenci
 def auto_update_paid_object(self, request, payment):
     """
     Update the object after online payment is received.
     """
     if not is_admin(request.user):
         self.status_detail = 'paid - pending approval'
     self.expiration_dt = self.activation_dt + timedelta(days=self.requested_duration)
     self.save()
コード例 #30
0
ファイル: forms.py プロジェクト: BakethemPie/tendenci
    def __init__(self, *args, **kwargs):
        super(EntityForm, self).__init__(*args, **kwargs)

        if not is_admin(self.user):
            if 'admin_notes' in self.fields: self.fields.pop('admin_notes')
            if 'status' in self.fields: self.fields.pop('status')
            if 'status_detail' in self.fields: self.fields.pop('status_detail')