예제 #1
0
def group_add_edit(request, group_slug=None,
                   form_class=GroupForm,
                   template_name="user_groups/add_edit.html"):
    add, edit = False, False
    if group_slug:
        group = get_object_or_404(Group, slug=group_slug)

        if not has_perm(request.user,'user_groups.change_group',group):
            raise Http403
        title = _("Edit Group")
        edit = True
    else:
        group = None
        if not has_perm(request.user,'user_groups.add_group'):raise Http403
        title = _("Add Group")
        add = True

    if request.method == 'POST':
        if edit:
            form = form_class(request.POST, instance=group, user=request.user)
        else:
            form = form_class(request.POST, user=request.user)
        if form.is_valid():
            group = form.save(commit=False)
            if not group.id:
                group.creator = request.user
                group.creator_username = request.user.username

            # set up user permission
            group.allow_user_view, group.allow_user_edit = form.cleaned_data['user_perms']

            group.owner =  request.user
            group.owner_username = request.user.username
            group = form.save()

            if add:
                # send notification to administrators
                recipients = get_notice_recipients('module', 'groups', 'grouprecipients')
                if recipients:
                    if notification:
                        extra_context = {
                            'object': group,
                            'request': request,
                        }
                        notification.send_emails(recipients,'group_added', extra_context)

            EventLog.objects.log(instance=group)

            return HttpResponseRedirect(group.get_absolute_url())
    else:
        if edit:
            form = form_class(instance=group, user=request.user)
        else:
            form = form_class(user=request.user)

    return render_to_response(template_name, {'form':form, 'titie':title, 'group':group}, context_instance=RequestContext(request))
예제 #2
0
파일: views.py 프로젝트: ediaz1/tendenci
def pending(request, template_name="jobs/pending.html"):
    can_view_jobs = has_perm(request.user, 'jobs.view_job')
    can_change_jobs = has_perm(request.user, 'jobs.change_job')

    if not all([can_view_jobs, can_change_jobs]):
        raise Http403

    EventLog.objects.log()
    jobs = Job.objects.filter(status_detail__contains='pending')
    return render_to_response(template_name, {'jobs': jobs},
            context_instance=RequestContext(request))
예제 #3
0
def pending(request, template_name="directories/pending.html"):
    can_view_directories = has_perm(request.user, 'directories.view_directory')
    can_change_directories = has_perm(request.user, 'directories.change_directory')

    if not all([can_view_directories, can_change_directories]):
        raise Http403

    directories = Directory.objects.filter(status_detail__contains='pending')
    EventLog.objects.log()

    return render_to_response(template_name, {'directories': directories},
            context_instance=RequestContext(request))
예제 #4
0
파일: views.py 프로젝트: BIGGANI/tendenci
def delete(request, id, template_name="committees/delete.html"):
    committee = get_object_or_404(Committee, pk=id)

    if not has_perm(request.user, 'committees.delete_committee'):
        raise Http403

    if request.method == "POST":
        EventLog.objects.log(instance=committee)
        messages.add_message(request, messages.SUCCESS, 'Successfully deleted %s' % committee)

        # send notification to administrators
        recipients = get_notice_recipients('module', 'committees', 'committeerecipients')
        if recipients:
            if notification:
                extra_context = {
                    'object': committee,
                    'request': request,
                }
                notification.send_emails(recipients, 'committee_deleted', extra_context)

        committee.delete()
        return HttpResponseRedirect(reverse('committees.search'))

    return render_to_response(template_name, {'committee': committee},
        context_instance=RequestContext(request))
예제 #5
0
파일: views.py 프로젝트: ediaz1/tendenci
def pricing_add(request, form_class=JobPricingForm,
                    template_name="jobs/pricing-add.html"):

    if has_perm(request.user, 'jobs.add_jobpricing'):
        if request.method == "POST":
            form = form_class(request.POST)
            if form.is_valid():
                job_pricing = form.save(commit=False)
                job_pricing.status = 1
                job_pricing.save(request.user)

                EventLog.objects.log(instance=job_pricing)

                if "_popup" in request.REQUEST:
                    return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % (escape(job_pricing.pk), escape(job_pricing)))

                return HttpResponseRedirect(
                    reverse('job_pricing.view', args=[job_pricing.id]))
        else:
            form = form_class()

        if "_popup" in request.REQUEST:
            template_name="jobs/pricing-add-popup.html"

        return render_to_response(template_name, {'form': form},
            context_instance=RequestContext(request))
    else:
        raise Http403
예제 #6
0
파일: views.py 프로젝트: BIGGANI/tendenci
def detail(request, slug, template_name="committees/detail.html"):
    committee = get_object_or_404(Committee, slug=slug)

    if has_perm(request.user, 'committees.view_committee', committee):
        EventLog.objects.log(instance=committee)
        officers = committee.officers()

        #has_group_view_permission is True if there is at least one
        #group where the user is a member that has a view_committee permission.
        has_group_view_permission = False
        #Check user for group view permissions
        if request.user.is_authenticated():
            groups = request.user.group_set.all()
            perms = has_groups_perms(committee).filter(group__in=groups)
            for perm in perms:
                #Check if permission has view committee permission
                has_group_view_permission |= perm.codename == 'view_committee'
                if has_group_view_permission:
                    break

        filters = get_query_filters(request.user, 'files.view_file')
        files = File.objects.filter(filters).filter(group=committee.group).distinct()

        return render_to_response(template_name,
            {
                'committee': committee,
                'officers': officers,
                'files': files,
                'has_group_view_permission': has_group_view_permission,
            },
            context_instance=RequestContext(request))
    else:
        raise Http403
예제 #7
0
파일: views.py 프로젝트: BIGGANI/tendenci
def edit_meta(request, id, form_class=MetaForm, template_name="committees/edit-meta.html"):
    """
    Return committee that allows you to edit meta-html information.
    """

    # check permission
    committee = get_object_or_404(Committee, pk=id)
    if not has_perm(request.user, 'committees.change_committee', committee):
        raise Http403

    EventLog.objects.log(instance=committee)

    defaults = {
        'title': committee.get_title(),
        'description': committee.get_description(),
        'keywords': committee.get_keywords(),
        'canonical_url': committee.get_canonical_url(),
    }
    committee.meta = MetaTags(**defaults)

    if request.method == "POST":
        form = form_class(request.POST, instance=committee.meta)
        if form.is_valid():
            committee.meta = form.save()  # save meta
            committee.save()  # save relationship

            messages.add_message(request, messages.SUCCESS, 'Successfully updated meta for %s' % committee)

            return HttpResponseRedirect(reverse('committees.detail', args=[committee.slug]))
    else:
        form = form_class(instance=committee.meta)

    return render_to_response(template_name, {'committee': committee, 'form': form},
        context_instance=RequestContext(request))
예제 #8
0
파일: views.py 프로젝트: tendenci/tendenci
def campaign_delete(request, campaign_id, template_name="campaign_monitor/campaigns/delete.html"):
    campaign = get_object_or_404(Campaign, campaign_id=campaign_id)

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

    if request.method == "POST":

        try:
            CSC(auth=auth, campaign_id=campaign.campaign_id).delete()
        except BadRequest as e:
            msg_string = 'Bad Request %s: %s' % (e.data.Code, e.data.Message)
            messages.add_message(request, messages.ERROR, _(msg_string))
            return redirect(campaign)
        except Exception as e:
            msg_string = 'Error: %s' % e
            messages.add_message(request, messages.ERROR, _(msg_string))
            return redirect(campaign)

        campaign.delete()
        messages.add_message(request, messages.SUCCESS, _('Successfully deleted campaign.'))
        return redirect("campaign_monitor.campaign_index")

    return render_to_resp(request=request, template_name=template_name,
            context={'campaign': campaign})
