Example #1
0
def edit_eptitude_for_book_card(
    request, card_id, eptitude_id, book_id, eptitude_form=EptitudeForm, template_name="card/edit_eptitude.html"
):

    card = get_object_or_404(Card, pk=card_id)
    get_object_or_404(Book, pk=book_id)
    redirect_to = "/cards/edit_card_for_book/%s/%s" % (card_id, book_id)

    eptitude = get_object_or_404(CardEptitude, pk=eptitude_id)

    if request.method == "POST":
        form = eptitude_form(card, request.POST)
        if form.is_valid():
            editEptitudeByRequest(request, eptitude)
            return HttpResponseRedirect(redirect_to)

    else:

        data = getEptitudeData(eptitude, card)
        form = eptitude_form(card, data)

    current_site = get_current_site(request)

    context = {"form": form, "card": card, "site": current_site, "site_name": current_site.name}

    return TemplateResponse(request, template_name, context)
Example #2
0
def project_index(request, username=None, tag=None):
    """
    The list of projects, which will optionally filter by user or tag,
    in which case a 'person' or 'tag' will be added to the context
    """
    queryset = Project.objects.live()
    if username:
        user = get_object_or_404(User, username=username)
        queryset = queryset.filter(user=user)
    else:
        user = None

    if tag:
        tag = get_object_or_404(Tag, slug=tag)
        queryset = queryset.filter(tags__name__in=[tag.slug])
    else:
        tag = None

    return object_list(
        request,
        queryset=queryset,
        extra_context={'person': user, 'tag': tag},
        page=int(request.GET.get('page', 1)),
        template_object_name='project',
    )
Example #3
0
def user_role_edit(request, username, membership_id, form_class=GroupMembershipEditForm, template_name="profiles/edit_role.html"):
    user = get_object_or_404(User, username=username)
    membership = get_object_or_404(GroupMembership, id=membership_id)
    
    try:
        profile = Profile.objects.get(user=user)
    except Profile.DoesNotExist:
        profile = Profile.objects.create_profile(user=user)
    
    if not profile.allow_edit_by(request.user):
        raise Http403
    
    if not has_perm(request.user,'user_groups.view_group', membership.group):
        raise Http403
        
    if request.method == 'POST':
        form = form_class(request.POST, instance=membership)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, 'Successfully edited membership for %s' % membership.group)
            return HttpResponseRedirect("%s%s" % (reverse('profile', args=[user.username]),'#userview-groups'))
    else:
        form = form_class(instance=membership)

    return render_to_response(template_name, {
                            'form': form,
                            'membership': membership,
                            }, context_instance=RequestContext(request))
Example #4
0
def challenge_accept_beneficiary_set_donation(request, participation_id, state, club_id, club_class):
    club = get_object_or_404(club_class, id=club_id)
    participation = get_object_or_404(ChallengeParticipation, id=participation_id)
    challenge = participation.challenge
    template = challenge.template
    form = ChallengeConfigureForm({
        'donation_with_challenge': int(challenge.proposed_donation_amount),
        'donation_without_challenge': int(challenge.proposed_donation_amount_decline)})
    # if request.method == 'POST':
    #     form = ChallengeConfigureForm(request.POST)
    if form.is_valid():
        challenge = _create_challenge(
            club_class, club_id, form, request, template, challenge,
            youtube_video_id=participation.youtube_video_id, image=participation.image)
        return redirect('/challenges/%s/share' % challenge.id)
    template_data = {
        'club': club,
        'club_class': club_class.__name__,
        'form': form,
        'state': state,
        'template': template}
    return render(
        request,
        'spudderspuds/challenges/pages/challenge_accept_beneficiary_choose_donation.html',
        template_data)
