Пример #1
0
 def __init__(self, *args, **kwargs):
     if 'user' in kwargs:
         self.user = kwargs.pop('user', None)
     else:
         self.user = None
     super(DonationForm, self).__init__(*args, **kwargs)
     # populate the user fields
     if self.user and self.user.id:
         self.fields['first_name'].initial = self.user.first_name
         self.fields['last_name'].initial = self.user.last_name
         self.fields['email'].initial = self.user.email
         try:
             profile = self.user.get_profile()
             if profile:
                 self.fields['company'].initial = profile.company
                 self.fields['address'].initial = profile.address
                 self.fields['address2'].initial = profile.address2
                 self.fields['city'].initial = profile.city
                 self.fields['state'].initial = profile.state
                 self.fields['zip_code'].initial = profile.zipcode
                 self.fields['country'].initial = profile.country
                 self.fields['phone'].initial = profile.phone
         except:
             pass
         
     self.fields['payment_method'].widget = forms.RadioSelect(choices=get_payment_method_choices(self.user))
     allocation_str = get_setting('module', 'donations', 'donationsallocations')
     if allocation_str:
         self.fields['allocation'].choices = get_allocation_choices(self.user, allocation_str)
     else:
         del self.fields['allocation']
     preset_amount_str = (get_setting('module', 'donations', 'donationspresetamounts')).strip('')
     if preset_amount_str:
         self.fields['donation_amount'] = forms.ChoiceField(choices=get_preset_amount_choices(preset_amount_str))
Пример #2
0
def prepare_paypal_form(request, payment):
    amount = "%.2f" % payment.amount
    image_url = get_setting("site", "global", "MerchantLogo")
    site_url = get_setting("site", "global", "siteurl")
    notify_url = "%s/%s" % (site_url, reverse("paypal.ipn"))
    currency_code = get_setting("site", "global", "currency")
    if not currency_code:
        currency_code = "USD"
    params = {
        "business": settings.PAYPAL_MERCHANT_LOGIN,
        "image_url": image_url,
        "amount": amount,
        "notify_url": notify_url,
        "currency_code": currency_code,
        "invoice": payment.id,
        "item_name": payment.description,
        "first_name": payment.first_name,
        "last_name": payment.last_name,
        "email": payment.email,
        "address1": payment.address,
        "address2": payment.address2,
        "city": payment.city,
        "state": payment.state,
        "country": payment.country,
        "zip": payment.zip,
        "night_phone_a": payment.phone,
    }
    form = PayPalPaymentForm(initial=params)
    form.fields["return"] = forms.CharField(max_length=100, widget=forms.HiddenInput, initial=payment.response_page)

    return form
Пример #3
0
    def get_description(self):
        object = self.object

        ### Assign variables -----------------------
        site_name = get_setting('site','global','sitedisplayname')
        geo_location = get_setting('site','global','sitegeographiclocation')

        if object.description:
            content = object.description

        content = strip_tags(content) #strips HTML tags
        content = unescape_entities(content)
        content = content.replace("\n","").replace("\r","")
        content = truncate_words(content, 50) # ~ about 250 chars

        ### Build string -----------------------
        value = object.name

        value = '%s : %s' % (value, content)

        value = '%s Photo Sets for %s, %s' % (
            value, site_name, geo_location)

        value = value.strip()

        return value
Пример #4
0
def search(request, template_name="profiles/search.html"):
    # check if allow anonymous user search
    allow_anonymous_search = get_setting('module', 'users', 'allowanonymoususersearchuser')
    allow_user_search = get_setting('module', 'users', 'allowusersearch')

    if request.user.is_anonymous():
        if not allow_anonymous_search:
            raise Http403

    if request.user.is_authenticated():
        if not allow_user_search and not request.user.profile.is_superuser:
            raise Http403

    query = request.GET.get('q', None)
    filters = get_query_filters(request.user, 'profiles.view_profile')
    profiles = Profile.objects.filter(filters).distinct()

    if query:
        profiles = profiles.filter(Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | Q(user__email__icontains=query) | Q(user__username__icontains=query))

    profiles = profiles.order_by('user__last_name', 'user__first_name')

    log_defaults = {
        'event_id' : 124000,
        'event_data': '%s searched by %s' % ('Profile', request.user),
        'description': '%s searched' % 'Profile',
        'user': request.user,
        'request': request,
        'source': 'profiles'
    }
    EventLog.objects.log(**log_defaults)

    return render_to_response(template_name, {'profiles':profiles, "user_this":None}, 
        context_instance=RequestContext(request))
Пример #5
0
    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 kwargs['user'].profile.is_superuser 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)
Пример #6
0
def send_welcome_email(user):
    """
    Send email to user account.
    Expects user account else returns false.
    """
    from django.utils.http import int_to_base36
    from django.contrib.auth.tokens import default_token_generator
    from tendenci.core.site_settings.utils import get_setting

    token_generator = default_token_generator

    site_url = get_setting("site", "global", "siteurl")
    site_name = get_setting("site", "global", "sitedisplayname")

    # send new user account welcome email (notification)
    send_emails(
        [user.email],
        "user_welcome",
        {
            "site_url": site_url,
            "site_name": site_name,
            "uid": int_to_base36(user.id),
            "user": user,
            "username": user.username,
            "token": token_generator.make_token(user),
        },
    )
Пример #7
0
def get_max_file_upload_size(file_module=False):
    global_max_upload_size = (
        get_setting("site", "global", "maxfilesize") or "26214400"
    )  # default value if ever site setting is missing
    if file_module:
        return int(get_setting("module", "files", "maxfilesize") or global_max_upload_size)
    return int(global_max_upload_size)
Пример #8
0
def get_theme():
    request = get_current_request()
    if request:
        theme = request.session.get('theme', get_setting('module', 'theme_editor', 'theme'))
    else:
        theme = get_setting('module', 'theme_editor', 'theme')
    return theme
Пример #9
0
 def get_search_filter(user):
     if user.profile.is_superuser: return None, None
     
     filter_and, filter_or = None, None
     
     allow_anonymous_search = get_setting('module', 
                                  'corporate_memberships', 
                                  'anonymoussearchcorporatemembers')
     allow_member_search = get_setting('module', 
                               'corporate_memberships', 
                               'membersearchcorporatemembers')
     
     if allow_anonymous_search or (allow_member_search and user.profile.is_member):
         filter_and =  {'status':1,
                        'status_detail':'active'}
     else:
         if user.is_authenticated():
             filter_or = {'creator': user,
                          'owner': user}
             if use_search_index:
                 filter_or.update({'reps': user})
             else:
                 filter_or.update({'reps__user': user})
         else:
             filter_and = {'allow_anonymous_view':True,}
             
             
     return filter_and, filter_or