예제 #9
0
def tinymce_fb(request, template_name="files/templates/tinymce_fb.html"):
    """
    Get a list of files (images) for tinymce file browser.
    """
    query = u''
    try:
        page_num = int(request.GET.get('page', 1))
    except:
        page_num = 1

    form = FileSearchMinForm(request.GET)
    if form.is_valid():
        query = form.cleaned_data.get('q', '')
    filters = get_query_filters(request.user, 'files.view_file')
    files = File.objects.filter(filters).distinct().order_by('-create_dt')
    type = request.GET.get('type', '')
    if type == 'image':
        files = files.filter(f_type='image')
    elif type == 'media':
        files = files.filter(f_type='video')
    if query:
        files = files.filter(Q(file__icontains=query)|
                             Q(name__icontains=query))
    paginator = Paginator(files, 10)
    files = paginator.page(page_num)

    return render_to_response(
        template_name, {
            "files": files,
            'page_num': page_num,
            'page_range': paginator.page_range,
            'csrf_token': csrf_get_token(request),
            'can_upload_file': has_perm(request.user, 'files.add_file')
        }, context_instance=RequestContext(request))
예제 #10
0
def edit_meta(request, id, form_class=MetaForm, template_name="directories/edit-meta.html"):
    directory = get_object_or_404(Directory, pk=id)

    if not has_perm(request.user, 'directories.change_directory', directory):
        raise Http403

    defaults = {
        'title': directory.get_title(),
        'description': directory.get_description(),
        'keywords': directory.get_keywords(),
        'canonical_url': directory.get_canonical_url(),
    }
    directory.meta = MetaTags(**defaults)

    if request.method == "POST":
        form = form_class(request.POST, instance=directory.meta)
        if form.is_valid():
            directory.meta = form.save() # save meta
            directory.save() # save relationship
            msg_string = 'Successfully updated meta for %s' % directory
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            return HttpResponseRedirect(reverse('directory', args=[directory.slug]))
    else:
        form = form_class(instance=directory.meta)

    return render_to_response(template_name, {'directory': directory, 'form':form},
        context_instance=RequestContext(request))
예제 #11
0
def edit(request, id, form_class=DirectoryForm, template_name="directories/edit.html"):
    directory = get_object_or_404(Directory, pk=id)

    if not has_perm(request.user,'directories.change_directory', directory):
        raise Http403

    form = form_class(request.POST or None, request.FILES or None,
                      instance=directory,
                      user=request.user)

    del form.fields['payment_method']
    if not request.user.profile.is_superuser:
        del form.fields['pricing']
        del form.fields['list_type']

    if request.method == "POST":
        if form.is_valid():
            directory = form.save(commit=False)

            if directory.logo:
                try:
                    directory.logo.file.seek(0)
                except IOError:
                    directory.logo = None
            # update all permissions and save the model
            directory = update_perms_and_save(request, form, directory)
            msg_string = 'Successfully updated %s' % directory
            messages.add_message(request, messages.SUCCESS, _(msg_string))

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


    return render_to_response(template_name, {'directory': directory, 'form':form},
        context_instance=RequestContext(request))
예제 #12
0
파일: views.py 프로젝트: goetzk/tendenci
def edit_meta(request, id, form_class=MetaForm, template_name="resumes/edit-meta.html"):
    # check permission
    resume = get_object_or_404(Resume, pk=id)
    if not has_perm(request.user,'resumes.change_resume',resume):
        raise Http403

    defaults = {
        'title': resume.get_title(),
        'description': resume.get_description(),
        'keywords': resume.get_keywords(),
        'canonical_url': resume.get_canonical_url(),
    }
    resume.meta = MetaTags(**defaults)

    if request.method == "POST":
        form = form_class(request.POST, instance=resume.meta)
        if form.is_valid():
            resume.meta = form.save() # save meta
            resume.save() # save relationship

            messages.add_message(request, messages.SUCCESS, _('Successfully updated meta for %(r)s' % { 'r':resume}))

            return HttpResponseRedirect(reverse('resume', args=[resume.slug]))
    else:
        form = form_class(instance=resume.meta)

    return render_to_response(template_name, {'resume': resume, 'form':form},
        context_instance=RequestContext(request))
예제 #13
0
파일: views.py 프로젝트: ZHW123/tendenci
def mark_as_paid(request, id, template_name="invoices/mark-as-paid.html"):
    """
    Makes a payment-record with a specified date/time
    payment method and payment amount.
    """
    invoice = get_object_or_404(Invoice, pk=id)

    if not has_perm(request.user, "payments.change_payment"):
        raise Http403

    if request.method == "POST":
        form = MarkAsPaidForm(request.POST)

        if form.is_valid():

            # make payment record
            payment = form.save(user=request.user, invoice=invoice, commit=False)

            payment = update_perms_and_save(request, form, payment)

            # update invoice; make accounting entries
            action_taken = invoice.make_payment(payment.creator, payment.amount)
            if action_taken:
                EventLog.objects.log(instance=invoice)
                messages.add_message(request, messages.SUCCESS, _("Payment successfully made"))

            return redirect(invoice)

    else:
        form = MarkAsPaidForm(initial={"amount": invoice.balance, "submit_dt": datetime.now()})

    return render_to_response(
        template_name, {"invoice": invoice, "form": form}, context_instance=RequestContext(request)
    )
예제 #14
0
파일: views.py 프로젝트: tendenci/tendenci
def detail(request, id, template_name="discounts/view.html"):
    discount = get_object_or_404(Discount, id=id)

    if not has_perm(request.user, 'discounts.view_discount', discount):
        raise Http403

    registrations = Registration.objects.filter(invoice__discount_code=discount.discount_code)
    registrant_list = []
    for registration in registrations:
        registrant_list += registration.registrant_set.filter(discount_amount__gt=0)

    memberships = MembershipSet.objects.filter(invoice__discount_code=discount.discount_code)
    membership_list = []
    for membership in memberships:
        count = DiscountUse.objects.filter(invoice=membership.invoice).count()
        membership_list += membership.membershipdefault_set.all()[:count]

    EventLog.objects.log(instance=discount)

    return render_to_resp(
        request=request, template_name=template_name,
        context={'discount':discount,
         'registrant_list':registrant_list,
         'membership_list':membership_list}
    )
예제 #15
0
파일: views.py 프로젝트: BIGGANI/tendenci
def upload_file(request):

    if not has_perm(request.user, 'theme_editor.add_themefileversion'):
        raise Http403

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)

        if form.is_valid():
            upload = request.FILES['upload']
            file_dir = form.cleaned_data['file_dir']
            overwrite = form.cleaned_data['overwrite']
            full_filename = os.path.join(file_dir, upload.name)

            if os.path.isfile(full_filename) and not overwrite:
                msg_string = 'File %s already exists in that folder.' % (upload.name)
                messages.add_message(request, messages.ERROR, _(msg_string))
                return HttpResponse('invalid', content_type="text/plain")
            else:
                handle_uploaded_file(upload, file_dir)
                msg_string = 'Successfully uploaded %s.' % (upload.name)
                messages.add_message(request, messages.SUCCESS, _(msg_string))

                EventLog.objects.log()
                # returning a response of "ok" (flash likes this)
                # response is for flash, not humans
                return HttpResponse('valid', content_type="text/plain")

        else:  # not valid
            messages.add_message(request, messages.ERROR, form.errors)
            return HttpResponse('invalid', content_type="text/plain")
    else:
        form = UploadForm()

    return HttpResponseRedirect('/theme-editor/editor/')