Example #5
0
def edit_links_edit(request, slug, link):
    link = get_object_or_404(Link, id=link)
    form = project_forms.ProjectLinksForm(request.POST or None, instance=link)
    profile = get_object_or_404(UserProfile, user=request.user)
    project = get_object_or_404(Project, slug=slug)
    if link.project != project:
        return http.HttpResponseForbidden(_("You can't edit this link"))
    metric_permissions = project.get_metrics_permissions(request.user)
    if form.is_valid():
        if link.subscription:
            #links_tasks.UnsubscribeFromFeed.apply_async(args=(link,))
            link.subscription = None
            link.save()
        link = form.save(commit=False)
        link.user = profile
        link.project = project
        link.save()
        messages.success(request, _('Link updated.'))
        return http.HttpResponseRedirect(
            reverse('projects_edit_links', kwargs=dict(slug=project.slug)))
    else:
        form = project_forms.ProjectLinksForm(instance=link)
    return render_to_response('projects/project_edit_links_edit.html', {
        'project': project,
        'form': form,
        'link': link,
        'links_tab': True,
        'can_view_metric_overview': metric_permissions[0],
    }, context_instance=RequestContext(request))
Example #6
0
    def get_region(self, request=None, kwargs=None):
        """
        Returns the Region associated with this view.
        """
        if kwargs is None:
            kwargs = self.kwargs
        if request is None:
            request = self.request

        if kwargs.get('region'):
            region_slug = kwargs.get('region')
            r = get_object_or_404(Region, slug=slugify(region_slug))
        else:
            if self.region_required:
                rs = get_object_or_404(RegionSettings, domain=request.META['HTTP_HOST'])
                r = rs.region
            else:
                if RegionSettings.objects.filter(domain=request.META['HTTP_HOST']).exists():
                    rs = get_object_or_404(RegionSettings, domain=request.META['HTTP_HOST'])
                    r = rs.region
                else:
                    r = None

        if self.region_required and not r.is_active:
            raise Http404(_("Region '%s' was deleted." % r.slug))

        return r
Example #7
0
def appcast(request, pagetype, slug):
    pagetype = get_object_or_404( PageType, folder = pagetype.lower() )
    slug = slug.lower()
    page = get_object_or_404( Page, pagetype__exact = pagetype.id, slug__exact = slug )

    feedclass = feed_engine('rss2')

    server = settings.SITE_URL
    feed = feedclass(
      title = "jerakeen.org / %s / appcast"%page.title,
      link = "%s%s"%( server, page.get_absolute_url() ),
      description = "",
      author_name = "Tom Insam",
      author_email = "tom@jerakeen.org",
      author_link = "http://jerakeen.org/",
      feed_url = "%s%s/appcast"%( server, page.get_absolute_url() ),
    );

    for upload in page.upload_set.all():
        feed.add_item(
            upload.title,
            upload.file.url, # includes hostname
            pagefilter( upload.description ),
            pubdate = upload.date,
            enclosure = feedgenerator.Enclosure( upload.file.url, unicode(upload.file.size), "application/octet-stream" ),
        )
        

    return HttpResponse(
        feed.writeString('utf-8'), mimetype = feed.mime_type )
Example #8
0
def write(request, slug_story, activation_key, t='stories/write.html', d={}):
    story = get_object_or_404(Story, slug=slug_story)
    active_membership = story.active_membership()
    d['story']=story
    if not active_membership:
        story.turn_membership()
        return render(request, 'stories/done.html', d)
    membership = get_object_or_404(Membership, activation_key=activation_key)
    if active_membership.id != membership.id:
        return render(request, 'stories/done.html', d)
    new_line = Line(story=story)
    if request.POST:
        line_form=LineForm(request.POST, prefix='line', instance=new_line)
        if line_form.is_valid():
            line_form.save()
            next = story.turn_membership()
            mail_d = {
                'story': story,
                'site': get_current_site(request)
            }
            message = render_to_string('stories/email.txt', mail_d)
            email = EmailMessage(
                'Estas participando del concurso',
                message,
                to=[next.user.email])
            email.send()
            return render(request, 'stories/done.html', d)  
    else:
        line_form=LineForm(prefix='line')
    d = {
        'form': line_form,
        'story': story,
        'site': get_current_site(request)
    }
    return render(request, t, d)