Пример #10
0
def send_registration_activation_email(user, registration_profile, **kwargs):
    """
        this function sends the activation email to the self registrant.
        modified based on the block in create_inactive_user in registration/models.py
    """
    from django.core.mail import send_mail
    from django.template.loader import render_to_string
    from django.conf import settings
    from tendenci.core.site_settings.utils import get_setting

    event = kwargs.pop('event', None)
    event_url = None
    if event: event_url = event.get_absolute_url()

    site_url = get_setting('site', 'global', 'siteurl')
    subject = render_to_string('registration/activation_email_subject.txt',
                                       { 'site_url': site_url })

    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    message = render_to_string('registration/activation_email.txt',
                               { 'activation_key': registration_profile.activation_key,
                                 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                 'event_url': event_url,
                                 'site_url': site_url })

    from_email = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL

    send_mail(subject, message, from_email, [user.email])
Пример #11
0
def membership_search(request, template_name="memberships/search.html"):
    membership_view_perms = get_setting('module', 'memberships', 'memberprotection')

    if not membership_view_perms == "public":
        return HttpResponseRedirect(reverse('profile.search') + "?members=on")

    query = request.GET.get('q')
    mem_type = request.GET.get('type')
    total_count = Membership.objects.all().count()
    if get_setting('site', 'global', 'searchindex') and (total_count > 1000 or query):
        members = Membership.objects.search(query, user=request.user)
        if mem_type:
            members = members.filter(mem_type=mem_type)
        members = members.order_by('last_name')
    else:
        filters = get_query_filters(request.user, 'memberships.view_membership')
        members = Membership.objects.filter(filters).distinct()
        if mem_type:
            members = members.filter(membership_type__pk=mem_type)
        members = members.exclude(status_detail='expired')
        members = members.order_by('user__last_name')
    types = MembershipType.objects.all()

    EventLog.objects.log()

    return render_to_response(template_name, {'members': members, 'types': types},
        context_instance=RequestContext(request))
Пример #12
0
    def get_keywords(self):
        object = self.object

        ### Assign variables -----------------------
        dynamic_keywords = generate_meta_keywords(object.body)
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')


        ### Build string -----------------------
        value = ''

        list = [
            'Photos',
            geo_location,
            site_name,
        ]

        # remove blank items
        for item in list:
            if not item.strip():
                list.remove(item)

        value = '%s %s, %s' % (value, ', '.join(list), dynamic_keywords)


        return value
Пример #13
0
def theme(request):
    contexts = {}
    if "theme" in request.GET and request.user.profile.is_superuser:
        if request.GET.get("theme"):
            request.session["theme"] = request.GET.get("theme")
        elif "theme" in request.session:
            del request.session["theme"]

    if "toggle_template" in request.GET:
        contexts["TOGGLE_TEMPLATE"] = True

    theme = request.session.get("theme", get_setting("module", "theme_editor", "theme"))
    contexts["THEME"] = theme

    if settings.USE_S3_STORAGE:
        contexts["THEME_URL"] = "%s/%s/%s/themes/%s/" % (
            settings.S3_ROOT_URL,
            settings.AWS_STORAGE_BUCKET_NAME,
            settings.AWS_LOCATION,
            theme,
        )
    else:
        contexts["THEME_URL"] = "/themes/" + theme + "/"

    contexts["LOCAL_THEME_URL"] = "/themes/" + theme + "/"
    contexts["ACTIVE_THEME"] = get_setting("module", "theme_editor", "theme")

    contexts["THEME_INFO"] = get_theme_info(theme)

    return contexts
Пример #14
0
def get_theme():
    request = get_current_request()
    if request:
        theme = request.session.get("theme", get_setting("module", "theme_editor", "theme"))
    else:
        theme = get_setting("module", "theme_editor", "theme")
    return theme
Пример #15
0
 def enabled(cls):
     """Return backend enabled status by checking Setting Model"""
     try:
         FACEBOOK_APP_ID = get_setting(scope='module', scope_category='users', name='facebook_app_id')
         FACEBOOK_API_SECRET = get_setting(scope='module', scope_category='users', name='facebook_api_secret')
     except Setting.DoesNotExist:
         return False
     return True
Пример #16
0
    def get_title(self):
        obj = self.object

        ### Assign variables -----------------------
        primary_keywords = get_setting('site', 'global', 'siteprimarykeywords')
        geo_location = get_setting('site', 'global', 'sitegeographiclocation')
        site_name = get_setting('site', 'global', 'sitedisplayname')
        category_set = obj.category_set
        category = category_set.get('category', '')
        subcategory = category_set.get('sub_category', '')

        contact_name = '%s %s' % (
            obj.first_name,
            obj.last_name
        )
        contact_name = contact_name.strip()

        ### Build string -----------------------
        values_list = []
        if obj.headline:
            values_list.append(obj.headline)

        if obj.headline and obj.release_dt:
            values_list.append('-')
        if obj.release_dt:
            values_list.append(obj.release_dt.strftime('%m-%d-%Y'))

        if primary_keywords:
            if values_list:
                values_list.append(':')
                values_list.append(primary_keywords)
        else:
            if category and subcategory:
                values_list.append('category')
                values_list.append(':')
                values_list.append('subcategory')
            elif category:
                values_list.append('category')

        if contact_name:
            values_list.append('contact: %s' % contact_name)

        if geo_location:
            values_list.append('in %s' % geo_location)
        # commenting out to avoid the duplicates - the site name
        # is included on base.html already.
#        if site_name:
#            if values_list:
#                values_list.append('|')
#            values_list.append(site_name)

        title = ' '.join(values_list)
        # truncate the meta title to 100 characters
        max_length = 100
        if len(title) > max_length:
            title = '%s...' % title[:(max_length - 3)]

        return title
 def get_admin_emails():
     admin_emails = get_setting("module", "corporate_memberships", "corporatemembershiprecipients").strip()
     if admin_emails:
         admin_emails = admin_emails.split(",")
     if not admin_emails:
         admin_emails = (get_setting("site", "global", "admincontactemail").strip()).split(",")
     if admin_emails:
         admin_emails = ",".join(admin_emails)
     return admin_emails