예제 #16
0
    def approve(self, request, pk):
        """
        Approve membership and redirect to
        membershipdefault change page.
        """
        if not has_perm(request.user, 'memberships.approve_membershipdefault'):
            raise Http403

        m = get_object_or_404(MembershipDefault, pk=pk)
        m.approve(request_user=request.user)
        m.send_email(request, 'approve')
        if m.corporate_membership_id:
            # notify corp reps
            m.email_corp_reps(request)

        messages.add_message(
            request,
            messages.SUCCESS,
            _('Successfully Approved')
        )

        return redirect(reverse(
            'admin:memberships_membershipdefault_change',
            args=[pk],
        ))
예제 #17
0
파일: views.py 프로젝트: goetzk/tendenci
def edit_meta(request, id, form_class=MetaForm, template_name="news/edit-meta.html"):
    # check permission
    news = get_object_or_404(News, pk=id)
    if not has_perm(request.user, 'news.change_news', news):
        raise Http403

    defaults = {
        'title': news.get_title(),
        'description': news.get_description(),
        'keywords': news.get_keywords(),
        'canonical_url': news.get_canonical_url(),
    }
    news.meta = MetaTags(**defaults)

    if request.method == "POST":
        form = form_class(request.POST, instance=news.meta)
        if form.is_valid():
            news.meta = form.save()  # save meta
            news.save()  # save relationship
            msg_string = 'Successfully updated meta for %s' % unicode(news)
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            return HttpResponseRedirect(reverse('news.detail', args=[news.slug]))
    else:
        form = form_class(instance=news.meta)

    return render_to_response(template_name, {'news': news, 'form': form},
        context_instance=RequestContext(request))
예제 #18
0
def delete(request, id, template_name="directories/delete.html"):
    directory = get_object_or_404(Directory, pk=id)

    if has_perm(request.user,'directories.delete_directory'):
        if request.method == "POST":
            msg_string = 'Successfully deleted %s' % directory
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            # send notification to administrators
            recipients = get_notice_recipients('module', 'directories', 'directoryrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': directory,
                        'request': request,
                    }
                    notification.send_emails(recipients,'directory_deleted', extra_context)

            directory.delete()

            return HttpResponseRedirect(reverse('directory.search'))

        return render_to_response(template_name, {'directory': directory},
            context_instance=RequestContext(request))
    else:
        raise Http403
예제 #19
0
파일: views.py 프로젝트: tendenci/tendenci
def add(request, form_class=FormForm, template_name="forms/add.html"):
    if not has_perm(request.user,'forms.add_form'):
        raise Http403

    PricingFormSet = inlineformset_factory(Form, Pricing, form=PricingForm, extra=2, can_delete=False)

    formset = PricingFormSet()
    if request.method == "POST":
        form = form_class(request.POST, user=request.user)
        if form.is_valid():
            form_instance = form.save(commit=False)
            # save form and associated pricings
            form_instance = update_perms_and_save(request, form, form_instance)
            formset = PricingFormSet(request.POST, instance=form_instance)
            if formset.is_valid():
                # update_perms_and_save does not appear to consider ManyToManyFields
                for method in form.cleaned_data['payment_methods']:
                    form_instance.payment_methods.add(method)

                formset.save()

                messages.add_message(request, messages.SUCCESS, _('Successfully added %(f)s' % {'f':form_instance}))
                return HttpResponseRedirect(reverse('form_field_update', args=[form_instance.pk]))
    else:
        form = form_class(user=request.user)

    return render_to_resp(request=request, template_name=template_name, context={
        'form':form,
        'formset': formset,
    })
예제 #20
0
파일: views.py 프로젝트: BIGGANI/tendenci
def single_setting(request, scope, scope_category, name, template_name="site_settings/list.html"):
    if not has_perm(request.user,'site_settings.change_setting'):
        raise Http403

    settings = Setting.objects.filter(scope=scope, scope_category=scope_category, name=name).order_by('label')
    if not settings:
        raise Http404

    if request.method == 'POST':
        form = build_settings_form(request.user, settings)(request.POST, request.FILES)
        if form.is_valid():
            # this save method is overriden in the forms.py
            form.save()
            try:
                if form.cleaned_data['theme']:
                    from django.core.management import call_command
                    call_command('hide_settings', 'theme')
                    call_command('update_settings', 'themes.%s' % form.cleaned_data['theme'].lstrip())
            except:
                pass

            EventLog.objects.log()
            msg_string = 'Successfully saved %s settings' % name.replace('_',' ').title()
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            redirect_to = request.REQUEST.get('next', '')
            if redirect_to:
                return HttpResponseRedirect(redirect_to)

    else:
        form = build_settings_form(request.user, settings)()

    return render_to_response(template_name, {'form': form }, context_instance=RequestContext(request))
예제 #21
0
파일: views.py 프로젝트: goetzk/tendenci
def delete(request, id, template_name="news/delete.html"):
    news = get_object_or_404(News, pk=id)

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

    if request.method == "POST":
        msg_string = 'Successfully deleted %s' % unicode(news)
        messages.add_message(request, messages.SUCCESS, _(msg_string))

        # send notification to administrators
        recipients = get_notice_recipients('module', 'news', 'newsrecipients')
        if recipients:
            if notification:
                extra_context = {
                    'object': news,
                    'request': request,
                }
                notification.send_emails(recipients, 'news_deleted', extra_context)

        news.delete()
        return HttpResponseRedirect(reverse('news.search'))

    return render_to_response(template_name, {'news': news},
        context_instance=RequestContext(request))
예제 #22
0
파일: views.py 프로젝트: BIGGANI/tendenci
def edit(request, id, form_class=LocationForm, template_name="locations/edit.html"):
    location = get_object_or_404(Location, pk=id)

    if has_perm(request.user,'locations.change_location',location):
        if request.method == "POST":
            form = form_class(request.POST, request.FILES, instance=location, user=request.user)
            if form.is_valid():
                location = form.save(commit=False)

                # update all permissions and save the model
                location = update_perms_and_save(request, form, location)

                if 'photo_upload' in form.cleaned_data:
                    photo = form.cleaned_data['photo_upload']
                    if photo:
                        location.save(photo=photo)
                msg_string = 'Successfully updated %s' % location
                messages.add_message(request, messages.SUCCESS, _(msg_string))

                return HttpResponseRedirect(reverse('location', args=[location.slug]))
        else:
            form = form_class(instance=location, user=request.user)

        return render_to_response(template_name, {'location': location, 'form':form},
            context_instance=RequestContext(request))
    else:
        raise Http403
예제 #23
0
def group_members_export(request, group_slug, export_target='all'):
    """
    Export members for a specific group
    """
    group = get_object_or_404(Group, slug=group_slug)
    # if they can edit it, they can export it
    if not has_perm(request.user,'user_groups.change_group', group):
        raise Http403

    identifier = '%s_%s' % (int(ttime.time()), request.user.id)
    file_dir = 'export/groups/'
    temp_export_path = '%sgroup_%d_%s_%s_temp.csv' % (file_dir,
                                             group.id,
                                             export_target,
                                            identifier)
    default_storage.save(temp_export_path, ContentFile(''))
    # start the process
    subprocess.Popen(["python", "manage.py",
                  "group_members_export",
                  '--group_id=%d' % group.id,
                  '--export_target=%s' % export_target,
                  '--identifier=%s' % identifier,
                  '--user_id=%s' % request.user.id])
    # log an event
    EventLog.objects.log()
    return redirect(reverse('group.members_export_status',
                     args=[group.slug, export_target, identifier]))
예제 #24
0
파일: views.py 프로젝트: goetzk/tendenci
def detail(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 request.user.profile.is_superuser):
        raise Http403

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

    #check for release date if it's in the future or not
    if not news.is_released:
        if not request.user.is_authenticated():
            raise Http404

        if not request.user.profile.is_superuser:
            raise Http403

    EventLog.objects.log(instance=news)

    return render_to_response(template_name, {'news': news},
        context_instance=RequestContext(request))