Example #9
0
def permissions_import_json(request, ufp_id=0):
    upload_file = request.FILES.get('perms_upload')

    if upload_file:
        try:
            perms = json.loads(upload_file.read().decode('utf-8'))
            username = perms.get('username')

            if ufp_id:
                ufp = get_object_or_404(UserFieldPermissions, pk=ufp_id)
                if username == ufp.user.username:
                    # Delete the old field permissions
                    ufp.permissions.all().delete()
                    _add_permissions(request, ufp, perms)
                else:
                    message = 'The wrong user is defined in the imported file'
                    messages.add_message(request, messages.ERROR, message)
            else:
                user = get_object_or_404(User, username=username)
                ufp = UserFieldPermissions(user=user)
                ufp.save()
                _add_permissions(request, ufp, perms)
                ufp_id = ufp.pk
        except Exception as e:
            message = 'Error in the import : %s' % e
            messages.add_message(request, messages.ERROR, message)
    else:
        message = 'Missing imported file'
        messages.add_message(request, messages.ERROR, message)

    return redirect(
        '/admin/rest_framework_fine_permissions/userfieldpermissions/%s'\
            % ufp_id)
Example #10
0
def user_page(request, user):
    '''
    User details page.
    '''
    user = get_object_or_404(User, username=user)
    profile = get_object_or_404(Profile, user=user)

    # Filter all user activity
    all_changes = Change.objects.last_changes(request.user).filter(
        user=user,
    )

    # Last user activity
    last_changes = all_changes[:10]

    # Filter where project is active
    user_projects_ids = set(all_changes.values_list(
        'translation__subproject__project', flat=True
    ))
    user_projects = Project.objects.filter(id__in=user_projects_ids)

    return render(
        request,
        'accounts/user.html',
        {
            'page_profile': profile,
            'page_user': user,
            'last_changes': last_changes,
            'last_changes_url': urlencode(
                {'user': user.username.encode('utf-8')}
            ),
            'user_projects': user_projects,
        }
    )
Example #11
0
def buy_now(request, id):
    if request.method == 'POST':
        print(request.POST)
        form = MakePaymentForm(request.POST)
        if form.is_valid():
            try:
                product = get_object_or_404(Products, pk=id)
                customer = stripe.Charge.create(
                    amount= int(product.price * 100),
                    currency="EUR",
                    description=product.name,
                    card=form.cleaned_data['stripe_id'],
                )
            except (stripe.error.CardError, e):
                messages.error(request, "Your card was declined!")

            if customer.paid:
                messages.success(request, "You have successfully paid")
                return redirect(reverse('products'))
            else:
                messages.error(request, "Unable to take payment")
        else:
            messages.error(request, "We were unable to take a payment with that card!")

    else:
        form = MakePaymentForm()
        product = get_object_or_404(Products, pk=id)

    args = {'form': form, 'publishable': settings.STRIPE_PUBLISHABLE_KEY, 'product': product}
    args.update(csrf(request))

    return render(request, 'pay.html', args)
Example #12
0
def user_delete(request, user_id=None, user_id_list=None):
    check_permissions(request.user, [PERMISSION_USER_DELETE])
    post_action_redirect = None

    if user_id:
        users = [get_object_or_404(User, pk=user_id)]
        post_action_redirect = reverse('user_list')
    elif user_id_list:
        users = [get_object_or_404(User, pk=user_id) for user_id in user_id_list.split(',')]
    else:
        messages.error(request, _(u'Must provide at least one user.'))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

    previous = request.POST.get('previous', request.GET.get('previous', request.META.get('HTTP_REFERER', '/')))
    next = request.POST.get('next', request.GET.get('next', post_action_redirect if post_action_redirect else request.META.get('HTTP_REFERER', '/')))

    if request.method == 'POST':
        for user in users:
            try:
                if user.is_superuser or user.is_staff:
                    messages.error(request, _(u'Super user and staff user deleting is not allowed, use the admin interface for these cases.'))
                else:
                    user.delete()
                    messages.success(request, _(u'User "%s" deleted successfully.') % user)
            except Exception, e:
                messages.error(request, _(u'Error deleting user "%(user)s": %(error)s') % {
                    'user': user, 'error': e
                })

        return HttpResponseRedirect(next)