Пример #18
0
    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        password_regex = get_setting('module', 'users', 'password_requirements_regex')
        password_requirements = get_setting('module', 'users', 'password_text')
        if password_regex:
            if not re.match(password_regex, password1):
                raise forms.ValidationError(mark_safe("The password does not meet the requirements </li><li>%s" % password_requirements))

        return password1
Пример #19
0
    def get_title(self):
        obj = self.object

        ### Assign variables -----------------------  
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')
        category = Category.objects.get_for_object(obj, 'category')
        subcategory = Category.objects.get_for_object(obj, 'subcategory')

        contact_name = '%s %s' % (
            obj.first_name, 
            obj.last_name
        )
        contact_name = contact_name.strip()

        ### Build string -----------------------
        values_list = []
        if obj.headline:
            values_list.append(obj.headline)

        if obj.headline and obj.release_dt:
            values_list.append('-')
        if obj.release_dt:
            values_list.append(obj.release_dt.strftime('%m-%d-%Y'))

        if primary_keywords:
            if values_list:
                values_list.append(':')
                values_list.append(primary_keywords)
        else:
            if category and subcategory:
                values_list.append('category')
                values_list.append(':')
                values_list.append('subcategory')
            elif category:
                values_list.append('category')

        if site_name:
            if values_list:
                values_list.append('news for')
            values_list.append(site_name)

        if contact_name:
            values_list.append('contact: %s' % contact_name)

        if geo_location:
            values_list.append('in %s' % geo_location)

        title = ' '.join(values_list)
        # truncate the meta title to 100 characters
        max_length = 100
        if len(title) > max_length:
            title = '%s...' % title[:(max_length - 3)]

        return title
Пример #20
0
def robots_txt(request):
    options = ['base/robots_private.txt', 'base/robots_public.txt', 'robots.txt']
    template_name = "robots.txt"

    robots_setting = get_setting('site', 'global', 'robotstxt')
    if robots_setting in options:
        template_name = robots_setting

    site_url = get_setting('site', 'global', 'siteurl')
    return render_to_response(template_name, {'site_url': site_url}, context_instance=RequestContext(request), mimetype="text/plain")
Пример #21
0
 def get_admin_emails():
     admin_emails = get_setting('module', 'memberships', 'membershiprecipients').strip()
     if admin_emails:
         admin_emails = admin_emails.split(',')
     if not user.profile.is_superuser_emails:
         admin_emails = (get_setting('site', 'global', 'admincontactemail').strip()).split(',')
         
     if admin_emails:
         admin_emails = ','.join(admin_emails)
     return admin_emails
Пример #22
0
 def get_admin_emails():
     admin_emails = get_setting('module', 'memberships',
                                'membershiprecipients').strip()
     if admin_emails:
         admin_emails = admin_emails.split(',')
     if not admin_emails:
         admin_emails = (get_setting('site', 'global',
                                     'admincontactemail'
                                     ).strip()).split(',')
     return admin_emails
Пример #23
0
    def get_title(self):
        object = self.object

        ### Assign variables -----------------------  
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')
        category_set = object.category_set
        category = category_set.get('category', '')
        subcategory = category_set.get('sub_category', '')

        creator_name = ''
        if object.creator:
            creator_name = '%s %s' % (
                object.creator.first_name,
                object.creator.last_name
            )
        creator_name = creator_name.strip()

        ### Build string -----------------------
        value = '%s - %s' % (object.headline, object.activation_dt)
        value = value.strip()

        value = ''

        # start w/ headline
        if object.headline:
            value += object.headline

        # contact activation
        if object.headline and object.activation_dt:
            value += ' - %s' % object.activation_dt.strftime('%m-%d-%Y')
        elif object.activation_dt:
            value += object.activation_dt.strftime('%m-%d-%Y')

        # primary keywords OR category/subcategory
        if primary_keywords:
            value = '%s : %s' % (value, primary_keywords)
        else:
            if category:
                value = '%s %s' % (value, category)
            if category and subcategory:
                value = '%s : %s' % (value, subcategory)

        value = '%s directory' % value

        if creator_name:
            value = '%s contact: %s' % (value, creator_name)

        value = '%s directories for %s' % (value, site_name)

        if geo_location:
            value = '%s in %s' % (value, geo_location)

        return value
Пример #24
0
    def clean_new_password1(self):
        password1 = self.cleaned_data.get('new_password1')
        password_regex = get_setting('module', 'users', 'password_requirements_regex')
        password_requirements = get_setting('module', 'users', 'password_text')
        if password_regex:
            # At least MIN_LENGTH long
            # "^(?=.{8,})(?=.*[0-9=]).*$"
            if not re.match(password_regex, password1):
                raise forms.ValidationError(mark_safe("The new password does not meet the requirements </li><li>%s" % password_requirements))

        return password1
Пример #25
0
def encode_site(xml):
    xml.write("<title>%s</title>"%get_setting('site', 'global', 'sitedisplayname'), depth=1)
    xml.write("<description></description>", depth=1)
    xml.write("<pubDate>%s</pubDate>"%datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), depth=1)
    xml.write("<language>%s</language>"%get_setting('site', 'global', 'localizationlanguage'), depth=1)
    xml.write("<wp:wxr_version>%s</wp:wxr_version>"%1.0, depth=1)
    # not sure if this is required
    #xml.write("<wp:base_site_url>http://wordpress.com/</wp:base_site_url>", depth=1)
    #xml.write("<wp:base_blog_url>http://sambixly.wordpress.com</wp:base_blog_url>", depth=1)
    encode_categories(xml)
    encode_tags(xml)
Пример #26
0
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        # check if we need to hide the remember me checkbox
        # and set the default value for remember me
        hide_remember_me = get_setting('module', 'users', 'usershiderememberme')
        remember_me_default_checked = get_setting('module', 'users', 'usersremembermedefaultchecked')

        if remember_me_default_checked:
            self.fields['remember'].initial = True
        if hide_remember_me:
            self.fields['remember'].widget = forms.HiddenInput()
Пример #27
0
    def get_admin_emails(self):
        payment_admins = get_setting("module", "payments", "paymentrecipients")
        if payment_admins:
            payment_admins = payment_admins.split(",")
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting("site", "global", "admincontactemail")).split(",")

        if admin_emails:
            admin_emails = ",".join(admin_emails)

        return admin_emails