예제 #25
0
파일: views.py 프로젝트: ZHW123/tendenci
def generate(request):
    """
    Newsletter generator form
    """
    if not has_perm(request.user, "newsletters.add_newsletter"):
        raise Http403

    if request.method == "POST":
        form = GenerateForm(request.POST)
        if form.is_valid():
            template = form.cleaned_data["template"]

            html_url = [
                reverse("newsletter.template_render", args=[template.template_id]),
                u"?jump_links=%s" % form.cleaned_data.get("jump_links"),
                "&events=%s" % form.cleaned_data.get("events"),
                "&events_type=%s" % form.cleaned_data.get("events_type"),
                "&event_start_dt=%s" % form.cleaned_data.get("event_start_dt", u""),
                "&event_end_dt=%s" % form.cleaned_data.get("event_end_dt", u""),
                "&articles=%s" % form.cleaned_data.get("articles", u""),
                "&articles_days=%s" % form.cleaned_data.get("articles_days", u""),
                "&news=%s" % form.cleaned_data.get("news", u""),
                "&news_days=%s" % form.cleaned_data.get("news_days", u""),
                "&jobs=%s" % form.cleaned_data.get("jobs", u""),
                "&jobs_days=%s" % form.cleaned_data.get("jobs_days", u""),
                "&pages=%s" % form.cleaned_data.get("pages", u""),
                "&pages_days=%s" % form.cleaned_data.get("pages_days", u""),
            ]

            return redirect("".join(html_url))

    form = GenerateForm()

    return render(request, "newsletters/generate.html", {"form": form})
예제 #26
0
파일: views.py 프로젝트: BIGGANI/tendenci
def delete(request, id, template_name="studygroups/delete.html"):
    study_group = get_object_or_404(StudyGroup, pk=id)

    if not has_perm(request.user, 'studygroups.delete_studygroup'):
        raise Http403

    if request.method == "POST":
        EventLog.objects.log(instance=study_group)
        messages.add_message(request, messages.SUCCESS, 'Successfully deleted %s' % study_group)

        # send notification to administrators
        recipients = get_notice_recipients('module', 'studygroups', 'studygrouprecipients')
        if recipients:
            if notification:
                extra_context = {
                    'object': study_group,
                    'request': request,
                }
                notification.send_emails(recipients, 'studygroup_deleted', extra_context)

        study_group.delete()
        return HttpResponseRedirect(reverse('studygroups.search'))

    return render_to_response(template_name, {'study_group': study_group},
        context_instance=RequestContext(request))
예제 #27
0
파일: views.py 프로젝트: tendenci/tendenci
def add(request, form_class=LocationForm, template_name="locations/add.html"):
    if has_perm(request.user,'locations.add_location'):
        if request.method == "POST":
            form = form_class(request.POST, request.FILES, user=request.user)
            if form.is_valid():
                location = form.save(commit=False)

                # update all permissions and save the model
                location = update_perms_and_save(request, form, location)

                if 'photo_upload' in form.cleaned_data:
                    photo = form.cleaned_data['photo_upload']
                    if photo:
                        location.save(photo=photo)
                msg_string = 'Successfully added %s' % location
                messages.add_message(request, messages.SUCCESS, _(msg_string))

                return HttpResponseRedirect(reverse('location', args=[location.slug]))
        else:
            form = form_class(user=request.user)

        return render_to_resp(request=request, template_name=template_name,
            context={'form':form})
    else:
        raise Http403
예제 #28
0
파일: views.py 프로젝트: tendenci/tendenci
def entries_export(request, id, include_files=False):
    form_instance = get_object_or_404(Form, pk=id)

    # check permission
    if not has_perm(request.user,'forms.change_form',form_instance):
        raise Http403

    EventLog.objects.log(instance=form_instance)

    entries = form_instance.entries.all()

    if entries:
        if not settings.CELERY_IS_ACTIVE:
            task = FormEntriesExportTask()
            response = task.run(form_instance, entries, include_files)
            return response
        else:
            task = FormEntriesExportTask.delay(form_instance, entries, include_files)
            task_id = task.task_id
            return redirect('form_entries_export_status', task_id)
    else:
        # blank csv document
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="export_entries_%d.csv"' % time.time()
        import six
        delimiter = ','
        if six.PY2:
            # string required because unicode_literals is imported at top
            delimiter = delimiter.encode('utf-8')
        csv.writer(response, delimiter=delimiter)

    return response
예제 #29
0
파일: mixins.py 프로젝트: BIGGANI/tendenci
    def dispatch(self, request, *args, **kwargs):
        obj = self.get_obj()
        perm = self.get_newsletter_permission()
        if not has_perm(request.user, perm, obj=obj):
            raise Http403

        return super(NewsletterPermissionMixin, self).dispatch(request, *args, **kwargs)
예제 #30
0
파일: views.py 프로젝트: a2call/tendenci
def edit_meta(request, id, form_class=MetaForm, template_name="pages/edit-meta.html"):
    """
    Return page that allows you to edit meta-html information.
    """
    # check permission
    page = get_object_or_404(Page, pk=id)
    if not has_perm(request.user, "pages.change_page", page):
        raise Http403

    defaults = {
        "title": page.get_title(),
        "description": page.get_description(),
        "keywords": page.get_keywords(),
        "canonical_url": page.get_canonical_url(),
    }
    page.meta = MetaTags(**defaults)

    if request.method == "POST":
        form = form_class(request.POST, instance=page.meta)
        if form.is_valid():
            page.meta = form.save()  # save meta
            page.save()  # save relationship

            messages.add_message(
                request, messages.SUCCESS, _("Successfully updated meta for %(p)s" % {"p": unicode(page)})
            )

            return HttpResponseRedirect(reverse("page", args=[page.slug]))
    else:
        form = form_class(instance=page.meta)

    return render_to_response(template_name, {"page": page, "form": form}, context_instance=RequestContext(request))
예제 #31
0
def tinymce_fb(request, template_name="files/templates/tinymce_fb.html"):
    """
    Get a list of files (images) for tinymce file browser.
    """
    query = u''
    try:
        page_num = int(request.GET.get('page', 1))
    except:
        page_num = 1

    form = FileSearchMinForm(request.GET)
    if form.is_valid():
        query = form.cleaned_data.get('q', '')
    #filters = get_query_filters(request.user, 'files.view_file')
    files = File.objects.all()
    if not request.user.is_superuser:
        #  non-admin: show only those images uploaded by this user
        files = files.filter(Q(creator=request.user) | Q(owner=request.user))
    files = files.order_by('-create_dt')
    type = request.GET.get('type', '')
    if type == 'image':
        files = files.filter(f_type='image')
    elif type == 'media':
        files = files.filter(f_type='video')
    if query:
        files = files.filter(
            Q(file__icontains=query) | Q(name__icontains=query))
    paginator = Paginator(files, 10)
    files = paginator.page(page_num)

    return render_to_response(
        template_name, {
            "files": files,
            'q': query,
            'page_num': page_num,
            'page_range': paginator.page_range,
            'csrf_token': csrf_get_token(request),
            'can_upload_file': has_perm(request.user, 'files.add_file')
        },
        context_instance=RequestContext(request))