Example #13
0
def group_delete(request, group_id=None, group_id_list=None):
    check_permissions(request.user, [PERMISSION_GROUP_DELETE])
    post_action_redirect = None

    if group_id:
        groups = [get_object_or_404(Group, pk=group_id)]
        post_action_redirect = reverse('group_list')
    elif group_id_list:
        groups = [get_object_or_404(Group, pk=group_id) for group_id in group_id_list.split(',')]
    else:
        messages.error(request, _(u'Must provide at least one group.'))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

    previous = request.POST.get('previous', request.GET.get('previous', request.META.get('HTTP_REFERER', '/')))
    next = request.POST.get('next', request.GET.get('next', post_action_redirect if post_action_redirect else request.META.get('HTTP_REFERER', '/')))

    if request.method == 'POST':
        for group in groups:
            try:
                group.delete()
                messages.success(request, _(u'Group "%s" deleted successfully.') % group)
            except Exception, e:
                messages.error(request, _(u'Error deleting group "%(group)s": %(error)s') % {
                    'group': group, 'error': e
                })

        return HttpResponseRedirect(next)
Example #14
0
def candidatelist_edit(request, candidatelist_id=None, entity_id=None):

    if not entity_id:
        entity = request.user.profile.locality
    else:
        entity = get_object_or_404(Entity, id=entity_id)

    if candidatelist_id:
        candidatelist = get_object_or_404(CandidateList, id=candidatelist_id)
    else:
        candidatelist = CandidateList(entity=entity)


    if not candidatelist.can_edit(request.user):
        return HttpResponseForbidden(_("Only editors have access to this page."))

    if request.method == "POST":
        form = CandidateListForm(request.POST, instance=candidatelist)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('candidate-list', kwargs={'candidatelist_id': candidatelist.id}))
    else:
        form = CandidateListForm(instance=candidatelist)

    context = RequestContext(request, {'form': form,
                                       'entity': entity,
                                       'candidatelist_id': candidatelist_id,
                                      })
    return render(request, "polyorg/candidatelist_form.html", context)
Example #15
0
    def obj_perms_manage_group_view(self, request, object_pk, group_id):
        """
        Manages selected groups' permissions for current object.
        """
        group = get_object_or_404(Group, id=group_id)
        obj = get_object_or_404(self.queryset(request), pk=object_pk)
        form_class = self.get_obj_perms_manage_group_form()
        form = form_class(group, obj, request.POST or None)

        if request.method == 'POST' and form.is_valid():
            form.save_obj_perms()
            msg = ugettext("Permissions saved.")
            messages.success(request, msg)
            info = (
                self.admin_site.name,
                self.model._meta.app_label,
                self.model._meta.module_name
            )
            url = reverse(
                '%s:%s_%s_permissions_manage_group' % info,
                args=[obj.pk, group.id]
            )
            return redirect(url)

        context = self.get_obj_perms_base_context(request, obj)
        context['group_obj'] = group
        context['group_perms'] = get_perms(group, obj)
        context['form'] = form

        return render_to_response(self.get_obj_perms_manage_group_template(),
            context, RequestContext(request, current_app=self.admin_site.name))
Example #16
0
def group_message_details(request, group_id, message_id):
    group = get_object_or_404(GroupedMessage, pk=group_id)

    message = get_object_or_404(group.message_set, pk=message_id)
    
    if '__sentry__' in message.data and 'exc' in message.data['__sentry__']:
        module, args, frames = message.data['__sentry__']['exc']
        message.class_name = str(message.class_name)
        # We fake the exception class due to many issues with imports/builtins/etc
        exc_type = type(message.class_name, (Exception,), {})
        exc_value = exc_type(message.message)

        exc_value.args = args
    
        reporter = ImprovedExceptionReporter(message.request, exc_type, exc_value, frames, message.data['__sentry__'].get('template'))
        traceback = mark_safe(reporter.get_traceback_html())
    elif group.traceback:
        traceback = mark_safe('<pre>%s</pre>' % (group.traceback,))
    
    def iter_data(obj):
        for k, v in obj.data.iteritems():
            if k.startswith('_') or k in ['url']:
                continue
            yield k, v

    json_data = iter_data(message)

    page = 'messages'

    return render_to_response('sentry/group/message.html', locals(),
                              context_instance=RequestContext(request))