Пример #28
0
    def get_admin_emails(self):
        payment_admins = get_setting('module', 'payments', 'paymentrecipients')
        if payment_admins:
            payment_admins = payment_admins.split(',')
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting('site', 'global', 'admincontactemail')).split(',')

        if admin_emails:
            admin_emails = ','.join(admin_emails)

        return admin_emails
Пример #29
0
    def get_title(self):
        object = self.object

        ### Assign variables -----------------------  
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')
        category = Category.objects.get_for_object(object, 'category')
        subcategory = Category.objects.get_for_object(object, 'subcategory')

        contact_name = '%s %s' % (
            object.first_name, 
            object.last_name
        )
        contact_name = contact_name.strip()

        ### Build string -----------------------
        value = '%s - %s' % (object.headline, object.release_dt)
        value = value.strip()

        value = ''

        # start w/ headline
        if object.headline:
            value += object.headline

        # contact release
        if object.headline and object.release_dt:
            value += ' - %s' % object.release_dt.strftime('%m-%d-%Y')
        elif object.release_dt:
            value += object.release_dt.strftime('%m-%d-%Y')

        # primary keywords OR category/subcategory
        if primary_keywords:
            value = '%s : %s' % (value, primary_keywords)
        else:
            if category:
                value = '%s %s' % (value, category)
            if category and subcategory:
                value = '%s : %s' % (value, subcategory)

        value = '%s news' % value

        if contact_name:
            value = '%s contact: %s' % (value, contact_name)

        value = '%s news for %s' % (value, site_name)

        if geo_location:
            value = '%s in %s' % (value, geo_location)

        return value
Пример #30
0
    def get_description(self):
        object = self.object

        ### Assign variables -----------------------  
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        category_set = object.category_set
        category = category_set.get('category', '')
        subcategory = category_set.get('sub_category', '')
        site_name = get_setting('site','global','sitedisplayname')
        geo_location = get_setting('site','global','sitegeographiclocation')
        creator_name = ''
        if object.creator:
            creator_name = '%s %s' % (
                object.creator.first_name,
                object.creator.last_name
            )
        creator_name = creator_name.strip()

        if object.summary:
            content = object.summary
        else:
            content = object.body

        content = strip_tags(content) #strips HTML tags
        content = unescape_entities(content)
        content = content.replace("\n","").replace("\r","")
        content = truncate_words(content, 50) # ~ about 250 chars

        ### Build string -----------------------
        value = object.headline

        if creator_name:
            value = '%s %s' % (value, creator_name)

        value = '%s : %s' % (value, content)

        if primary_keywords:
            value = '%s %s' % (value, primary_keywords)
        else:
            if category:
                value = '%s %s' % (value, category)
            if category and subcategory:
                value = '%s : %s' % (value, subcategory)

            value = '%s directory' % value

        value = '%s Directories for %s %s' % (
            value, site_name, geo_location)

        value = value.strip()

        return value
Пример #31
0
def search(request, template_name="directories/search.html"):
    query = request.GET.get('q')
    category = request.GET.get('category')
    subcategory = request.GET.get('sub_category')

    if get_setting('site', 'global', 'searchindex') and query:
        if category:
            try:
                query = '%s category:%s' % (query, Category.objects.get(id=int(category)).name)
            except (Category.DoesNotExist, ValueError):
                pass

        if subcategory:
            try:
                query = '%s subcategory:%s' % (query, Category.objects.get(id=int(subcategory)).name)
            except (Category.DoesNotExist, ValueError):
                pass

        directories = Directory.objects.search(query, user=request.user).order_by('headline_exact')
    else:
        filters = get_query_filters(request.user, 'directories.view_directory')
        directories = Directory.objects.filter(filters).distinct()
        if not request.user.is_anonymous():
            directories = directories.select_related()

        if category:
            directories = directories.filter(categories__category=category)
        if subcategory:
            directories = directories.filter(categories__parent=subcategory)

        directories = directories.order_by('headline')

    EventLog.objects.log()

    try:
        category = int(category)
    except:
        category = 0
    categories, sub_categories = Directory.objects.get_categories(category=category)

    return render_to_response(template_name, {
        'directories': directories,
        'categories': categories,
        'sub_categories': sub_categories,
    }, context_instance=RequestContext(request))
Пример #32
0
    def save(self, profile_callback=None, event=None):
        #
        #new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
        #                                                            password=self.cleaned_data['password1'],
        # create inactive user                                                           email=self.cleaned_data['email'])
        new_user = User.objects.create_user(self.cleaned_data['username'],
                                            self.cleaned_data['email'],
                                            self.cleaned_data['password1'])

        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.is_active = False
        new_user.save()
        # create registration profile
        registration_profile = RegistrationProfile.objects.create_profile(
            new_user)
        send_registration_activation_email(new_user,
                                           registration_profile,
                                           event=event)

        new_profile = Profile(
            user=new_user,
            company=self.cleaned_data['company'],
            phone=self.cleaned_data['phone'],
            address=self.cleaned_data['address'],
            city=self.cleaned_data['city'],
            state=self.cleaned_data['state'],
            country=self.cleaned_data['country'],
            zipcode=self.cleaned_data['zipcode'],
        )
        user_hide_default = get_setting('module', 'users', 'usershidedefault')
        if user_hide_default:
            new_profile.hide_in_search = 1
            new_profile.hide_address = 1
            new_profile.hide_email = 1
            new_profile.hide_phone = 1

        new_profile.creator = new_user
        new_profile.creator_username = new_user.username
        new_profile.owner = new_user
        new_profile.owner_username = new_user.username
        new_profile.save()
        sf_id = create_salesforce_contact(new_profile)

        return new_user
Пример #33
0
 def render(self, context):
     theme = context.get('THEME',
                         get_setting('module', 'theme_editor', 'theme'))
     theme_template = get_theme_template(self.template_path, theme=theme)
     try:
         try:
             t = get_template(theme_template)
         except TemplateDoesNotExist:
             t = get_default_template(self.template_path)
         self.template = t
     except:
         if settings.TEMPLATE_DEBUG:
             raise
         self.template = None
     if self.template:
         return self.template.render(context)
     else:
         return ''