예제 #32
0
def edit(request, id, form_class=DirectoryForm, template_name="directories/edit.html"):
    directory = get_object_or_404(Directory, pk=id)

    if not (has_perm(request.user,'directories.change_directory', directory) \
            or directory.has_membership_with(request.user)):
        raise Http403

    if request.user.is_superuser:
        if not directory.activation_dt:
            # auto-populate activation_dt
            directory.activation_dt = datetime.now()

    form = form_class(request.POST or None, request.FILES or None,
                      instance=directory,
                      user=request.user)

    del form.fields['payment_method']
    if not request.user.profile.is_superuser:
        del form.fields['pricing']
        del form.fields['list_type']

    if request.method == "POST":
        if form.is_valid():
            directory = form.save(commit=False)

            if directory.logo:
                try:
                    directory.logo.file.seek(0)
                except IOError:
                    directory.logo = None
            # update all permissions and save the model
            directory = update_perms_and_save(request, form, directory)
            form.save_m2m()
            msg_string = 'Successfully updated %s' % directory
            messages.add_message(request, messages.SUCCESS, _(msg_string))

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

    return render_to_resp(request=request, template_name=template_name,
        context={'directory': directory, 'form':form})
예제 #33
0
파일: views.py 프로젝트: dkofiarmah/memba
def edit(request, id, form_class=StoryForm, template_name="stories/edit.html"):
    story = get_object_or_404(Story, pk=id)

    if has_perm(request.user, 'stories.change_story', story):
        if request.method == "POST":
            form = form_class(request.POST,
                              request.FILES,
                              instance=story,
                              user=request.user)
            if form.is_valid():
                story = form.save(commit=False)

                # save photo
                photo = form.cleaned_data['photo_upload']
                if photo:
                    story.save(photo=photo)

                story = update_perms_and_save(request, form, story)

                messages.add_message(
                    request, messages.SUCCESS,
                    _('Successfully updated %(str)s' %
                      {'str': unicode(story)}))

                redirect_to = request.REQUEST.get('next', '')
                if redirect_to:
                    return HttpResponseRedirect(redirect_to)
                else:
                    return redirect('story', id=story.pk)
        else:
            form = form_class(instance=story, user=request.user)

    else:
        raise Http403

    return render_to_response(template_name, {
        'story': story,
        'form': form
    },
                              context_instance=RequestContext(request))
예제 #34
0
파일: views.py 프로젝트: rob-hills/tendenci
def edit(request,
         id=None,
         form_class=HelpFileForm,
         template_name="help_files/edit.html"):
    help_file = get_object_or_404(HelpFile, pk=id)
    if has_perm(request.user, 'help_files.change_helpfile', help_file):
        if request.method == "POST":
            form = form_class(request.POST,
                              instance=help_file,
                              user=request.user)
            if form.is_valid():
                help_file = form.save(commit=False)

                # add all permissions and save the model
                help_file = update_perms_and_save(request, form, help_file)
                form.save_m2m()
                msg_string = 'Successfully edited %s' % help_file
                messages.add_message(request, messages.SUCCESS, _(msg_string))

                #                # send notification to administrator(s) and module recipient(s)
                #                recipients = get_notice_recipients('module', 'help_files', 'helpfilerecipients')
                #                # if recipients and notification:
                #                     notification.send_emails(recipients,'help_file_added', {
                #                         'object': help_file,
                #                         'request': request,
                #                     })

                return HttpResponseRedirect(
                    reverse('help_file.details', args=[help_file.slug]))
        else:
            form = form_class(instance=help_file, user=request.user)

        return render_to_resp(request=request,
                              template_name=template_name,
                              context={
                                  'help_file': help_file,
                                  'form': form
                              })
    else:
        raise Http403
예제 #35
0
def group_delete(request, id, template_name="user_groups/delete.html"):
    group = get_object_or_404(Group, pk=id)

    if not has_perm(request.user,'user_groups.delete_group',group): raise Http403

    if request.method == "POST":
        # send notification to administrators
        recipients = get_notice_recipients('module', 'groups', 'grouprecipients')
        if recipients:
            if notification:
                extra_context = {
                    'object': group,
                    'request': request,
                }
                notification.send_emails(recipients,'group_deleted', extra_context)

        EventLog.objects.log(instance=group)

        group.delete()
        return HttpResponseRedirect(reverse('group.search'))

    (deleted_objects, count, perms_needed, protected) = get_deleted_objects(
            [group], request.user)
    object_name = group.label or group.name

    if perms_needed or protected:
        title = _("Cannot delete %(name)s") % {"name": object_name}
    else:
        title = _("Are you sure?")

    return render_to_response(template_name,
            {'group':group,
             "title": title,
             "object_name": object_name,
             "deleted_objects": deleted_objects,
             "perms_lacking": perms_needed,
             "protected": protected,
             "opts": group._meta,
             },
        context_instance=RequestContext(request))
예제 #36
0
def generate(request):
    """
    Newsletter generator form
    """
    if not has_perm(request.user, 'newsletters.add_newsletter'):
        raise Http403

    if request.method == 'POST':
        form = GenerateForm(request.POST)
        if form.is_valid():
            template = form.cleaned_data['template']

            html_url = [
                reverse('newsletter.template_render',
                        args=[template.template_id]),
                u'?jump_links=%s' % form.cleaned_data.get('jump_links'),
                '&events=%s' % form.cleaned_data.get('events'),
                '&events_type=%s' % form.cleaned_data.get('events_type'),
                '&event_start_dt=%s' %
                form.cleaned_data.get('event_start_dt', u''),
                '&event_end_dt=%s' %
                form.cleaned_data.get('event_end_dt', u''),
                '&articles=%s' % form.cleaned_data.get('articles', u''),
                '&articles_days=%s' %
                form.cleaned_data.get('articles_days', u''),
                '&news=%s' % form.cleaned_data.get('news', u''),
                '&news_days=%s' % form.cleaned_data.get('news_days', u''),
                '&jobs=%s' % form.cleaned_data.get('jobs', u''),
                '&jobs_days=%s' % form.cleaned_data.get('jobs_days', u''),
                '&pages=%s' % form.cleaned_data.get('pages', u''),
                '&pages_days=%s' % form.cleaned_data.get('pages_days', u''),
            ]

            return redirect(''.join(html_url))

    form = GenerateForm()

    return render_to_resp(request=request,
                          template_name='newsletters/generate.html',
                          context={'form': form})
예제 #37
0
def edit(request, id, form_class=JobForm, template_name="jobs/edit.html", object_type=Job, success_redirect='job', job_change_perm='jobs.change_job'):
    job = get_object_or_404(object_type, pk=id)

    if not has_perm(request.user, job_change_perm, job):
        raise Http403

    form = form_class(request.POST or None,
                        instance=job,
                        user=request.user)

    # delete admin only fields for non-admin on edit - GJQ 8/25/2010
    if not request.user.profile.is_superuser:
        del form.fields['pricing']
        del form.fields['list_type']
        if 'activation_dt' in form.fields:
            del form.fields['activation_dt']
        if 'post_dt' in form.fields:
            del form.fields['post_dt']
        if 'expiration_dt' in form.fields:
            del form.fields['expiration_dt']
        if 'entity' in form.fields:
            del form.fields['entity']
    del form.fields['payment_method']

    if request.method == "POST":
        if form.is_valid():
            job = form.save(commit=False)

            job = update_perms_and_save(request, form, job)

            msg_string = u'Successfully updated {}'.format(str(job))
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            return HttpResponseRedirect(
                reverse(success_redirect, args=[job.slug]))

    return render_to_resp(request=request, template_name=template_name, context={
        'job': job,
        'form': form,
        })