Example #17
0
def move_choose_destination(request, page_to_move_id, viewed_page_id=None):
    page_to_move = get_object_or_404(Page, id=page_to_move_id)
    page_perms = page_to_move.permissions_for_user(request.user)
    if not page_perms.can_move():
        raise PermissionDenied

    if viewed_page_id:
        viewed_page = get_object_or_404(Page, id=viewed_page_id)
    else:
        viewed_page = Page.get_first_root_node()

    viewed_page.can_choose = page_perms.can_move_to(viewed_page)

    child_pages = []
    for target in viewed_page.get_children():
        # can't move the page into itself or its descendants
        target.can_choose = page_perms.can_move_to(target)

        target.can_descend = not(target == page_to_move or target.is_child_of(page_to_move)) and target.get_children_count()

        child_pages.append(target)

    return render(request, 'wagtailadmin/pages/move_choose_destination.html', {
        'page_to_move': page_to_move,
        'viewed_page': viewed_page,
        'child_pages': child_pages,
    })
Example #18
0
def channel(request, slug_c, slug_t=None):
    channel = get_object_or_404(Channel, slug=slug_c)
    theme = None

    videos_list = VIDEOS.filter(channel=channel)

    if slug_t:
        theme = get_object_or_404(Theme, slug=slug_t)
        videos_list = videos_list.filter(theme=theme)

    order_by = request.COOKIES.get('orderby') if request.COOKIES.get(
        'orderby') else "order_by_-date_added"
    videos_list = videos_list.order_by(
        "%s" % replace(order_by, "order_by_", ""))

    #per_page = request.GET.get('per_page') if request.GET.get('per_page') and request.GET.get('per_page').isdigit() else DEFAULT_PER_PAGE
    per_page = request.COOKIES.get('perpage') if request.COOKIES.get(
        'perpage') and request.COOKIES.get('perpage').isdigit() else DEFAULT_PER_PAGE
    paginator = Paginator(videos_list, per_page)
    page = request.GET.get('page')

    videos = get_pagination(page, paginator)

    if request.is_ajax():
        return render_to_response("videos/videos_list.html",
                                  {"videos": videos},
                                  context_instance=RequestContext(request))

    return render_to_response("channels/channel.html",
                              {"channel": channel, "theme": theme,
                                  "videos": videos},
                              context_instance=RequestContext(request))
Example #19
0
 def get_context_data(self, **kwargs):
     context = super(BoardView, self).get_context_data(**kwargs)
     profile_user = get_object_or_404(User, username=kwargs["username"])
     context['profile_user'] = profile_user
     context['board'] = get_object_or_404(Board, slug=kwargs['board_slug'])
     context['pin_form'] = PinForm()
     return context
Example #20
0
def childcare_create(request):
    if request.method == 'POST':
        form = ChildcareCreateForm(request.POST)
        if form.is_valid():
            #managers = form.cleaned_data['managers']
            childcare = form.save(commit=False)
            # check if there is a default theme
            try:
                theme = get_object_or_404(Theme, pk=1)
                theme_exist = True
            except:
                theme_exist = False
            if theme_exist:
                childcare.theme = get_object_or_404(Theme, pk=1)  # set 1st theme as default
            else:
                theme = Theme(title='Default theme', computer_name='default', description='Default theme')
                theme.save()
                childcare.theme = theme
            childcare = form.save(commit=True)
            # automatically add current user as manager and give him permissions
            childcare.managers.add(request.user)
            managers = list(childcare.managers.all())
            # add manager permissions
            group = Group.objects.get(name='Childcare %s: Manager' % childcare.pk)
            for manager in managers:
                manager.groups.add(group)
            # create default classroom
            classroom = Classroom(name='%s classroom' % childcare, childcare=childcare)
            classroom.save()
            log.info(log_prefix+'Childcare created (childcare: %s, user: %s)' % (childcare.name, request.user))
            return HttpResponseRedirect(reverse('childcare:childcare_info', kwargs={'childcare_slug': childcare.slug}))
    else:
        form = ChildcareCreateForm()
    return render(request, 'childcare/childcare_create.html', {'form': form})