Пример #34
0
    def handle(self, *args, **options):
        from tendenci.apps.user_groups.models import Group
        from tendenci.addons.memberships.models import MembershipType
        from tendenci.core.site_settings.utils import get_setting

        # membership group ids
        groups_list = list(
            MembershipType.objects.values_list('group', flat=True))
        # corp reps group id
        reps_group_id = get_setting('module', 'corporate_memberships',
                                    'corpmembershiprepsgroupid')
        if reps_group_id:
            groups_list.append(reps_group_id)

        if groups_list:
            # change type to 'system_generated'
            Group.objects.filter(id__in=groups_list).update(
                type='system_generated')
Пример #35
0
def tcurrency(mymoney):
    """
        format currency - GJQ
        ex: 30000.232 -> $30,000.23
            -30000.232 -> $(30,000.23)
    """
    currency_symbol = get_setting("site", "global", "currencysymbol")

    if not currency_symbol:
        currency_symbol = "$"

    if not isinstance(mymoney, str):
        if mymoney >= 0:
            return currency_symbol + intcomma(mymoney)
        else:
            return currency_symbol + '(%s)' % intcomma(mymoney)
    else:
        return mymoney
Пример #36
0
def photoset_view_latest(request,
                         template_name="photos/photo-set/latest.html"):
    """ View latest photo set """

    query = request.GET.get('q', None)
    if get_setting('site', 'global', 'searchindex') and query:
        photo_sets = PhotoSet.objects.search(query, user=request.user)
    else:
        filters = get_query_filters(request.user, 'photos.view_photoset')
        photo_sets = PhotoSet.objects.filter(filters).distinct()
        if not request.user.is_anonymous():
            photo_sets = photo_sets.select_related()
    photo_sets = photo_sets.order_by('-create_dt')

    EventLog.objects.log()

    return render_to_response(template_name, {"photo_sets": photo_sets},
                              context_instance=RequestContext(request))
Пример #37
0
def my_jobs(request, template_name = "jobs/my_jobs.html"):
    query = request.GET.get('q', None)
    if not request.user.is_anonymous():
        if get_setting('site', 'global', 'searchindex') and query:
            jobs = Job.objects.search(query, user=request.user)
        else:
            filters = get_query_filters(request.user, 'jobs.view_job')
            jobs = Job.objects.filter(filters).distinct()
            jobs = jobs.select_related()
        jobs = jobs.order_by('status_detail', 'list_type', '-post_dt')
        jobs = jobs.filter(creator_username=request.user.username)

        EventLog.objects.log()

        return render_to_response(template_name, {'jobs': jobs},
            context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('jobs'))
Пример #38
0
def get_payment_method_choices(user):
    if user.profile.is_superuser:
        return (
            ('paid - check', 'User paid by check'),
            ('paid - cc', 'User paid by credit card'),
            ('Credit Card', 'Make online payment NOW'),
        )
    else:
        job_payment_types = get_setting('module', 'jobs', 'jobspaymenttypes')
        if job_payment_types:
            job_payment_types_list = job_payment_types.split(',')
            job_payment_types_list = [
                item.strip() for item in job_payment_types_list
            ]

            return [(item, item) for item in job_payment_types_list]
        else:
            return ()
Пример #39
0
def prepare_authorizenet_sim_form(request, payment):
    x_fp_timestamp = str(int(time.time()))
    x_amount = "%.2f" % payment.amount
    x_fp_hash = get_fingerprint(str(payment.id), x_fp_timestamp, x_amount)
    x_logo_URL = get_setting("site", "global", "MerchantLogo")

    params = {
        'x_fp_sequence': payment.id,
        'x_fp_timestamp': x_fp_timestamp,
        'x_fp_hash': x_fp_hash,
        'x_amount': x_amount,
        'x_version': '3.1',
        'x_login': settings.MERCHANT_LOGIN,
        'x_relay_response': 'TRUE',
        'x_relay_url': payment.response_page,
        'x_invoice_num': payment.invoice_num,
        'x_description': payment.description,
        'x_email_customer': "True",
        'x_email': payment.email,
        'x_cust_id': payment.cust_id,
        'x_first_name': payment.first_name,
        'x_last_name': payment.last_name,
        'x_company': payment.company,
        'x_address': payment.address,
        'x_city': payment.city,
        'x_state': payment.state,
        'x_zip': payment.zip,
        'x_country': payment.country,
        'x_ship_to_first_name': payment.ship_to_first_name,
        'x_ship_to_last_name': payment.ship_to_last_name,
        'x_ship_to_company': payment.ship_to_company,
        'x_ship_to_address': payment.ship_to_address,
        'x_ship_to_city': payment.ship_to_city,
        'x_ship_to_state': payment.ship_to_state,
        'x_ship_to_zip': payment.ship_to_zip,
        'x_ship_to_country': payment.ship_to_country,
        'x_fax': payment.fax,
        'x_phone': payment.phone,
        'x_show_form': 'payment_form',
        'x_logo_URL': x_logo_URL,
    }
    form = SIMPaymentForm(initial=params)

    return form
Пример #40
0
    def handle(self, *args, **kwargs):
        from tendenci.core.site_settings.utils import get_setting
        from tendenci.addons.memberships.models import Membership
        from tendenci.apps.user_groups.models import GroupMembership
        protection = get_setting('module', 'memberships', 'memberprotection')

        if protection == 'public':
            Membership.objects.update(
                allow_anonymous_view=True,
                allow_user_view=False,
                allow_member_view=False
            )
        elif protection == 'all-members':
            Membership.objects.update(
                allow_anonymous_view=False,
                allow_user_view=False,
                allow_member_view=True
            )
        elif protection == 'member-type':
            Membership.objects.update(
                allow_anonymous_view=False,
                allow_user_view=False,
                allow_member_view=False
            )
            for membership in Membership.objects.all():

                # add or remove from group -----
                if membership.is_active():  # should be in group; make sure they're in
                    membership.membership_type.group.add_user(membership.user)
                else:  # should not be in group; make sure they're out
                    GroupMembership.objects.filter(
                        member=membership.user,
                        group=membership.membership_type.group
                    ).delete()
                # -----

                print membership

        else:  # private
            Membership.objects.update(
                allow_anonymous_view=False,
                allow_user_view=False,
                allow_member_view=False
            )