예제 #38
0
def edit(request, id, set_id=0, form_class=PhotoEditForm, template_name="photos/edit.html"):
    """ edit photo view """
    # get photo
    photo = get_object_or_404(Image, id=id)
    set_id = int(set_id)

    # permissions
    if not has_perm(request.user,'photos.change_image',photo):
        raise Http403

    # get available photo sets
    photo_sets = PhotoSet.objects.all()

    if request.method == "POST":
        if request.POST["action"] == "update":
            form = form_class(request.POST, instance=photo, user=request.user)
            if form.is_valid():
                photo = form.save(commit=False)

                # update all permissions and save the model
                photo = update_perms_and_save(request, form, photo)

                messages.add_message(request, messages.SUCCESS, _("Successfully updated photo '%(title)s'" % {'title': unicode(photo)}) )
                if set_id:
                    return HttpResponseRedirect(reverse("photo", kwargs={"id": photo.id, "set_id": set_id}))
                else:
                    return HttpResponseRedirect(reverse("photo", kwargs={"id": photo.id}))
        else:
            form = form_class(instance=photo, user=request.user)

    else:
        form = form_class(instance=photo, user=request.user)

    return render_to_response(template_name, {
        "photo_form": form,
        "photo": photo,
        "photo_sets": photo_sets,
        "id": photo.id,
        "set_id": set_id,
    }, context_instance=RequestContext(request))
예제 #39
0
파일: views.py 프로젝트: chendong0444/ams
def edit_meta(request,
              id,
              form_class=MetaForm,
              template_name="pages/edit-meta.html"):
    """
    Return page that allows you to edit meta-html information.
    """
    # check permission
    page = get_object_or_404(Page, pk=id)
    if not has_perm(request.user, 'pages.change_page', page):
        raise Http403

    defaults = {
        'title': page.get_title(),
        'description': page.get_description(),
        'keywords': page.get_keywords(),
        'canonical_url': page.get_canonical_url(),
    }
    page.meta = MetaTags(**defaults)

    if request.method == "POST":
        form = form_class(request.POST, instance=page.meta)
        if form.is_valid():
            page.meta = form.save()  # save meta
            page.save()  # save relationship

            messages.add_message(
                request, messages.SUCCESS,
                _('Successfully updated meta for %(p)s' %
                  {'p': unicode(page)}))

            return HttpResponseRedirect(reverse('page', args=[page.slug]))
    else:
        form = form_class(instance=page.meta)

    return render_to_response(template_name, {
        'page': page,
        'form': form
    },
                              context_instance=RequestContext(request))
예제 #40
0
def pricing_delete(request,
                   id,
                   template_name="directories/pricing-delete.html"):
    directory_pricing = get_object_or_404(DirectoryPricing, pk=id)

    if not has_perm(request.user, 'directories.delete_directorypricing'):
        raise Http403

    if request.method == "POST":
        messages.add_message(request, messages.SUCCESS,
                             'Successfully deleted %s' % directory_pricing)

        #directory_pricing.delete()
        # soft delete
        directory_pricing.status = False
        directory_pricing.save()

        return HttpResponseRedirect(reverse('directory_pricing.search'))

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={'directory_pricing': directory_pricing})
예제 #41
0
def add(request, form_class=VideoFrontEndForm, template_name="videos/edit.html"):
    # check permission
    if not has_perm(request.user, 'videos.add_video'):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            video = form.save(commit=False)
            video.creator = request.user
            video.creator_username = request.user.username
            if not request.user.is_superuser:
                video.status_detail = 'pending'

            # update all permissions and save the model
            video = update_perms_and_save(request, form, video)
            form.save_m2m()

            msg_string = _(f'Successfully added {str(video)}')
            if not request.user.is_superuser:
                msg_string += _('... Pending on Admin approval.')
            messages.add_message(request, messages.SUCCESS, msg_string)
            
            # send notification to administrator(s) and module recipient(s)
            recipients = get_notice_recipients('module', 'videos', 'videorecipients')
            if recipients and notification:
                notification.send_emails(recipients, 'video_added', {
                    'object': video,
                    'request': request,
                })

            return HttpResponseRedirect(reverse('video.details', args=[video.slug]))
    else:
        form = form_class(user=request.user)

    return render_to_resp(request=request,
                          template_name=template_name,
        context={'form': form,
                 'edit_mode': False})
예제 #42
0
파일: views.py 프로젝트: iniForum/tendenci
def add(request, form_class=FormForm, template_name="forms/add.html"):
    if not has_perm(request.user, 'forms.add_form'):
        raise Http403

    PricingFormSet = inlineformset_factory(Form,
                                           Pricing,
                                           form=PricingForm,
                                           extra=2,
                                           can_delete=False)

    formset = PricingFormSet()
    if request.method == "POST":
        form = form_class(request.POST, user=request.user)
        if form.is_valid():
            form_instance = form.save(commit=False)
            # save form and associated pricings
            form_instance = update_perms_and_save(request, form, form_instance)
            formset = PricingFormSet(request.POST, instance=form_instance)
            if formset.is_valid():
                # update_perms_and_save does not appear to consider ManyToManyFields
                for method in form.cleaned_data['payment_methods']:
                    form_instance.payment_methods.add(method)

                formset.save()

                messages.add_message(
                    request, messages.SUCCESS,
                    _('Successfully added %(f)s' % {'f': form_instance}))
                return HttpResponseRedirect(
                    reverse('form_field_update', args=[form_instance.pk]))
    else:
        form = form_class(user=request.user)

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={
                              'form': form,
                              'formset': formset,
                          })
예제 #43
0
def add(request, form_class=RedirectForm, template_name="redirects/add.html"):

    # check permission
    if not has_perm(request.user, 'redirects.add_redirect'):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            redirect = form.save(commit=False)
            redirect.save()  # get pk

            messages.add_message(request, messages.SUCCESS, _('Successfully added %(r)s' % {'r':redirect}))

            # reload the urls
            reload(dynamic_urls)

            return HttpResponseRedirect(reverse('redirects'))
    else:
        form = form_class()

    return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
예제 #44
0
def photoset_edit(request, id, form_class=PhotoSetEditForm, template_name="photos/photo-set/edit.html"):
    from tendenci.apps.perms.object_perms import ObjectPermission
    photo_set = get_object_or_404(PhotoSet, id=id)

    # if no permission; permission exception
    if not has_perm(request.user,'photos.change_photoset',photo_set):
        raise Http403

    if request.method == "POST":
        if request.POST["action"] == "edit":
            form = form_class(request.POST, instance=photo_set, user=request.user)
            if form.is_valid():
                photo_set = form.save(commit=False)

                # update all permissions and save the model
                photo_set = update_perms_and_save(request, form, photo_set)

                # copy all privacy settings from photo set to photos
                Image.objects.filter(photoset=photo_set).update(**get_privacy_settings(photo_set))

                # photo set group permissions
                group_perms = photo_set.perms.filter(group__isnull=False).values_list('group','codename')
                group_perms = tuple([(unicode(g), c.split('_')[0]) for g, c in group_perms ])

                photos = Image.objects.filter(photoset=photo_set)
                for photo in photos:
                    ObjectPermission.objects.remove_all(photo)
                    ObjectPermission.objects.assign_group(group_perms, photo)

                messages.add_message(request, messages.SUCCESS, _("Successfully updated photo set! "))

                return HttpResponseRedirect(reverse('photoset_details', args=[photo_set.id]))
    else:
        form = form_class(instance=photo_set, user=request.user)

    return render_to_response(template_name, {
        'photo_set': photo_set,
        "photoset_form": form,
    }, context_instance=RequestContext(request))