Example #21
0
def create_challenge_set_donation(request, template_id, state, club_id, club_class):
    club = get_object_or_404(club_class, id=club_id)
    template = get_object_or_404(ChallengeTemplate, id=template_id)
    form = ChallengeConfigureForm()
    upload_url = blobstore.create_upload_url('/challenges/create/%s/%s/%s/%s' % (
        template_id, state, 'o' if club_class == Club else 't', club_id))
    if request.method == 'POST':
        form = ChallengeConfigureForm(request.POST)
        if form.is_valid():
            uploaded_file = None
            if request.FILES:
                upload_form = UploadForm(request.POST, request.FILES)
                uploaded_file = upload_form.save()
            challenge = _create_challenge(club_class, club_id, form, request, template, image=uploaded_file)
            redirect_url = '/challenges/%s/share' % challenge.id
            if request.is_ajax():
                return HttpResponse(redirect_url)
            return redirect(redirect_url)
        if request.is_ajax():
            return HttpResponse("%s|%s" % (
                blobstore.create_upload_url(upload_url),
                '<br/>'.join(['<br/>'.join([_e for _e in e]) for e in form.errors.values()])))
    template_data = {
        'club': club,
        'club_class': club_class.__name__,
        'form': form,
        'state': state,
        'template': template,
        'upload_url': upload_url}
    return render(
        request,
        'spudderspuds/challenges/pages/create_challenge_configure.html',
        template_data)
Example #22
0
def revisions_unschedule(request, page_id, revision_id):
    page = get_object_or_404(Page, id=page_id).specific

    user_perms = UserPagePermissionsProxy(request.user)
    if not user_perms.for_page(page).can_unschedule():
        raise PermissionDenied

    revision = get_object_or_404(page.revisions, id=revision_id)

    next_url = get_valid_next_url_from_request(request)

    subtitle = _('revision {0} of "{1}"').format(revision.id, page.get_admin_display_title())

    if request.method == 'POST':
        revision.approved_go_live_at = None
        revision.save(update_fields=['approved_go_live_at'])

        messages.success(request, _('Revision {0} of "{1}" unscheduled.').format(revision.id, page.get_admin_display_title()), buttons=[
            messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
        ])

        if next_url:
            return redirect(next_url)
        return redirect('wagtailadmin_pages:revisions_index', page.id)

    return render(request, 'wagtailadmin/pages/revisions/confirm_unschedule.html', {
        'page': page,
        'revision': revision,
        'next': next_url,
        'subtitle': subtitle
    })
Example #23
0
    def __process_activities_badge(self, query, badge, content_object, update_auditted=True):
        content_type = ContentType.objects.get_for_model(content_object)

        cursor = connection.cursor()
        try:
            cursor.execute(query)
            rows = cursor.fetchall()
            
            if update_auditted:
                activity_ids = []
            badge = get_object_or_404(Badge, id=badge)
            for row in rows:
                activity_id = row[0]
                user_id = row[1]
                object_id = row[2]
                
                user = get_object_or_404(User, id=user_id)
                award = Award(user=user, badge=badge, content_type=content_type, object_id=objet_id)
                award.save()
                
                if update_auditted:
                    activity_ids.append(activity_id)
                
            if update_auditted:
                self.update_activities_auditted(cursor, activity_ids)
        finally:
            cursor.close()