Пример #41
0
    def render(self, context):
        context['setting_name'] = unicode(self.template_name).replace(
            'MODULE_THEME_', '').lower()
        try:
            setting_value = Variable(self.template_name).resolve(context)
        except VariableDoesNotExist:
            setting_value = None

        if setting_value:
            # First try to render this as a box
            user = AnonymousUser()
            if 'user' in context:
                if isinstance(context['user'], User):
                    user = context['user']
            try:
                # for performance reason, pass AnonymousUser() to reduce the joins of objectpermissions
                # in the meantime, we do want to show public items on homepage
                filters = get_query_filters(AnonymousUser(), 'boxes.view_box')
                box = Box.objects.filter(filters).filter(pk=setting_value)
                context['box'] = box[0]
                template = get_template('theme_includes/box.html')
                return template.render(context)
            except:
                # Otherwise try to render a template
                try:
                    template_name = os.path.join('theme_includes',
                                                 setting_value)
                    theme = context.get(
                        'THEME', get_setting('module', 'theme_editor',
                                             'theme'))
                    theme_template = get_theme_template(template_name,
                                                        theme=theme)
                    try:
                        t = get_template(theme_template)
                    except TemplateDoesNotExist:
                        t = get_default_template(template_name)
                    return t.render(context)
                except:
                    if settings.TEMPLATE_DEBUG:
                        raise
                    return ''
        else:
            return ''
Пример #42
0
def tcurrency(mymoney):
    """
        format currency - GJQ
        ex: 30000.232 -> $30,000.23
            -30000.232 -> $(30,000.23)
    """
    currency_symbol = get_setting("site", "global", "currencysymbol")

    if not currency_symbol:
        currency_symbol = "$"

    if not isinstance(mymoney, basestring):
        if mymoney >= 0:
            fmt = '%s%s'
        else:
            fmt = '%s(%s)'
        return fmt % (currency_symbol, intcomma(mymoney))
    else:
        return mymoney
Пример #43
0
def date_long(value, arg=None):
    """Formats a date according to the given format."""
    from django.utils.dateformat import format
    from tendenci.core.site_settings.utils import get_setting
    if not value:
        return u''
    if arg is None:
        s_date_format = get_setting('site', 'global', 'dateformatlong')
        if s_date_format:
            arg = s_date_format
        else:
            arg = settings.DATETIME_FORMAT
    try:
        return formats.date_format(value, arg)
    except AttributeError:
        try:
            return format(value, arg)
        except AttributeError:
            return ''
Пример #44
0
    def run(self, template, **kwargs):
        #set up urls
        site_url = get_setting('site', 'global', 'siteurl')
        html_url = unicode("%s%s" % (site_url, template.get_html_url()))
        html_url += "?jump_links=%s" % form.cleaned_data.get('jump_links')
        try:
            from tendenci.addons.events.models import Event, Type
            html_url += "&events=%s" % form.cleaned_data.get('events')
            html_url += "&events_type=%s" % form.cleaned_data.get(
                'events_type')
            html_url += "&event_start_dt=%s" % form.cleaned_data.get(
                'event_start_dt', '')
            html_url += "&event_end_dt=%s" % form.cleaned_data.get(
                'event_end_dt', '')
        except ImportError:
            pass
        html_url += "&articles=%s" % form.cleaned_data.get('articles')
        html_url += "&articles_days=%s" % form.cleaned_data.get(
            'articles_days')
        html_url += "&news=%s" % form.cleaned_data.get('news')
        html_url += "&news_days=%s" % form.cleaned_data.get('news_days')
        html_url += "&jobs=%s" % form.cleaned_data.get('jobs')
        html_url += "&jobs_days=%s" % form.cleaned_data.get('jobs_days')
        html_url += "&pages=%s" % form.cleaned_data.get('pages')
        html_url += "&pages_days=%s" % form.cleaned_data.get('pages_days')

        if template.zip_file:
            if hasattr(settings, 'USE_S3_STORAGE') and settings.USE_S3_STORAGE:
                zip_url = unicode(template.get_zip_url())
            else:
                zip_url = unicode("%s%s" % (site_url, template.get_zip_url()))
        else:
            zip_url = unicode()

        #sync with campaign monitor
        try:
            t = CST(template_id=template.template_id)
            t.update(unicode(template.name), html_url, zip_url)
        except BadRequest, e:
            messages.add_message(
                request, messages.ERROR,
                'Bad Request %s: %s' % (e.data.Code, e.data.Message))
            return redirect('campaign_monitor.campaign_generate')
Пример #45
0
def template_update(request, template_id):
    """
    This method makes use of the same files to update the CM Template.
    Useful for updating data/content only and retaining design.
    """

    template = get_object_or_404(Template, template_id=template_id)

    if not has_perm(request.user, 'campaign_monitor.change_template',
                    template):
        raise Http403

    #set up urls
    site_url = get_setting('site', 'global', 'siteurl')
    html_url = unicode("%s%s" % (site_url, template.get_html_url()))
    html_url += "?jump_links=1&articles=1&articles_days=60&news=1&news_days=60&jobs=1&jobs_days=60&pages=1&pages_days=7"
    try:
        from tendenci.addons.events.models import Event, Type
        html_url += "&events=1"
        html_url += "&events_type="
        html_url += "&event_start_dt=%s" % datetime.date.today()
        end_dt = datetime.date.today() + timedelta(days=90)
        html_url += "&event_end_dt=%s" % end_dt
    except ImportError:
        pass

    if template.zip_file:
        if hasattr(settings, 'USE_S3_STORAGE') and settings.USE_S3_STORAGE:
            zip_url = unicode(template.get_zip_url())
        else:
            zip_url = unicode("%s%s" % (site_url, template.get_zip_url()))
    else:
        zip_url = unicode()

    #sync with campaign monitor
    try:
        t = CST(auth=auth, template_id=template.template_id)
        t.update(unicode(template.name), html_url, zip_url)
    except BadRequest, e:
        messages.add_message(
            request, messages.ERROR,
            'Bad Request %s: %s' % (e.data.Code, e.data.Message))
        return redirect(template)
Пример #46
0
    def set_default_private_settings(self):
        # public, private, all-members, member-type
        memberprotection = get_setting('module', 'memberships',
                                       'memberprotection')
        d = {
            'allow_anonymous_view': False,
            'allow_user_view': False,
            'allow_member_view': False,
            'allow_user_edit': False,
            'allow_member_edit': False
        }

        if memberprotection == 'public':
            d['allow_anonymous_view'] = True
        if memberprotection == 'all-members':
            d['allow_user_view'] = True
        if memberprotection == 'member-type':
            d['allow_member_view'] = True
        return d