예제 #45
0
파일: views.py 프로젝트: aprildh31/tendenci
def edit(request, id, form_class=FormForm, template_name="forms/edit.html"):
    form_instance = get_object_or_404(Form, pk=id)

    if not has_perm(request.user,'forms.change_form',form_instance):
        raise Http403

    PricingFormSet = inlineformset_factory(Form, Pricing, form=PricingForm, extra=2)
    RecurringPaymentFormSet = inlineformset_factory(Form, RecurringPayment, form=RecurringPaymentForm, extra=2)

    if request.method == "POST":
        form = form_class(request.POST, instance=form_instance, user=request.user)
        if form_instance.recurring_payment:
            formset = RecurringPaymentFormSet(request.POST, instance=form_instance)
        else:
            formset = PricingFormSet(request.POST, instance=form_instance)
        if form.is_valid() and formset.is_valid():
            form_instance = form.save(commit=False)
            form_instance = update_perms_and_save(request, form, form_instance)

            form.save_m2m()  # save payment methods
            formset.save()  # save price options

            # remove all pricings if no custom_payment form
            if not form.cleaned_data['custom_payment']:
                form_instance.pricing_set.all().delete()

            messages.add_message(request, messages.SUCCESS, _('Successfully edited %(f)s' % {'f': form_instance}))
            return HttpResponseRedirect(reverse('form_field_update', args=[form_instance.pk]))
    else:
        form = form_class(instance=form_instance, user=request.user)
        if form_instance.recurring_payment:
            formset = RecurringPaymentFormSet(instance=form_instance)
        else:
            formset = PricingFormSet(instance=form_instance)
    return render_to_resp(request=request, template_name=template_name,context={
        'form':form,
        'formset':formset,
        'form_instance':form_instance,
        })
예제 #46
0
def add(request, form_class=DiscountForm, template_name="discounts/add.html"):
    if not has_perm(request.user, 'discounts.add_discount'):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST, user=request.user)
        if form.is_valid():
            discount = form.save(commit=False)
            discount = update_perms_and_save(request, form, discount)
            form.save_m2m()
            messages.add_message(
                request, messages.SUCCESS,
                _('Successfully added %(d)s' % {'d': discount}))
            return redirect('discount.detail', id=discount.id)
    else:
        form = form_class(user=request.user)

    return render_to_response(
        template_name,
        {'form': form},
        context_instance=RequestContext(request),
    )
예제 #47
0
def add(request, form_class=NewsForm, template_name="news/add.html"):
    # check permission
    if not has_perm(request.user, 'news.add_news'):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            news = form.save(commit=False)

            # update all permissions and save the model
            news = update_perms_and_save(request, form, news)
            form.save_m2m()

            # save photo
            photo = form.cleaned_data['photo_upload']
            if photo:
                news.save(photo=photo)
                assign_files_perms(news, files=[news.thumbnail])

            msg_string = 'Successfully added %s' % unicode(news)
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            # send notification to administrators
            recipients = get_notice_recipients('module', 'news', 'newsrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': news,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'news_added', extra_context)

            return HttpResponseRedirect(reverse('news.detail', args=[news.slug]))
    else:
        form = form_class(user=request.user)

    return render_to_response(template_name, {'form': form},
        context_instance=RequestContext(request))
예제 #48
0
def add(request, form_class=StoryForm, template_name="stories/add.html"):
    if has_perm(request.user, 'stories.add_story'):
        if request.method == "POST":
            form = form_class(request.POST, request.FILES, user=request.user)
            if form.is_valid():
                story = form.save(commit=False)

                story = update_perms_and_save(request, form, story)

                # save photo
                photo = form.cleaned_data['photo_upload']
                if photo:
                    story.save(photo=photo)
                    assign_files_perms(story, files=[story.image])

                if 'rotator' in story.tags:
                    checklist_update('add-story')

                messages.add_message(
                    request, messages.SUCCESS,
                    _('Successfully added %(str)s' % {'str': str(story)}))

                return HttpResponseRedirect(reverse('story', args=[story.pk]))
            else:
                from pprint import pprint
                pprint(list(form.errors.items()))
        else:
            form = form_class(user=request.user)

            tags = request.GET.get('tags', '')
            if tags:
                form.fields['tags'].initial = tags

    else:
        raise Http403

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={'form': form})
예제 #49
0
def detail(request, slug=None, hash=None, template_name="articles/view.html"):
    if not slug and not hash:
        return HttpResponseRedirect(reverse('articles'))

    if hash:
        version = get_object_or_404(Version, hash=hash)
        current_article = get_object_or_404(Article, pk=version.object_id)
        article = version.get_version_object()
        msg_string = 'You are viewing a previous version of this article. View the <a href="%s%s">Current Version</a>.' % (
            get_setting('site', 'global',
                        'siteurl'), current_article.get_absolute_url())
        messages.add_message(request, messages.WARNING, _(msg_string))
    else:
        article = get_object_or_404(Article, slug=slug)

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

    if not article.release_dt_local and article.release_dt:
        article.assign_release_dt_local()

    if not article.release_dt_local or article.release_dt_local >= datetime.now(
    ):
        if not any([
                has_perm(request.user, 'articles.view_article'), request.user
                == article.owner, request.user == article.creator
        ]):
            raise Http403

    if has_view_perm(request.user, 'articles.view_article', article):
        EventLog.objects.log(instance=article)
        return render_to_resp(request=request,
                              template_name=template_name,
                              context={'article': article})
    else:
        raise Http403
예제 #50
0
def detail(request, slug, template_name="studygroups/detail.html"):
    study_group = get_object_or_404(StudyGroup, slug=slug)

    if has_perm(request.user, 'studygroups.view_studygroup', study_group):
        EventLog.objects.log(instance=study_group)
        officers = study_group.officers()

        #has_group_view_permission is True if there is at least one
        #group where the user is a member that has a view_studygroup permission.
        has_group_view_permission = False
        #Check user for group view permissions
        if request.user.is_authenticated:
            groups = request.user.group_set.all()
            perms = has_groups_perms(study_group).filter(group__in=groups)
            for perm in perms:
                #Check if permission has view studygroup permission
                has_group_view_permission |= perm.codename == 'view_studygroup'
                if has_group_view_permission:
                    break

        filters = get_query_filters(request.user, 'files.view_file')
        files = File.objects.filter(filters).filter(
            group=study_group.group).distinct()

        return render_to_resp(request=request,
                              template_name=template_name,
                              context={
                                  'study_group':
                                  study_group,
                                  'officers':
                                  officers,
                                  'files':
                                  files,
                                  'has_group_view_permission':
                                  has_group_view_permission,
                              })
    else:
        raise Http403
예제 #51
0
def edit(request,
         id,
         form_class=LocationForm,
         template_name="locations/edit.html"):
    location = get_object_or_404(Location, pk=id)

    if has_perm(request.user, 'locations.change_location', location):
        if request.method == "POST":
            form = form_class(request.POST,
                              request.FILES,
                              instance=location,
                              user=request.user)
            if form.is_valid():
                location = form.save(commit=False)

                # update all permissions and save the model
                location = update_perms_and_save(request, form, location)

                if 'photo_upload' in form.cleaned_data:
                    photo = form.cleaned_data['photo_upload']
                    if photo:
                        location.save(photo=photo)
                msg_string = 'Successfully updated %s' % location
                messages.add_message(request, messages.SUCCESS, _(msg_string))

                return HttpResponseRedirect(
                    reverse('location', args=[location.slug]))
        else:
            form = form_class(instance=location, user=request.user)

        return render_to_resp(request=request,
                              template_name=template_name,
                              context={
                                  'location': location,
                                  'form': form
                              })
    else:
        raise Http403