Example #24
0
 def __init__(self, user, project_id, stack_ids, x_min, x_max, y_min, y_max,
              z_min, z_max, rotation_cw, zoom_level, single_channel=False,
              output_path=None):
     self.user = user
     self.project_id = int(project_id)
     self.project = get_object_or_404(Project, pk=project_id)
     # Allow a single ID and a list
     if isinstance(stack_ids, int):
         self.stack_ids = [stack_ids]
     else:
         self.stack_ids = stack_ids
     self.stacks = []
     for sid in self.stack_ids:
         self.stacks.append( get_object_or_404(Stack, pk=sid) )
     # The reference stack is used to obtain e.g. resolution information
     self.ref_stack = self.stacks[0]
     self.x_min = float(x_min)
     self.x_max = float(x_max)
     self.y_min = float(y_min)
     self.y_max = float(y_max)
     self.z_min = float(z_min)
     self.z_max = float(z_max)
     self.zoom_level = int(zoom_level)
     # Save a normalized version of the rotation angle
     self.rotation_cw = rotation_cw % 360
     # Create an output path if not already present
     if output_path is None:
         file_name = file_prefix + id_generator() + "." + file_extension
         output_path = os.path.join(crop_output_path, file_name)
     self.single_channel = single_channel
     self.output_path = output_path
     # State that extra initialization is needed
     self.needs_initialization = True
Example #25
0
File: files.py Project: nirgal/ngw
    def get(self, request, fid, cid):
        cf = get_object_or_404(ContactField, pk=fid)
        if not perms.c_can_view_fields_cg(request.user.id,
                                          cf.contact_group_id):
            raise PermissionDenied
        fullpath = os.path.join(settings.MEDIA_ROOT, 'fields', fid, cid)
        if not os.path.exists(fullpath):
            raise Http404(_('"{path}" does not exist').format(path=fullpath))
        # Respect the If-Modified-Since header.
        statobj = os.stat(fullpath)
        if not static.was_modified_since(
           request.META.get('HTTP_IF_MODIFIED_SINCE'),
           statobj.st_mtime, statobj.st_size):
            return HttpResponseNotModified()

        # START OF content_type detection
        cfv = get_object_or_404(ContactFieldValue,
                                contact_id=cid, contact_field_id=fid)
        fileinfo = json.loads(cfv.value)
        content_type = fileinfo['content_type']
        # END OF content_type detection

        response = FileResponse(open(fullpath, 'rb'),
                                content_type=content_type)
        response["Last-Modified"] = http_date(statobj.st_mtime)
        if stat.S_ISREG(statobj.st_mode):
            response["Content-Length"] = statobj.st_size

        response['Content-Disposition'] = 'inline; filename="{0}"'.format(
            header_encode(fileinfo['filename'].encode('utf-8'), 'utf-8'))
        return response
Example #26
0
def edit_question(request, survey_id, question_id=None):
    survey = get_object_or_404(Survey, id=survey_id)
    question = get_object_or_404(Question, id=question_id)
    if request.method == 'GET':
        form = QuestionForm(instance=question)
        info = {'id': question.id,
        }
        data = {'info': info,
                'form' : form.as_customized_extjs(question),
        }
        json_data = json.JSONEncoder(ensure_ascii=False).encode({
            'success':True,
            'data': data 
        })
        return utils.JsonResponse(json_data)
    elif request.method == 'POST':
        form = QuestionForm(request.REQUEST, instance=question)
        if form.is_valid():
            question = form.save(commit=False)
            question.survey = survey
            question.save()
            return api_utils.success()
        else:
            return utils.JsonResponse(form.as_extjsdata())          
    raise Http404