Пример #47
0
def search(request, template_name="articles/search.html"):
    get = dict(request.GET)
    query = get.pop('q', [])
    get.pop('page', None)  # pop page query string out; page ruins pagination
    query_extra = ['%s:%s' % (k, v[0]) for k, v in get.items() if v[0].strip()]
    query = ' '.join(query)
    if query_extra:
        query = '%s %s' % (query, ' '.join(query_extra))

    if get_setting('site', 'global', 'searchindex') and query:
        articles = Article.objects.search(query, user=request.user)
    else:
        filters = get_query_filters(request.user, 'articles.view_article')
        articles = Article.objects.filter(filters).distinct()
        if not request.user.is_anonymous():
            articles = articles.select_related()

    if not has_perm(request.user, 'articles.view_article'):
        articles = articles.filter(release_dt__lte=datetime.now())

    # don't use order_by with "whoosh"
    if not query or settings.HAYSTACK_SEARCH_ENGINE.lower() != "whoosh":
        articles = articles.order_by('-release_dt')
    else:
        articles = articles.order_by('-create_dt')

    EventLog.objects.log()

    # Query list of category and subcategory for dropdown filters
    category = request.GET.get('category')
    try:
        category = int(category)
    except:
        category = 0
    categories, sub_categories = Article.objects.get_categories(
        category=category)

    return render_to_response(template_name, {
        'articles': articles,
        'categories': categories,
        'sub_categories': sub_categories
    },
                              context_instance=RequestContext(request))
Пример #48
0
def search(request, template_name="contacts/search.html"):
    if request.user.is_anonymous():
        raise Http403
    if not has_perm(request.user,'contacts.view_contact'):
        raise Http403

    query = request.GET.get('q', None)
    if get_setting('site', 'global', 'searchindex') and query:
        contacts = Contact.objects.search(query, user=request.user)
    else:
        filters = get_query_filters(request.user, 'contacts.view_contact')
        contacts = Contact.objects.filter(filters).distinct()
        if not request.user.is_anonymous():
            contacts = contacts.select_related()

    contacts = contacts.order_by('-create_dt')

    return render_to_response(template_name, {'contacts':contacts},
        context_instance=RequestContext(request))
Пример #49
0
 def clean_email(self):
     """
     Validates that a user exists with the given e-mail address.
     """
     email = self.cleaned_data["email"]
     self_reg = get_setting('module', 'users', 'selfregistration')
     self.email = email
     self.users_cache = User.objects.filter(email__iexact=email)
     if len(self.users_cache) == 0:
         if self_reg:
             raise forms.ValidationError(
                 mark_safe(
                     _('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve <a href="/accounts/register" >registered</a>?'
                       )))
         else:
             raise forms.ValidationError(
                 _("That e-mail address doesn't have an associated user account."
                   ))
     return email
Пример #50
0
def search(request, template_name="jobs/search.html"):
    query = request.GET.get('q', None)
    my_pending_jobs = request.GET.get('my_pending_jobs', False)
    category = None
    subcategory = None

    if get_setting('site', 'global', 'searchindex') and query:
        jobs = Job.objects.search(query, user=request.user)
    else:
        filters = get_query_filters(request.user, 'jobs.view_job')
        jobs = Job.objects.filter(filters).distinct()
        if not request.user.is_anonymous():
            jobs = jobs.select_related()

    form = JobSearchForm(request.GET)
    if form.is_valid():
        query = form.cleaned_data.get('q')
        category = form.cleaned_data.get('categories')
        subcategory = form.cleaned_data.get('subcategories')

    if category:
        jobs = jobs.filter(categories__category=category)
    if subcategory:
        jobs = jobs.filter(categories__parent=subcategory)

    # filter for "my pending jobs"
    if my_pending_jobs and not request.user.is_anonymous():
        template_name = "jobs/my_pending_jobs.html"
        jobs = jobs.filter(
            creator_username=request.user.username,
            status_detail__contains='pending'
        )

    jobs = jobs.order_by('status_detail', 'list_type', '-post_dt')

    EventLog.objects.log()

    return render_to_response(
        template_name,
        {'jobs': jobs, 'form': form},
        context_instance=RequestContext(request)
    )
Пример #51
0
    def get_parent(self, context):
        if self.parent_name_expr:
            self.parent_name = self.parent_name_expr.resolve(context)
        parent = unicode(self.parent_name)

        if not parent:
            error_msg = "Invalid template name in 'extends' tag: %r." % parent
            if self.parent_name_expr:
                error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token
            raise TemplateSyntaxError(_(error_msg))
        if hasattr(parent, 'render'):
            return parent  # parent is a Template object
        theme = context.get('THEME', get_setting('module', 'theme_editor', 'theme'))
        theme_template = get_theme_template(parent, theme=theme)
        try:
            template = get_template(theme_template)
        except TemplateDoesNotExist:
            #to be sure that we not are loading the active theme's template
            template = get_default_template(parent)
        return template
Пример #52
0
def generate_admin_email_body(entry, form_for_form):
    """
        Generates the email body so that is readable
    """
    context = Context()
    site_url = get_setting('site', 'global', 'siteurl')
    template = get_template('forms/admin_email_content.html')

    # fields to loop through in the template
    context['fields'] = entry.entry_fields()
    # media_url necessary for file upload fields
    context['site_url'] = site_url
    context['media_url'] = site_url + settings.MEDIA_URL
    # form details to show in the email
    context['form'] = entry.form
    context['entry'] = entry
    context['custom_price'] = form_for_form.cleaned_data.get('custom_price')
    output = template.render(context)

    return output
Пример #53
0
def search(request, template_name="news/search.html"):
    query = request.GET.get('q', None)

    if get_setting('site', 'global', 'searchindex') and query:
        news = News.objects.search(query, user=request.user)
        # use order (existing for all modules) for sorting cause the current
        # haystack + whoosh cannot sort by release_dt correctly
        news = news.order_by('-order')
    else:
        filters = get_query_filters(request.user, 'news.view_news')
        news = News.objects.filter(filters).distinct()
        news = news.order_by('-release_dt')

    if not has_perm(request.user, 'news.view_news'):
        news = news.filter(release_dt_local__lte=datetime.now())

    EventLog.objects.log()

    return render_to_response(template_name, {'search_news': news},
                              context_instance=RequestContext(request))