예제 #52
0
def edit(request, id, form_class=NewsForm, template_name="news/edit.html"):
    news = get_object_or_404(News, pk=id)

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

    form = form_class(instance=news, user=request.user)

    if request.method == "POST":
        form = form_class(request.POST, request.FILES, instance=news, user=request.user)
        if form.is_valid():
            news = form.save(commit=False)

            # update all permissions and save the model
            news = update_perms_and_save(request, form, news)
            form.save_m2m()

            # save photo
            photo = form.cleaned_data['photo_upload']
            if photo:
                news.save(photo=photo)
                assign_files_perms(news, files=[news.thumbnail])

            # update thumbnail status when news status is updated
            # this will fix the error wherein a thumbnail image
            # can be viewed only when logged in.
            thumbnail = news.thumbnail
            if thumbnail:
                thumbnail.status_detail = news.status_detail
                thumbnail.save()
            msg_string = 'Successfully updated %s' % unicode(news)
            messages.add_message(request, messages.SUCCESS, _(msg_string))

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

    return render_to_response(template_name, {'news': news, 'form': form},
        context_instance=RequestContext(request))
예제 #53
0
def delete(request, id, template_name="files/delete.html"):
    file = get_object_or_404(File, pk=id)

    # check permission
    if not has_perm(request.user, 'files.delete_file'):
        raise Http403

    if request.method == "POST":
        # reassign owner to current user
        file.owner = request.user
        file.owner_username = request.user.username
        file.save()
        file.delete()

        if 'ajax' in request.POST:
            return HttpResponse('Ok')
        else:
            return HttpResponseRedirect(reverse('file.search'))

    return render_to_response(
        template_name, {
            'file': file
        }, context_instance=RequestContext(request))
예제 #54
0
def corporate_membership_notice_log_search(request, template_name="corporate_memberships/notices/logs_search.html"):
    if not has_perm(request.user,'corporate_memberships.change_notice'): raise Http403

    form = NoticeLogSearchForm(request.GET or None)
    logs = NoticeLog.objects.all()
    if form.is_valid():
        notice_id = form.cleaned_data['notice_id']
        if notice_id:
            notice = Notice.objects.get(id=notice_id)
            logs = logs.filter(notice=notice)
        start_dt = form.cleaned_data['start_dt']
        end_dt = form.cleaned_data['end_dt']
        if start_dt:
            start_dt = datetime(*(time.strptime(start_dt, '%Y-%m-%d %H:%M')[0:6]))
            logs = logs.filter(notice_sent_dt__gte=start_dt)
        if end_dt:
            end_dt = datetime(*(time.strptime(end_dt, '%Y-%m-%d %H:%M')[0:6]))
            logs = logs.filter(notice_sent_dt__lte=end_dt)

    logs = logs.order_by('-notice_sent_dt')

    return render_to_response(template_name, {'logs': logs, 'form':form},
        context_instance=RequestContext(request))
예제 #55
0
def edit(request, id, form_class=ResumeForm, template_name="resumes/edit.html"):
    resume = get_object_or_404(Resume, pk=id)

    form = form_class(request.POST or None, request.FILES or None, instance=resume, user=request.user)
    if has_perm(request.user,'resumes.change_resume',resume):
        if request.method == "POST":
            if form.is_valid():
                resume = form.save(commit=False)

                if resume.resume_file:
                    resume.resume_file.file.seek(0)
                resume = update_perms_and_save(request, form, resume)

                EventLog.objects.log(instance=resume)

                messages.add_message(request, messages.SUCCESS, _('Successfully updated %(r)s' % {'r':resume}))

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

        return render_to_resp(request=request, template_name=template_name,
            context={'resume': resume, 'form':form})
    else:
        raise Http403
예제 #56
0
파일: models.py 프로젝트: iniForum/tendenci
    def allow_view_by(self, user2_compare, guid=''):
        if user2_compare.profile.is_superuser:
            return True

        if has_perm(user2_compare, 'invoices.view_invoice'):
            return True

        if not get_setting("module", "invoices", "disallow_private_urls"):
            if self.guid == guid:
                return True

        obj = self.get_object()
        if obj and hasattr(obj, 'allow_adjust_invoice_by'):
            # example: chapter leaders can view/adjust invoices for their chapter memberships.
            if obj.allow_adjust_invoice_by(user2_compare):
                return True

        if user2_compare.is_authenticated:
            if user2_compare in [self.creator, self.owner] or \
                    user2_compare.email == self.bill_to_email:
                return self.status

        return False
예제 #57
0
파일: views.py 프로젝트: pfreal/tendenci
def pricing_edit(request,
                 id,
                 form_class=JobPricingForm,
                 template_name="jobs/pricing-edit.html"):
    job_pricing = get_object_or_404(JobPricing, pk=id)
    if not has_perm(request.user, 'jobs.change_jobpricing', job_pricing):
        Http403

    if request.method == "POST":
        form = form_class(request.POST, instance=job_pricing)
        if form.is_valid():
            job_pricing = form.save(commit=False)
            job_pricing.save(request.user)

            EventLog.objects.log(instance=job_pricing)

            return HttpResponseRedirect(
                reverse('job_pricing.view', args=[job_pricing.id]))
    else:
        form = form_class(instance=job_pricing)

    return render_to_response(template_name, {'form': form},
                              context_instance=RequestContext(request))
예제 #58
0
파일: views.py 프로젝트: mdaraban/tendenci
def pricing_add(request, form_class=DirectoryPricingForm, template_name="directories/pricing-add.html"):
    if has_perm(request.user,'directories.add_directorypricing'):
        if request.method == "POST":
            form = form_class(request.POST, user=request.user)
            if form.is_valid():
                directory_pricing = form.save(commit=False)
                directory_pricing.status = 1
                directory_pricing.save(request.user)

                if "_popup" in request.REQUEST:
                    return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % (escape(directory_pricing.pk), escape(directory_pricing)))

                return HttpResponseRedirect(reverse('directory_pricing.view', args=[directory_pricing.id]))
        else:
            form = form_class(user=request.user)

        if "_popup" in request.REQUEST:
            template_name="directories/pricing-add-popup.html"

        return render_to_response(template_name, {'form':form},
            context_instance=RequestContext(request))
    else:
        raise Http403
예제 #59
0
    def approve(self, request, pk):
        """
        Approve membership and redirect to
        membershipdefault change page.
        """
        if not has_perm(request.user, 'memberships.approve_membershipdefault'):
            raise Http403

        m = get_object_or_404(MembershipDefault, pk=pk)
        m.approve(request_user=request.user)
        m.send_email(request, 'approve')
        if m.corporate_membership_id:
            # notify corp reps
            m.email_corp_reps(request)

        messages.add_message(request, messages.SUCCESS,
                             _('Successfully Approved'))

        return redirect(
            reverse(
                'admin:memberships_membershipdefault_change',
                args=[pk],
            ))
예제 #60
0
파일: views.py 프로젝트: rob-hills/tendenci
def add(request, form_class=HelpFileForm, template_name="help_files/add.html"):
    if has_perm(request.user, 'help_files.add_helpfile'):
        if request.method == "POST":
            form = form_class(request.POST, user=request.user)
            if form.is_valid():
                help_file = form.save(commit=False)

                if not request.user.is_superuser:
                    help_file.status_detail = 'pending'

                # add all permissions and save the model
                help_file = update_perms_and_save(request, form, help_file)
                form.save_m2m()
                msg_string = 'Successfully added %s' % help_file
                messages.add_message(request, messages.SUCCESS, _(msg_string))

                # send notification to administrator(s) and module recipient(s)
                if not request.user.is_superuser:
                    recipients = get_notice_recipients('module', 'help_files',
                                                       'helpfilerecipients')
                    if recipients:
                        notification.send_emails(recipients, 'help_file_added',
                                                 {
                                                     'object': help_file,
                                                     'request': request,
                                                 })

                return HttpResponseRedirect(
                    reverse('help_file.details', args=[help_file.slug]))
        else:
            form = form_class(user=request.user)

        return render_to_resp(request=request,
                              template_name=template_name,
                              context={'form': form})
    else:
        raise Http403