Example #27
0
def edit_post(request, post_id):
    if request.method == 'POST':
        add_post_form = EditPostForm(request.POST)
        post_inst = get_object_or_404(Posts, id=post_id)
        # user_inst = UserProfile.objects.get(user_id=request.user.id)
        if add_post_form.is_valid():
            # form_instance = add_post_form.save(commit=False)
            post_inst.lift_type = add_post_form.cleaned_data['lift_type']
            post_inst.location = add_post_form.cleaned_data['location']
            post_inst.leaving_date = add_post_form.cleaned_data['leaving_date']
            post_inst.leaving_time = add_post_form.cleaned_data['leaving_time']
            post_inst.return_date = add_post_form.cleaned_data['return_date']
            post_inst.fulfilled = add_post_form.cleaned_data['fulfilled']
            post_inst.spaces = add_post_form.cleaned_data['spaces']
            post_inst.event = add_post_form.cleaned_data['event']
            post_inst.save()

            return redirect(post_inst)

    else:
        post_inst = get_object_or_404(Posts, pk=post_id)
        # This loads a form with an instance of the post we get from the id passed in the url
        add_post_form = EditPostForm(instance=post_inst)

    event_inst = get_object_or_404(Events, pk=post_inst.event_id)
    # print(event_inst.end_date)
    # If post is for event in the future all the events show up in the event drop down
    if event_inst.end_date > datetime.date.today():
        add_post_form.fields['event'].queryset = Events.objects.future_events()

    context = {
        'post_form': add_post_form,
        'page_title': 'Edit post',
    }
    return render(request, 'posts/edit_post.html', context)
Example #28
0
def questions(request, survey_id, question_id=None):
    survey = get_object_or_404(Survey, id=survey_id)
    if request.method == 'GET':
        qs = Question.objects.filter(survey__id=survey_id).order_by('order', 'id')
        return api_utils.response(request, qs, QuestionGrid)
    elif request.method == 'POST':
        form = api_utils.load_form(request, QuestionForm)
        if form.is_valid():
            question = form.save(commit=False)
            question.survey = survey
            if question.order is None:
                res = Question.objects.filter(survey__id=survey_id).aggregate(Max('order'))
                max_order = res['order__max']
                if max_order:
                    question.order = max_order + 1
                else:
                    question.order = 0
            question.save()
            qs = Question.objects.filter(id=question.id)
            return api_utils.response(request, qs, QuestionGrid)
        else:
            return api_utils.response_error(request, form)
    elif request.method == 'DELETE':
        question = get_object_or_404(Question, id=question_id)
        question.delete()
        return api_utils.success()
    raise Http404
Example #29
0
def AgendaYear(request, member_pk=None, year=None):
    """ Main listing, years and months; three years per page."""
    # prev / next years
    member = None
    if member_pk:
        member = get_object_or_404(C4CUser, pk=member_pk)
    else:
        member = get_object_or_404(C4CUser, user=request.user)

    if member != request.user.c4cuser and not member.network.filter(pk=request.user.pk).exists():
        return HttpResponseNotFound('<h1>Page not found</h1>')

    if year:
        year = int(year)
    else:
        year = time.localtime()[0]

    # create a list of months for each year, indicating ones that contain entries and current
    mlst = _get_monthes_for_year(member, year)

    has_entries = False
    for month in mlst:
        if len(month["entries"]) != 0:
            has_entries = True

    context = {'months': mlst, 'member': member, 'year': year, 'has_entries': has_entries}

    return render(request, "agenda.html", context)
Example #30
0
def product_add(request, bill_id, product_id):
    """ Add a product to a bill. If this product contains others products,
    we have to add them too.

    :param request: HttpRequest request
    :param bill_id: Facture
    :param product_id: Produit
    """
    bill = get_object_or_404(Facture, pk=bill_id)
    if not set_edition_status(request, bill):
        LOG.debug("[F%s] bill is already in edition mode" % bill_id)
        return bill_view(request, bill.id)
    product = get_object_or_404(Produit, pk=product_id)

    # how many products to add
    count = int(request.session.get('count', 1))
    LOG.debug("[F%s] get %d X %s" % (bill_id, count, product))
    if count > 1:
        request.session['product_to_add'] = product_id
        request.session['product_count'] = count
        request.session['count'] = 1

    sold = ProduitVendu(produit=product)
    sold.save()
    LOG.debug("[F%s] ProduitVendu(%s) created" % (bill_id, product))
    bill.add_product(sold)
    request.session["products_modified"] = bill_id
    return sold_working(request, bill_id, sold.id)