Пример #54
0
def new(request, template_name="dashboard/new.html"):

    if get_setting('module', 'dashboard', 'themeredirect'):
        redirect_setting = Setting.objects.get(scope_category='dashboard',
                                               name='themeredirect')
        redirect_setting.set_value(False)
        redirect_setting.save()
        return redirect('tendenci.apps.theme_editor.views.theme_picker')

    profile_redirect = get_setting('site', 'global', 'profile_redirect')
    if profile_redirect and profile_redirect != '/dashboard' and not request.user.profile.is_superuser:
        if "<username>" in profile_redirect:
            profile_redirect = profile_redirect.replace("<username>", request.user.username)
        return redirect(profile_redirect)

    # self signup  free trial version
    has_paid = True
    activate_url = ''
    expired = False
    expiration_dt = ''
    if get_setting('site', 'developer', 'partner') == 'Self-Signup' \
             and  get_setting('site', 'developer', 'freepaid') == 'free':
        has_paid = False
        activate_url = get_setting('site', 'developer', 'siteactivatepaymenturl')
        site_create_dt = get_setting('site', 'developer', 'sitecreatedt')
        
        if site_create_dt:
            site_create_dt = parser.parse(site_create_dt)
        else:
            # find the site create date in user's table
            u = User.objects.get(pk=1)
            site_create_dt = u.date_joined
            
        expiration_dt = site_create_dt + timedelta(days=30)
            
        now = datetime.now()
        if now >= expiration_dt:
            expired = True

    statistics = DashboardStatType.objects.filter(displayed=True)

    EventLog.objects.log()
    return render_to_response(template_name, {
        'has_paid': has_paid,
        'activate_url': activate_url,
        'expired': expired,
        'expiration_dt': expiration_dt,
        'statistics': statistics,
    }, context_instance=RequestContext(request))
Пример #55
0
def generate_admin_email_body(entry, form_for_form):
    """
        Generates the email body so that is readable
    """
    context = Context()
    site_url = get_setting('site', 'global', 'siteurl')

    if site_url[-1:] == "/":
        site_url = site_url[:-1]
    template = get_template('forms/admin_email_content.html')
    
    # fields to loop through in the template
    context['fields'] = entry.fields.all()
    # media_url necessary for file upload fields
    context['media_url'] = site_url + settings.MEDIA_URL
    # form details to show in the email
    context['form'] = entry.form
    output = template.render(context)

    return output
Пример #56
0
    def delete(self, *args, **kwargs):
        # Related objects
        # Import related objects here to prevent circular references
        from tendenci.apps.pages.models import Page
        from tendenci.addons.events.models import Event
        from tendenci.apps.stories.models import Story
        pages = Page.objects.filter(header_image=self.pk)
        events = Event.objects.filter(image=self.pk)
        stories = Story.objects.filter(image=self.pk)
        # Set foreign key of related objects to None
        for page in pages:
            page.header_image = None
            page.save()
        for event in events:
            event.image = None
            event.save()
        for story in stories:
            story.image = None
            story.save()

        # roll back the transaction to fix the error for postgresql
        #"current transaction is aborted, commands ignored until
        # end of transaction block"
        connection._rollback()

        # send notification to administrator(s) and module recipient(s)
        recipients = get_notice_recipients('module', 'files', 'filerecipients')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        if recipients and notification:
            notification.send_emails(
                recipients, 'file_deleted', {
                    'object': self,
                    'author': self.owner.get_full_name() or self.owner,
                    'SITE_GLOBAL_SITEDISPLAYNAME': site_display_name,
                })

        # delete actual file; do not save() self.instance
        self.file.delete(save=False)

        # delete database record
        super(File, self).delete(*args, **kwargs)
Пример #57
0
 def __init__(self):
     self.site_display_name = get_setting('site', 'global', 'sitedisplayname')
     self.site_contact_name = get_setting('site', 'global', 'sitecontactname')
     self.site_contact_email = get_setting('site', 'global', 'sitecontactemail')
     self.reply_to_email = get_setting('module', 'payments', 'paymentrecipients')
     if not self.reply_to_email:
         self.reply_to_email = self.site_contact_email
     self.site_url = get_setting('site', 'global', 'siteurl')
 
     self.email = Email()
     self.email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
     self.email.sender_display = self.site_display_name
     self.email.reply_to = self.reply_to_email
     
     self.admin_emails = self.get_admin_emails() 
Пример #58
0
 def __init__(self, *args, **kwargs):
     self.pricings = kwargs.pop('pricings')
     self.form_index = kwargs.pop('form_index', None)
     
     super(RegistrantForm, self).__init__(*args, **kwargs)
     
     # make the fields in the subsequent forms as not required
     if self.form_index and self.form_index > 0:
         for key in self.fields.keys():
             self.fields[key].required = False
     
     # initialize pricing options and reg_set field
     self.fields['pricing'] = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=self.pricings)
     
     allow_memberid = get_setting('module', 'events', 'memberidpricing')
     if not allow_memberid:
         self.fields.pop('memberid')
     
     # initialize internal variables
     self.price = Decimal('0.00')
     self.saved_data = {}
Пример #59
0
    def handle(self, *args, **options):
        from tendenci.apps.pages.models import Page
        from tendenci.core.site_settings.utils import get_setting

        self.SITE_URL = get_setting('site', 'global', 'siteurl')

        for page in Page.objects.all():

            soup = BeautifulSoup(page.content)

            links = soup.findAll('a')
            # images = soup.findAll('img')

            broken_links = self.get_broken_links(links)
            # broken_images = self.get_broken_images(images)

            # print page.slug,
            # print 'images', '%s/%s' % (len(images), len(broken_images)),
            # print 'links', '%s/%s' % (len(links), len(broken_links)), broken_links

            print page.slug, broken_links
Пример #60
0
def fb_like_button_iframe(url, show_faces='false', width=400, height=40):
    from tendenci.core.site_settings.utils import get_setting
    site_url = get_setting('site', 'global', 'siteurl')
    url = '%s%s' % (site_url,url)
    if show_faces.lower() == 'true':
        show_faces = 'true'
    else:
        show_faces = 'false'
    try:
        width = int(width) 
    except:
        width = 400
    try:
        height = int(height) 
    except:
        height = 400
        
    return {'url': url, 
            'width': width,
            'height': height,
            'show_faces':show_faces}