django.shortcuts.get_object_or_404

Here are the examples of the python api django.shortcuts.get_object_or_404 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

177 Examples 7

Example 51

Project: django-lean Source File: views.py
def experiment_details(request, experiment_name,
                       template_name="experiments/experiment_details.html"):
    """
    Displays a view with details for a specific experiment.
    Exposes:
        "experiment" (the experiment model)
        "daily_data" (An array of dicts with:
            {"date",
             "engagement_data": {
               "control_group_size",
               "control_group_score",
               "test_group_size",
               "test_group_score",
               "test_group_improvement",
               "confidence"
              },
              "conversion_data": {
                "test_group_size",
                "control_group_size",
                "goal_types": {
                  <goal-type-name>: {
                    "test_count",
                    "control_count",
                    "test_rate",
                    "control_rate",
                    "improvement",
                    "confidence"
                  }
                },
                "totals": {
                  "test_count",
                  "control_count",
                  "test_rate",
                  "control_rate",
                  "improvement",
                  "confidence"
                }
               }
             })
    
    """
    experiment = get_object_or_404(Experiment, name=experiment_name)
    
    daily_data = []
    
    start_date = experiment.start_date
    if experiment.start_date:
        if experiment.end_date:
            if experiment.end_date > date.today():
                # This experiment hasn't finished yet, so don't show details for days in the future
                end_date = date.today()
            else:
                end_date = experiment.end_date
        else:
            end_date = date.today() - timedelta(days=1)
        current_date = end_date
        while current_date >= start_date:
            daily_engagement_data = None
            daily_conversion_data = None
            engagement_report = None
            conversion_report = None
            try:
                engagement_report = DailyEngagementReport.objects.get(experiment=experiment,
                                                                  date=current_date)
            except:
                l.warn("No engagement report for date %s and experiment %s" %
                       (current_date, experiment.name))
            daily_conversion_data = get_conversion_data(experiment, current_date)
            
            if engagement_report:
                improvement = None
                
                if engagement_report.control_score > 0:
                    improvement = ((engagement_report.test_score -
                                    engagement_report.control_score) /
                                   engagement_report.control_score) * 100
                daily_engagement_data = {
                    "control_group_size": engagement_report.control_group_size,
                    "control_group_score": engagement_report.control_score,
                    "test_group_size": engagement_report.test_group_size,
                    "test_group_score": engagement_report.test_score,
                    "test_group_improvement": improvement,
                    "confidence": engagement_report.confidence}
            daily_data.append({
                    "date": current_date,
                    "conversion_data": daily_conversion_data,
                    "engagement_data": daily_engagement_data})
            current_date = current_date - timedelta(1)
    context_var = {"experiment": experiment,
                   "daily_data": daily_data,
                   "experiment_states": experiment_states,
                   "root_path": "../../",
                   "title": "Experiment Report"}
    return render_to_response(template_name, context_var,
                              context_instance=RequestContext(request))

Example 52

Project: Arkestra Source File: views.py
Function: person
def person(request, slug, active_tab=""):
    """
    Responsible for the person pages
    """
    # does this Person even exist?
    person = get_object_or_404(Person, slug=slug, active=True)

    meta = {}

    tabs = PERSON_TABS(person, active_tab)

    if active_tab:
        if active_tab not in tabs.live_tabs:
            raise Http404

        active_tab = "_" + tabs.live_tabs[active_tab]["tab"]
        meta = {"description": tabs.description}

    person.links = object_links(person)

    # we have a home_role, but we should also provide a role, even where it's
    # good enough to give us an address
    home_role = person.get_role

    if home_role:
        entity = home_role.entity
    # don't rely on home_role.entity - could be None or overridden
    entity = person.get_entity

    building = person.get_building

    email = person.get_email()
    phone = person.get_phone_contacts()

    # contact = person.get_please_contact()

    if person.please_contact:
        precise_location = None
    else:
        precise_location = person.precise_location
    access_note = person.access_note

    if home_role:
        description = ", ".join(
            (home_role.__unicode__(), entity.__unicode__())
        )
        request.current_page = entity.get_website
    else:
        description = Entity.objects.base_entity().__unicode__()
        request.current_page = Entity.objects.base_entity().get_website

    # if we don't have an active_tab, meta["description"] is ""
    meta.setdefault(
        "description", " ".join((person.__unicode__(), description))
        )

    if entity:
        template = entity.get_template()
    # no memberships, no useful information
    else:
        template = Entity.objects.base_entity().get_template()

    if tabs.tabs:
        if not active_tab:
            # find out what to add to the url for this tab
            active_tab = tabs.tabs[0]["address"]
            # mark the tab as active for the template
            tabs.tabs[0]["active"] = True
        # fewer than 2? not worth having tabs!
        if len(tabs.tabs) == 1:
            tabs.tabs = []

    # there's a problem here - pages such as Cardiff's
    # /person/dr-kathrine-jane-craig/ don't get the menu right - why?
    # print "cuem", request.auto_page_url, request.path, request.current_page,
    # entity.get_website

    return render_to_response(
        "contacts_and_people/person%s.html" % active_tab,
        {
            "person": person,  # personal information
            "home_role": home_role,  # entity and position
            "entity": entity,
            "template": template,  # from entity
            "building": building,
            "email": email,  # from person or please_contact
            "precise_location": precise_location,  # from person, or None
            "phone": phone,
            "full_address": person.get_full_address,
            "access_note": access_note,  # from person
            "tabs": tabs.tabs,
            "tab_object": person,
            "active_tab": active_tab,
            "meta": meta,
        },
        RequestContext(request),
    )

Example 53

Project: 1flow Source File: __init__.py
@token_protected
def export_content(request, **kwargs):
    """ Export recent feeds/articles as JSON. """

    since = kwargs.get('since')
    until = kwargs.get('until', None)
    format = request.GET.get('format', 'json')
    folder_id = kwargs.get('folder_id', None)
    folder_slug = kwargs.get('folder_slug', None)

    if folder_id:
        folder = get_object_or_404(Folder, id=folder_id)

    elif folder_slug:
        folder = get_object_or_404(Folder, slug=folder_slug)

    else:
        try:
            default_user_config = Configuration.objects.get(
                name='export_feeds_default_user')

        except Configuration.DoesNotExist:
            folder = None

        else:
            folder = User.objects.get(
                username=default_user_config.value).root_folder

    if format == 'json':

        def content_generator():

            pretty_print = human_user_agent(request)
            new_lines = u'\n' if pretty_print else u''
            indentation = u'  ' if pretty_print else u''

            yield u'{{{0}{1}"data":{0}{1}{1}[{0}'.format(new_lines,
                                                         indentation)

            data_chunked = 0

            try:
                for chunk, last in lookahead(BaseFeed.export_content(
                                             since, until, folder=folder)):

                    if last:
                        format_string = u'{1}{1}{1}{2}{0}'

                    else:
                        format_string = u'{1}{1}{1}{2},{0}'

                    # With JSON util, we overcome the now-traditional
                    # "datetime is not JSON serializable" error.
                    yield format_string.format(
                        new_lines,
                        indentation,
                        json.dumps(
                            chunk,
                            default=json_util.default,
                            indent=2
                            if pretty_print else None,

                            separators=(',', ': ')
                            if pretty_print else (',', ':'),
                        )
                    )

                    data_chunked += 1

            except Exception as e:
                LOGGER.exception(u'Could not export content')

                # ID is unavailable if the exception
                # happens in the low-level WSGI.
                yield u'{1}{1}],{0}{1}{1}"sentry_id": "{2}",{0}'.format(
                    new_lines, indentation,
                    getattr(request, 'sentry', {'id': 'unavailable'})['id'])

                yield u'{1}{1}"exception": "{2}",{0}'.format(
                    new_lines, indentation, unicode(e))

                yield u'{1}{1}"result": "ERR"{0}}}'.format(
                    new_lines, indentation)

            else:
                yield u'{1}{1}],{0}{1}{1}"result": "OK"{0}}}'.format(
                    new_lines, indentation)

        response = StreamingHttpResponse(content_generator(),
                                         content_type="application/json")

        response['Content-Disposition'] = 'attachment; filename="export.json"'
        return response
    else:
        return HttpResponseBadRequest(u'Unknown format “%s”' % format)

Example 54

Project: patchwork Source File: bundle.py
@login_required
def setbundle(request):
    context = PatchworkRequestContext(request)

    bundle = None

    if request.method == 'POST':
        action = request.POST.get('action', None)
        if action is None:
            pass
        elif action == 'create':
            project = get_object_or_404(Project,
                                        id=request.POST.get('project'))
            bundle = Bundle(owner=request.user, project=project,
                            name=request.POST['name'])
            bundle.save()
            patch_id = request.POST.get('patch_id', None)
            if patch_id:
                patch = get_object_or_404(Patch, id=patch_id)
                try:
                    bundle.append_patch(patch)
                except Exception:
                    pass
            bundle.save()
        elif action == 'add':
            bundle = get_object_or_404(Bundle,
                                       owner=request.user,
                                       id=request.POST['id'])
            bundle.save()

            patch_id = request.get('patch_id', None)
            if patch_id:
                patch_ids = patch_id
            else:
                patch_ids = get_patch_ids(request.POST)

            for id in patch_ids:
                try:
                    patch = Patch.objects.get(id=id)
                    bundle.append_patch(patch)
                except:
                    pass

            bundle.save()
        elif action == 'delete':
            try:
                bundle = Bundle.objects.get(owner=request.user,
                                            id=request.POST['id'])
                bundle.delete()
            except Exception:
                pass

            bundle = None

    else:
        bundle = get_object_or_404(Bundle, owner=request.user,
                                   id=request.POST['bundle_id'])

    if 'error' in context:
        pass

    if bundle:
        return HttpResponseRedirect(
            django.core.urlresolvers.reverse(
                'patchwork.views.bundle.bundle',
                kwargs={'bundle_id': bundle.id}
            )
        )
    else:
        return HttpResponseRedirect(
            django.core.urlresolvers.reverse(
                'patchwork.views.bundle.list')
        )

Example 55

Project: blue-channel Source File: views.py
def profile(request, username, template_name="profiles/profile.html"):
    other_user = get_object_or_404(User, username=username)
    if request.user.is_authenticated():
        # is_friend = Friendship.objects.are_friends(request.user, other_user)
        # is_following = Following.objects.is_following(request.user, other_user)
        # other_friends = Friendship.objects.friends_for_user(other_user)
        if request.user == other_user:
            is_me = True
        else:
            is_me = False
    else:
        other_friends = []
        is_friend = False
        is_me = False
        is_following = False
    
    if request.user.is_authenticated() and request.method == "POST" and not is_me:
        
        # @@@ some of this should go in zwitschern itself
        
        if request.POST["action"] == "follow":
            Following.objects.follow(request.user, other_user)
            is_following = True
            request.user.message_set.create(message=_("You are now following %(other_user)s") % {'other_user': other_user})
            if notification:
                notification.send([other_user], "tweet_follow", {"user": request.user})
        elif request.POST["action"] == "unfollow":
            Following.objects.unfollow(request.user, other_user)
            is_following = False
            request.user.message_set.create(message=_("You have stopped following %(other_user)s") % {'other_user': other_user})
    
    """if is_friend:
        invite_form = None
        previous_invitations_to = None
        previous_invitations_from = None
    else:
        if request.user.is_authenticated() and request.method == "POST":
            if request.POST["action"] == "invite":
                invite_form = InviteFriendForm(request.user, request.POST)
                if invite_form.is_valid():
                    invite_form.save()
            else:
                invite_form = InviteFriendForm(request.user, {
                    'to_user': username,
                    'message': ugettext("Let's be friends!"),
                })
                if request.POST["action"] == "accept": # @@@ perhaps the form should just post to friends and be redirected here
                    invitation_id = request.POST["invitation"]
                    try:
                        invitation = FriendshipInvitation.objects.get(id=invitation_id)
                        if invitation.to_user == request.user:
                            invitation.accept()
                            request.user.message_set.create(message=_("You have accepted the friendship request from %(from_user)s") % {'from_user': invitation.from_user})
                            is_friend = True
                            other_friends = Friendship.objects.friends_for_user(other_user)
                    except FriendshipInvitation.DoesNotExist:
                        pass
        else:
            invite_form = InviteFriendForm(request.user, {
                'to_user': username,
                'message': ugettext("Let's be friends!"),
            })
    previous_invitations_to = FriendshipInvitation.objects.filter(to_user=other_user, from_user=request.user)
    previous_invitations_from = FriendshipInvitation.objects.filter(to_user=request.user, from_user=other_user)"""
    
    if is_me:
        if request.method == "POST":
            if request.POST["action"] == "update":
                profile_form = ProfileForm(request.POST, instance=other_user.get_profile())
                if profile_form.is_valid():
                    profile = profile_form.save(commit=False)
                    profile.user = other_user
                    profile.save()
            else:
                profile_form = ProfileForm(instance=other_user.get_profile())
        else:
            profile_form = ProfileForm(instance=other_user.get_profile())
    else:
        profile_form = None

    return render_to_response(template_name, {
        "profile_form": profile_form,
        "is_me": is_me,
        #"is_friend": is_friend,
        #"is_following": is_following,
        "other_user": other_user,
        #"other_friends": other_friends,
        #"invite_form": invite_form,
        #"previous_invitations_to": previous_invitations_to,
        #"previous_invitations_from": previous_invitations_from,
    }, context_instance=RequestContext(request))

Example 56

Project: canvas Source File: view_helpers.py
    def __init__(self, request, short_id, page=None, gotoreply=None):
        try:
            mapping_id = get_mapping_id_from_short_id(short_id)
        except ValueError:
            raise Http404

        self.request = request
        self.short_id = short_id
        self.page = page
        try:
            self.gotoreply = int(gotoreply)
        except TypeError:
            self.gotoreply = None

        _op_comment = get_object_or_404(Comment.published, id=mapping_id)

        # Get relevant OP data.
        _op_content = _op_comment.reply_content
        op_content = _op_content.details() if _op_content else None

        op_comment = _op_comment.details
        op_category = _op_comment.category.details() if _op_comment.category else Category.ALL.details()

        linked_comment = op_comment
        _linked_comment = _op_comment

        reply_ids = list(_op_comment.get_replies().values_list('id', flat=True))

        # Remove user-hidden comments.
        reply_ids = remove_hidden_comment_ids(request.user, reply_ids)

        # Pagination.
        explicit_page_view = bool(page)
        num_replies = len(reply_ids)
        if gotoreply is not None:
            gotoreply = int(gotoreply)
            try:
                page = page_divide(reply_ids.index(gotoreply)+1, knobs.COMMENTS_PER_PAGE)
                # If going to a reply on the last page, show 'current'.
                if reply_ids.index(gotoreply) + 1 >= num_replies - knobs.COMMENTS_PER_PAGE:
                    page = 'current'
            except ValueError:
                page = '1'

            # Grab the gotoreply's content for metadata
            _linked_comment = Comment.objects.get_or_none(id=gotoreply)
            if _linked_comment:
                linked_comment = _linked_comment.details
        elif page is None:
            page = '1'

        self.page_reply_ids, self.page_current, self.page_next, self.page_last = paginate(
                reply_ids, page=page, per_page=knobs.COMMENTS_PER_PAGE)
        self.page_penultimate = self.page_last - 1
        # Make it easy for Django to do a for loop on the page numbers.
        pages = xrange(1, self.page_last + 1)

        self.op_comment     = op_comment
        self._op_comment    = _op_comment
        self.op_content     = op_content
        self._op_content    = _op_content
        self.op_category    = op_category
        self.linked_comment = linked_comment
        self._linked_comment = _linked_comment
        self.page           = page
        self.pages          = pages
        self.per_page       = knobs.COMMENTS_PER_PAGE
        self.num_replies    = num_replies
        self.reply_ids      = reply_ids
        self.explicit_page_view = explicit_page_view
        self.is_author = request.user == _op_comment.author

Example 57

Project: djangodash2012 Source File: views.py
def project(request, company_slug, project_slug):
    """ Project page view. """
    project = get_object_or_404(TestProject, company__slug=company_slug,
                                slug=project_slug)
    testcases = project.testcases.all()

    testcase = None
    if request.GET.get('testcase'):
        testcase = get_object_or_404(TestCase, project=project,
                                     slug=request.GET.get('testcase'))
    elif testcases:
        testcase = testcases[0]

    tc_form = TestCaseForm(instance=testcase)

    if request.POST:
        if not can_edit_project(request.user, project):
            return HttpResponseForbidden()

        if request.POST.get('action') == 'add_testcase':
            name = TestCase.objects.get_unique_new_name()
            order = TestCaseStep.objects.filter(testcase=testcase).order_by('-order')
            if order:
                order = order[0].order + 1
            else:
                order = 1
            tc = TestCase.objects.create(name=name, project=project, order=order)
            return redirect(request.path + '?testcase=%s' % tc.slug)

        if request.POST.get('action') == 'delete_testcase':
            TestCase.objects.filter(pk=request.POST.get('testcase')).delete()
            return redirect(request.path)

        if request.POST.get('action') in ['save_step', 'add_step']:
            if request.POST.get('action') == 'add_step':
                order = TestCaseStep.objects.filter(testcase=testcase).order_by('-order')
                if order:
                    order = order[0].order + 1
                else:
                    order = 1
                step = [TestCaseStep(testcase=testcase, order=order)]
            else:
                step = TestCaseStep.objects.filter(pk=request.POST.get('teststep'))

            if step:
                step = step[0]
                step.params = Params()
                for param in request.POST:
                    if param.startswith('js_'):
                        step.params[param[3:]] = request.POST[param]
                method = request.POST.get('method')
                url = request.POST.get('url')
                if url:
                    step.url = url
                if method and method in dict(method_choices):
                    step.method = method
                step.save()
            return redirect(request.path + '?testcase=%s' % testcase.slug)

        if request.POST.get('action') == 'delete_step':
            TestCaseStep.objects.filter(pk=request.POST.get('teststep')).delete()
            return redirect(request.path + '?testcase=%s' % testcase.slug)

        if request.POST.get('action') == 'add_assertion':
            lhs = request.POST.get('lhs')
            rhs = request.POST.get('rhs')
            operator = request.POST.get('operator')
            teststep = TestCaseStep.objects.filter(testcase=testcase).order_by('-order')[0]
            order = TestCaseAssert.objects.filter(step=teststep).order_by('-order')
            if order:
                order = order[0].order + 1
            else:
                order = 1
            TestCaseAssert.objects.create(step=teststep,
                lhs=lhs, rhs=rhs, operator=operator, order=order)
            return redirect(request.path + '?testcase=%s' % testcase.slug)

        if request.POST.get('action') == 'save_assert':
            lhs = request.POST.get('lhs')
            rhs = request.POST.get('rhs')
            operator = request.POST.get('operator', 'eq')
            assertion = TestCaseAssert.objects.get(pk=request.POST.get('assert'))

            assertion.lhs = lhs
            assertion.rhs = rhs
            assertion.save()
            return redirect(request.path + '?testcase=%s' % testcase.slug)

        if request.POST.get('action') == 'delete_assert':
            assertion = TestCaseAssert.objects.get(pk=request.POST.get('assert'))
            if assertion:
                assertion.delete()
            return redirect(request.path + '?testcase=%s' % testcase.slug)

        tc_form = TestCaseForm(request.POST, instance=testcase)
        if tc_form.is_valid():
            tc_form.save()
            return redirect(request.path + '?testcase=%s' % testcase.slug)

    data = {
        'project': project,
        'testcases': testcases,
        'testcase': testcase,
        'tc_form': tc_form,
        'new': request.GET.get('new'),
        'methods': method_choices,
    }
    return TemplateResponse(request, 'fortuitus/feditor/project.html', data)

Example 58

Project: wger Source File: plan.py
def export_pdf(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of a nutrition plan

    See also
    * http://www.blog.pythonlibrary.org/2010/09/21/reportlab
    * http://www.reportlab.com/apis/reportlab/dev/platypus.html
    '''

    # Load the plan
    if uidb64 is not None and token is not None:
        if check_token(uidb64, token):
            plan = get_object_or_404(NutritionPlan, pk=id)
        else:
            return HttpResponseForbidden()
    else:
        if request.user.is_anonymous():
            return HttpResponseForbidden()
        plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)

    plan_data = plan.get_nutritional_values()

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            title=_('Nutrition plan'),
                            author='wger Workout Manager',
                            subject=_('Nutritional plan %s') % request.user.username)

    # Background colour for header
    # Reportlab doesn't use the HTML hexadecimal format, but has a range of
    # 0 till 1, so we have to convert here.
    header_colour = colors.Color(int('73', 16) / 255.0,
                                 int('8a', 16) / 255.0,
                                 int('5f', 16) / 255.0)

    # container for the 'Flowable' objects
    elements = []
    data = []

    # Iterate through the Plan
    meal_markers = []
    ingredient_markers = []

    # Meals
    i = 0
    for meal in plan.meal_set.select_related():
        i += 1

        meal_markers.append(len(data))

        if not meal.time:
            p = Paragraph(u'<para align="center"><strong>{nr} {meal_nr}</strong></para>'
                          .format(nr=_('Nr.'), meal_nr=i),
                          styleSheet["Normal"])
        else:
            p = Paragraph(u'<para align="center"><strong>'
                          u'{nr} {meal_nr} - {meal_time}'
                          u'</strong></para>'
                          .format(nr=_('Nr.'), meal_nr=i, meal_time=meal.time.strftime("%H:%M")),
                          styleSheet["Normal"])
        data.append([p])

        # Ingredients
        for item in meal.mealitem_set.select_related():
            ingredient_markers.append(len(data))

            p = Paragraph(u'<para>{0}</para>'.format(item.ingredient.name), styleSheet["Normal"])
            if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:
                unit_name = 'g'
            else:
                unit_name = ' ' + item.weight_unit.unit.name

            data.append([Paragraph(u"{0}{1}".format(item.amount, unit_name), styleSheet["Normal"]),
                         p])

    # Set general table styles
    table_style = []

    # Set specific styles, e.g. background for title cells
    for marker in meal_markers:
        # Set background colour for headings
        table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))
        table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))

        # Make the headings span the whole width
        table_style.append(('SPAN', (0, marker), (-1, marker)))

    # has the plan any data?
    if data:
        t = Table(data, style=table_style)

        # Manually set the width of the columns
        t._argW[0] = 2.5 * cm

    # There is nothing to output
    else:
        t = Paragraph(_('<i>This is an empty plan, what did you expect on the PDF?</i>'),
                      styleSheet["Normal"])

    # Set the title (if available)
    if plan.description:
        p = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
                      {'description': plan.description},
                      styleSheet["Bold"])
        elements.append(p)

        # Filler
        elements.append(Spacer(10 * cm, 0.5 * cm))

    # append the table to the docuement
    elements.append(t)
    elements.append(Paragraph('<para>&nbsp;</para>', styleSheet["Normal"]))

    # Create table with nutritional calculations
    data = []
    data.append([Paragraph(u'<para align="center">{0}</para>'.format(_('Nutritional data')),
                 styleSheet["Bold"])])
    data.append([Paragraph(_('Macronutrients'), styleSheet["Normal"]),
                 Paragraph(_('Total'), styleSheet["Normal"]),
                 Paragraph(_('Percent of energy'), styleSheet["Normal"]),
                 Paragraph(_('g per body kg'), styleSheet["Normal"])])
    data.append([Paragraph(_('Energy'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['energy']), styleSheet["Normal"])])
    data.append([Paragraph(_('Protein'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['protein']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['protein']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['protein']), styleSheet["Normal"])])
    data.append([Paragraph(_('Carbohydrates'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['carbohydrates']),
                           styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['carbohydrates']),
                           styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['carbohydrates']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Sugar content in carbohydrates'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['carbohydrates_sugar']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Fat'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fat']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['fat']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['fat']), styleSheet["Normal"])])
    data.append([Paragraph(_('Saturated fat content in fats'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fat_saturated']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Fibres'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fibres']), styleSheet["Normal"])])
    data.append([Paragraph(_('Sodium'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['sodium']), styleSheet["Normal"])])

    table_style = []
    table_style.append(('BOX', (0, 0), (-1, -1), 1.25, colors.black))
    table_style.append(('GRID', (0, 0), (-1, -1), 0.40, colors.black))
    table_style.append(('SPAN', (0, 0), (-1, 0)))  # Title
    table_style.append(('SPAN', (1, 2), (-1, 2)))  # Energy
    table_style.append(('SPAN', (1, 5), (-1, 5)))  # Sugar
    table_style.append(('SPAN', (1, 7), (-1, 7)))  # Saturated fats
    table_style.append(('SPAN', (1, 8), (-1, 8)))  # Fibres
    table_style.append(('SPAN', (1, 9), (-1, 9)))  # Sodium
    t = Table(data, style=table_style)
    t._argW[0] = 5 * cm
    elements.append(t)

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    created = datetime.date.today().strftime("%d.%m.%Y")
    url = reverse('nutrition:plan:view', kwargs={'id': plan.id})
    p = Paragraph('''<para align="left">
                        %(date)s -
                        <a href="%(url)s">%(url)s</a> -
                        %(created)s
                        %(version)s
                    </para>''' %
                  {'date': _("Created on the <b>%s</b>") % created,
                   'created': "wger Workout Manager",
                   'version': get_version(),
                   'url': request.build_absolute_uri(url), },
                  styleSheet["Normal"])
    elements.append(p)
    doc.build(elements)

    response['Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf'
    response['Content-Length'] = len(response.content)
    return response

Example 59

Project: aemanager Source File: views.py
@settings_required
@subscription_required
@commit_on_success
def invoice_create_or_edit(request, id=None, customer_id=None, proposal_id=None):
    if id:
        title = _('Edit an invoice')
        invoice = get_object_or_404(Invoice, pk=id, owner=request.user)
        customer = invoice.customer
    else:
        title = _('Draw up an invoice')
        invoice = None
        """
        in case of invoice creation, if a customer_id is not provided by url
        we look for it in the autocomplete field (case of direct invoice draw up
        without proposal)
        """
        if request.method == 'POST':
            autocompleted_customer_id = request.POST.get('contact-customer_id')
            if not customer_id:
                customer_id = autocompleted_customer_id
        if customer_id:
            customer = get_object_or_404(Contact, pk=customer_id, owner=request.user)
        else:
            customer = None

    address = None
    original_customer_name = None
    if customer:
        address = customer.address
        original_customer_name = customer.name

    proposal = None
    if proposal_id:
        proposal = get_object_or_404(Proposal,
                                     pk=proposal_id,
                                     project__customer=customer,
                                     owner=request.user,
                                     state__in=[PROPOSAL_STATE_ACCEPTED])

    InvoiceRowFormSet = inlineformset_factory(Invoice,
                                              InvoiceRow,
                                              form=InvoiceRowForm,
                                              fk_name="invoice",
                                              extra=1)

    proposals = Proposal.objects.get_proposals_for_invoice(customer, request.user, invoice)

    if request.method == 'POST':
        contactForm = ContactQuickCreateForm(request.POST,
                                             instance=customer,
                                             prefix="contact")
        if customer:
            contactForm.setToEditMode()

        addressForm = AddressForm(request.POST,
                                  instance=address,
                                  prefix="address")
        invoiceForm = InvoiceForm(request.POST,
                                  instance=invoice,
                                  prefix="invoice")
        invoicerowformset = InvoiceRowFormSet(request.POST,
                                              instance=invoice)
        for invoicerowform in invoicerowformset.forms:
            invoicerowform.fields['proposal'].queryset = proposals

        if contactForm.is_valid() and addressForm.is_valid() and \
           invoiceForm.is_valid() and invoicerowformset.is_valid():
            try:
                user = request.user

                address = addressForm.save(commit=False)
                address.save(user=user)

                customer = contactForm.save(commit=False)
                if not customer.contact_type:
                    customer.contact_type = CONTACT_TYPE_COMPANY
                # restore original name since it shouldn't be changed in invoice
                if original_customer_name:
                    customer.name = original_customer_name
                customer.address_id = address.id
                customer.save(user=user)

                invoice = invoiceForm.save(commit=False)
                invoice.customer = customer
                if invoice.paid_date:
                    invoice.state = INVOICE_STATE_PAID
                invoice.save(user=user)
                invoiceForm.save_m2m()
                for invoicerowform in invoicerowformset.forms:
                    if invoicerowform not in invoicerowformset.deleted_forms and invoicerowform.cleaned_data:
                        invoicerow = invoicerowform.save(commit=False)
                        invoicerow.invoice = invoice
                        invoicerow.save(user=user)

                        if invoicerow.proposal and invoicerow.balance_payments and invoice.paid_date:
                            invoicerow.proposal.state = PROPOSAL_STATE_BALANCED
                            invoicerow.proposal.save()

                for deleted_invoicerowform in invoicerowformset.deleted_forms:
                    deleted_invoicerowform.instance.delete()

                invoice.check_amounts()

                messages.success(request, _('The invoice has been saved successfully'))
                if invoice.paid_date and invoice.paid_date > datetime.date.today():
                    messages.warning(request, _("Paid date is in the future, is this normal ?"))
                if invoice.execution_begin_date and invoice.execution_end_date and invoice.execution_begin_date > invoice.execution_end_date:
                    messages.warning(request, _("Execution begin date is greater than execution end date, is this normal ?"))
                if invoice.penalty_date and invoice.penalty_date < invoice.payment_date:
                    messages.warning(request, _("Payment date is greater than penalty date, is this normal ?"))
                return redirect(reverse('invoice_detail', kwargs={'id': invoice.id}))
            except InvoiceRowAmountError:
                transaction.rollback()
                messages.error(request, _("Amounts invoiced can't be greater than proposals remaining amounts"))
            except InvoiceIdNotUniqueError:
                transaction.rollback()
                invoiceForm._errors["invoice_id"] = invoiceForm.error_class([_("Invoice id must be unique")])
        else:
            messages.error(request, _('Data provided are invalid'))
    else:
        next_invoice_id = Invoice.objects.get_next_invoice_id(request.user)
        initial_data = None
        if not invoice:
            initial_data = {'invoice_id': next_invoice_id,
                            'edition_date': datetime.datetime.now()}
            if proposal:
                initial_data['execution_begin_date'] = proposal.begin_date
                initial_data['execution_end_date'] = proposal.end_date

        contactForm = ContactQuickCreateForm(instance=customer,
                                             prefix="contact")
        if customer:
            contactForm.setToEditMode()
        addressForm = AddressForm(instance=address,
                                  prefix="address")

        invoiceForm = InvoiceForm(instance=invoice,
                                  prefix="invoice",
                                  initial=initial_data)

        initial_row_data = None
        if proposal:
            initial_row_data = []
            for proposal_row in proposal.proposal_rows.all():
                initial_row_data.append({'label': proposal_row.label,
                                         'proposal': proposal,
                                         'balance_payments': True,
                                         'category': proposal_row.category,
                                         'quantity': proposal_row.quantity,
                                         'detail': proposal_row.detail,
                                         'unit_price': proposal_row.unit_price})
            InvoiceRowFormSet.extra = len(initial_row_data) + 1

        invoicerowformset = InvoiceRowFormSet(instance=invoice)
        i = 0
        for invoicerowform in invoicerowformset.forms:
            invoicerowform.fields['proposal'].queryset = proposals
            # for all rows except last
            if i < InvoiceRowFormSet.extra - 1:
                invoicerowform.initial = initial_row_data[i]
                i = i + 1


    return render_to_response('invoice/edit.html',
                              {'active': 'accounts',
                               'title': title,
                               'from_proposal': proposal,
                               'contactForm': contactForm,
                               'addressForm': addressForm,
                               'invoiceForm': invoiceForm,
                               'invoicerowformset': invoicerowformset},
                               context_instance=RequestContext(request))

Example 60

Project: zorna Source File: views.py
def edit_calendar_reccurrent_event(request, event_id, event, occurrence):
    instance_event_details = EventDetails.objects.get_eventdetails_for_object(
        event)
    calendars = get_user_calendars(request.user, ['manager', 'creator'])
    if event.calendar.pk not in [c.calendar_id for c in calendars]:
        return HttpResponseRedirect(reverse('view_calendar', args=[]))
    original_start = event.start
    params = event.rule.get_params()
    initial_data = {}
    initial_data['rule'] = event.rule.frequency
    if 'interval' in params:
        initial_data['interval'] = params['interval']
    if 'byweekday' in params:
        initial_data['weekdays'] = params['byweekday'] if type(params[
                                                               'byweekday']) == type(list()) else [params['byweekday']]
    initial_data['start'] = occurrence.start
    initial_data['end'] = occurrence.end
    initial_data['title'] = occurrence.title
    initial_data['description'] = occurrence.description

    if request.method == 'POST':
        form = EditEventForm(data=request.POST, instance=event)
        form_details = EditEventDetailsForm(
            data=request.POST, instance=instance_event_details)

        action = request.POST.get('action', None)
        if action and action == 'deleteone':
            occurrence.cancel()
            return HttpResponseRedirect(reverse('view_calendar', args=[]))

        if action and action == 'deleteall':
            persisted_occurrences = event.occurrence_set.all()
            for occ in persisted_occurrences:
                try:
                    EventDetails.objects.get_eventdetails_for_object(
                        occ).delete()
                except:
                    pass
            event.rule.delete()
            event.delete()
            instance_event_details.delete()
            return HttpResponseRedirect(reverse('view_calendar', args=[]))

        if action and action == 'updateevent' and form.is_valid():  # update only this occurrence
            occurrence.title = form.cleaned_data['title']
            occurrence.description = form.cleaned_data['description']
            occurrence.start = form.cleaned_data[
                'start'].strftime('%Y-%m-%d %H:%M:%S')
            occurrence.end = form.cleaned_data[
                'end'].strftime('%Y-%m-%d %H:%M:%S')
            occurrence.save()
            EventDetails.objects.create_details(
                occurrence,
                request.POST.get('location', ''),
                request.POST.get('free_busy', 0),
                request.POST.get('privacy', 0),
            )
            return HttpResponseRedirect(reverse('view_calendar', args=[]))

        if form.is_valid():
            calendar = get_object_or_404(
                ZornaCalendar, pk=request.POST['calendar_id'])
            evt = form.save(commit=False)
            evt.calendar = calendar.calendar
            if 'end_recurring_period' in form.cleaned_data and form.cleaned_data['end_recurring_period']:
                evt.end_recurring_period = evt.end_recurring_period + \
                    datetime.timedelta(days=1, seconds= -1)
            rule = event.rule
            if rule and request.POST['rule'] == '':
                persisted_occurrences = event.occurrence_set.all()
                for occ in persisted_occurrences:
                    try:
                        EventDetails.objects.get_eventdetails_for_object(
                            occ).delete()
                    except:
                        pass
                event.rule = None
                rule.delete()

            if request.POST['rule'] != '':
                params = "interval:" + request.POST['interval']
                if request.POST['rule'] == 'WEEKLY':
                    wl = request.POST.getlist('weekdays')
                    if not wl:
                        wl = [str((int(evt.start.strftime('%w')) + 6) % 7)]
                    if wl:
                        params += ";byweekday:" + ",".join(wl)
                if evt.rule:
                    evt.rule.name = request.POST['rule']
                    evt.rule.frequency = request.POST['rule']
                    evt.rule.params = params
                    evt.rule.save()
                else:
                    rule = Rule(name=request.POST['rule'],
                                frequency=request.POST['rule'],
                                params=params
                                )
                    rule.save()
                    evt.rule = rule
            if occurrence.start.date() == evt.start.date():
                td = evt.end.date() - evt.start.date()
                evt.start = datetime.datetime.combine(
                    original_start.date(), evt.start.time())
                evt.end = datetime.datetime.combine(
                    original_start.date() + td, evt.end.time())
            evt.save()
            form_details.save()
            return HttpResponseRedirect(reverse('view_calendar', args=[]))
        else:
            form = EditEventForm(data=request.POST)
            form_details = EditEventDetailsForm(data=request.POST)
    else:
        form = EditEventForm(instance=event, initial=initial_data)
        form_details = EditEventDetailsForm(instance=instance_event_details)

    extra_context = {
        'form': form,
        'boccurrence': False,
        'event': event,
        'form_details': form_details,
        'calendars': calendars,
        'calendar': ZornaCalendar.objects.get(calendar=event.calendar)
    }

    context = RequestContext(request)
    return render_to_response('calendars/calendar_edit.html', extra_context, context_instance=context)

Example 61

Project: django-cms Source File: placeholderadmin.py
    @method_decorator(require_POST)
    @xframe_options_sameorigin
    @transaction.atomic
    def copy_plugins(self, request):
        """
        POST request should have the following data:

        - source_language
        - source_placeholder_id
        - source_plugin_id (optional)
        - target_language
        - target_placeholder_id
        - target_plugin_id (optional, new parent)
        """
        source_language = request.POST['source_language']
        source_placeholder_id = request.POST['source_placeholder_id']
        source_plugin_id = request.POST.get('source_plugin_id', None)
        target_language = request.POST['target_language']
        target_placeholder_id = request.POST['target_placeholder_id']
        target_plugin_id = request.POST.get('target_plugin_id', None)
        source_placeholder = get_object_or_404(Placeholder, pk=source_placeholder_id)
        target_placeholder = get_object_or_404(Placeholder, pk=target_placeholder_id)

        if not target_language or not target_language in get_language_list():
            return HttpResponseBadRequest(force_text(_("Language must be set to a supported language!")))

        copy_to_clipboard = target_placeholder.pk == request.toolbar.clipboard.pk

        if source_plugin_id:
            source_plugin = get_object_or_404(CMSPlugin, pk=source_plugin_id)
            reload_required = requires_reload(PLUGIN_COPY_ACTION, [source_plugin])
            if source_plugin.plugin_type == "PlaceholderPlugin":
                # if it is a PlaceholderReference plugin only copy the plugins it references
                inst, cls = source_plugin.get_plugin_instance(self)
                plugins = inst.placeholder_ref.get_plugins_list()
            else:
                plugins = list(
                    source_placeholder.get_plugins().filter(
                        path__startswith=source_plugin.path,
                        depth__gte=source_plugin.depth).order_by('path')
                )
        else:
            plugins = list(
                source_placeholder.get_plugins(language=source_language).order_by('path'))
            reload_required = requires_reload(PLUGIN_COPY_ACTION, plugins)

        if copy_to_clipboard:
            has_permissions = self.has_copy_plugins_permission(request, plugins)
        else:
            # Plugins are being copied from a placeholder in another language
            # using the "Copy from language" placeholder action.
            # Check if the user can copy plugins from source placeholder to
            # target placeholder.
            has_permissions = self.has_copy_from_placeholder_permission(
                request,
                source_placeholder,
                target_placeholder,
                plugins,
            )

        if not has_permissions:
            return HttpResponseForbidden(force_text(
                _('You do not have permission to copy these plugins.')))

        if copy_to_clipboard and not source_plugin_id and not target_plugin_id:
            # if we copy a whole placeholder to the clipboard create
            # PlaceholderReference plugin instead and fill it the content of the
            # source_placeholder.
            ref = PlaceholderReference()
            ref.name = source_placeholder.get_label()
            ref.plugin_type = "PlaceholderPlugin"
            ref.language = target_language
            ref.placeholder = target_placeholder
            ref.save()
            ref.copy_from(source_placeholder, source_language)
        else:
            copy_plugins.copy_plugins_to(
                plugins, target_placeholder, target_language, target_plugin_id)

        plugin_list = CMSPlugin.objects.filter(
                language=target_language,
                placeholder=target_placeholder
            ).order_by('path')
        reduced_list = []

        for plugin in plugin_list:
            reduced_list.append(
                {
                    'id': plugin.pk, 'type': plugin.plugin_type, 'parent': plugin.parent_id,
                    'position': plugin.position, 'desc': force_text(plugin.get_short_description()),
                    'language': plugin.language, 'placeholder_id': plugin.placeholder_id
                }
            )

        self.post_copy_plugins(request, source_placeholder, target_placeholder, plugins)

        # When this is executed we are in the admin class of the source placeholder
        # It can be a page or a model with a placeholder field.
        # Because of this we need to get the admin class instance of the
        # target placeholder and call post_copy_plugins() on it.
        # By doing this we make sure that both the source and target are
        # informed of the operation.
        target_placeholder_admin = self._get_attached_admin(target_placeholder)

        if (target_placeholder_admin and
                target_placeholder_admin.model != self.model):
            target_placeholder_admin.post_copy_plugins(
                request,
                source_placeholder=source_placeholder,
                target_placeholder=target_placeholder,
                plugins=plugins,
            )

        json_response = {'plugin_list': reduced_list, 'reload': reload_required}
        return HttpResponse(json.dumps(json_response), content_type='application/json')

Example 62

Project: mezzanine-wiki Source File: views.py
def wiki_page_list(request, tag=None, username=None,
                   category=None, template="mezawiki/wiki_page_list.html"):
    """
    Display a list of wiki pages that are filtered by tag, 
    author or category.

    Custom templates are checked for using the name
    ``mezawiki/wiki_page_list_XXX.html`` where ``XXX`` is either the
    category slug or author's username if given.
    """
    settings.use_editable()
    templates = []
    wiki_pages = WikiPage.objects.published(for_user=request.user)
    if tag is not None:
        tag = get_object_or_404(Keyword, slug=tag)
        wiki_pages = wiki_pages.filter(keywords__in=tag.assignments.all())
    if category is not None:
        category = get_object_or_404(WikiCategory, slug=category)
        wiki_pages = wiki_pages.filter(categories=category)
        templates.append(u"mezawiki/wiki_post_list_%s.html" %
                          unicode(category.slug))
    author = None
    if username is not None:
        author = get_object_or_404(User, username=username)
        wiki_pages = wiki_pages.filter(user=author)
        templates.append(u"mezawiki/wiki_page_list_%s.html" % username)

    # We want to iterate keywords and categories for each wiki page
    # without triggering "num posts x 2" queries.
    #
    # For Django 1.3 we create dicts mapping wiki page IDs to lists of
    # categories and keywords, and assign these to each wiki page
    #
    # For Django 1.4 we just use prefetch related.

    if VERSION >= (1, 4):
        rel = ("categories", "keywords__keyword")
        wiki_pages = wiki_pages.select_related("user").prefetch_related(*rel)
    else:
        wiki_pages = list(wiki_pages.select_related("user"))
        categories = defaultdict(list)
        if wiki_pages:
            ids = ",".join([str(p.id) for p in wiki_pages])
            for cat in WikiCategory.objects.raw(
                "SELECT * FROM mezzanine_wiki_wikicategory "
                "JOIN mezzanine_wiki_wikipage_categories "
                "ON mezzanine_wiki_wikicategory.id = wikicategory_id "
                "WHERE wikipage_id IN (%s)" % ids):
                categories[cat.wikipage_id].append(cat)
        keywords = defaultdict(list)
        wikipage_type = ContentType.objects.get(app_label="mezzanine_wiki",
                                                model="wikipage")
        assigned = AssignedKeyword.objects.filter(wikipage__in=wiki_pages,
                        content_type=wikipage_type).select_related("keyword")
        for a in assigned:
            keywords[a.object_pk].append(a.keyword)
    for i, page in enumerate(wiki_pages):
        if VERSION < (1, 4):
            setattr(wiki_pages[i], "category_list", categories[page.id])
            setattr(wiki_pages[i], "keyword_list", keywords[page.id])
        else:
            setattr(wiki_pages[i], "category_list",
                    page.categories.all())
            setattr(wiki_pages[i], "keyword_list",
                    [k.keyword for k in page.keywords.all()])

    wiki_pages = paginate(wiki_pages,
                          request.GET.get("page", 1),
                          settings.WIKI_PAGES_PER_PAGE,
                          settings.MAX_PAGING_LINKS)
    context = {"wiki_pages": wiki_pages,
               "tag": tag, "category": category, "author": author}
    templates.append(template)
    return render(request, templates, context)

Example 63

Project: django-timepiece Source File: views.py
@login_required
@transaction.atomic
def create_invoice(request):
    pk = request.GET.get('project', None)
    to_date = request.GET.get('to_date', None)
    if not (pk and to_date):
        raise Http404
    from_date = request.GET.get('from_date', None)
    if not request.user.has_perm('crm.generate_project_invoice'):
        return HttpResponseForbidden('Forbidden')
    try:
        to_date = utils.add_timezone(
            datetime.datetime.strptime(to_date, '%Y-%m-%d'))
        if from_date:
            from_date = utils.add_timezone(
                datetime.datetime.strptime(from_date, '%Y-%m-%d'))
    except (ValueError, OverflowError):
        raise Http404
    project = get_object_or_404(Project, pk=pk)
    initial = {
        'project': project,
        'user': request.user,
        'from_date': from_date,
        'to_date': to_date,
    }
    entries_query = {
        'status': Entry.APPROVED,
        'end_time__lt': to_date + relativedelta(days=1),
        'project__id': project.id
    }
    if from_date:
        entries_query.update({'end_time__gte': from_date})
    invoice_form = InvoiceForm(request.POST or None, initial=initial)
    if request.POST and invoice_form.is_valid():
        entries = Entry.no_join.filter(**entries_query)
        if entries.exists():
            # LOCK the entries until our transaction completes - nobody
            # else will be able to lock or change them - see
            # https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-for-update
            # (This feature requires Django 1.4.)
            # If more than one request is trying to create an invoice from
            # these same entries, then the second one to get to this line will
            # throw a DatabaseError.  That can happen if someone double-clicks
            # the Create Invoice button.
            try:
                entries.select_for_update(nowait=True)
            except DatabaseError:
                # Whoops, we lost the race
                messages.add_message(request, messages.ERROR,
                                     "Lock error trying to get entries")
            else:
                # We got the lock, we can carry on
                invoice = invoice_form.save()
                Entry.no_join.filter(pk__in=entries).update(
                    status=invoice.status, entry_group=invoice)
                messages.add_message(request, messages.INFO,
                                     "Invoice created")
                return HttpResponseRedirect(reverse('view_invoice',
                                                    args=[invoice.pk]))
        else:
            messages.add_message(request, messages.ERROR,
                                 "No entries for invoice")
    else:
        entries = Entry.objects.filter(**entries_query)
        entries = entries.order_by('start_time')
        if not entries:
            raise Http404

    billable_entries = entries.filter(activity__billable=True) \
        .select_related()
    nonbillable_entries = entries.filter(activity__billable=False) \
        .select_related()
    return render(request, 'timepiece/invoice/create.html', {
        'invoice_form': invoice_form,
        'billable_entries': billable_entries,
        'nonbillable_entries': nonbillable_entries,
        'project': project,
        'billable_totals': HourGroup.objects.summaries(billable_entries),
        'nonbillable_totals': HourGroup.objects.summaries(nonbillable_entries),
        'from_date': from_date,
        'to_date': to_date,
    })

Example 64

Project: dndtools Source File: views.py
@menu_item(MenuItem.CHARACTER_OPTIONS)
@submenu_item(MenuItem.CharacterOptions.SKILLS)
def skill_detail(request, skill_slug, rulebook_slug=None,
                 rulebook_id=None):
    # fetch the class
    skill = get_object_or_404(Skill.objects.select_related(
        'skill_variant', 'skill_variant__rulebook'), slug=skill_slug)

    # fetch primary variant, this is independent of rulebook selected
    try:
        primary_variant = SkillVariant.objects.select_related(
            'rulebook', 'rulebook__dnd_edition',
        ).filter(
            skill=skill,
        ).order_by('-rulebook__dnd_edition__core', '-rulebook__published')[0]
    except Exception:
        primary_variant = None

    # if rulebook is supplied, select find this variant
    if rulebook_slug and rulebook_id:
        # use canonical link in head as this is more or less duplicated content
        use_canonical_link = True
        selected_variant = get_object_or_404(
            SkillVariant.objects.select_related(
                'rulebook', 'skill', 'rulebook__dnd_edition'),
            skill__slug=skill_slug,
            rulebook__pk=rulebook_id)

        # possible malformed/changed slug
        if rulebook_slug != selected_variant.rulebook.slug:
            return permanent_redirect_object(request, selected_variant)

        # selected variant is primary! Redirect to canonical url
        if selected_variant == primary_variant:
            return permanent_redirect_view(
                request, skill_detail, kwargs={
                    'skill_slug': skill_slug}
            )
    else:
        # this is canonical, no need to specify it
        use_canonical_link = False
        selected_variant = primary_variant

    other_variants = [
        variant
        for variant
        in skill.skillvariant_set.select_related(
            'rulebook', 'rulebook__dnd_edition', 'skill').all()
        if variant != selected_variant
    ]

    if selected_variant:
        display_3e_warning = is_3e_edition(selected_variant.rulebook.dnd_edition)
    else:
        display_3e_warning = False

    feat_list = skill.required_by_feats.select_related('rulebook').all()
    feat_paginator = DndPaginator(feat_list, request)

    return render_to_response('dnd/skills/skill_detail.html',
                              {
                                  'skill': skill,
                                  'feat_list': feat_paginator.items(),
                                  'feat_paginator': feat_paginator,
                                  'request': request,
                                  'i_like_it_url': request.build_absolute_uri(),
                                  'inaccurate_url': request.build_absolute_uri(),
                                  'selected_variant': selected_variant,
                                  'other_variants': other_variants,
                                  'use_canonical_link': use_canonical_link,
                                  'display_3e_warning': display_3e_warning,
                              }, context_instance=RequestContext(request), )

Example 65

Project: wger Source File: log.py
def add(request, pk):
    '''
    Add a new workout log
    '''

    template_data = {}
    template_data.update(csrf(request))

    # Load the day and check ownership
    day = get_object_or_404(Day, pk=pk)
    if day.get_owner_object().user != request.user:
        return HttpResponseForbidden()

    # We need several lists here because we need to assign specific form to each
    # exercise: the entries for weight and repetitions have no indicator to which
    # exercise they belong besides the form-ID, from Django's formset
    counter = 0
    total_sets = 0
    exercise_list = {}
    form_to_exercise = {}

    for exercise_set in day.set_set.all():
        for exercise in exercise_set.exercises.all():

            # Maximum possible values
            total_sets += int(exercise_set.sets)
            counter_before = counter
            counter = counter + int(exercise_set.sets) - 1
            form_id_range = range(counter_before, counter + 1)

            # Add to list
            exercise_list[exercise.id] = {'obj': exercise,
                                          'sets': int(exercise_set.sets),
                                          'form_ids': form_id_range}

            counter += 1
            # Helper mapping form-ID <--> Exercise
            for id in form_id_range:
                form_to_exercise[id] = exercise

    # Define the formset here because now we know the value to pass to 'extra'
    WorkoutLogFormSet = modelformset_factory(WorkoutLog,
                                             form=WorkoutLogForm,
                                             exclude=('date', 'workout'),
                                             extra=total_sets)
    # Process the request
    if request.method == 'POST':

        # Make a copy of the POST data and go through it. The reason for this is
        # that the form expects a value for the exercise which is not present in
        # the form (for space and usability reasons)
        post_copy = request.POST.copy()

        for form_id in form_to_exercise:
            if post_copy.get('form-%s-weight' % form_id) or post_copy.get('form-%s-reps' % form_id):
                post_copy['form-%s-exercise' % form_id] = form_to_exercise[form_id].id

        # Pass the new data to the forms
        formset = WorkoutLogFormSet(data=post_copy)
        dateform = HelperDateForm(data=post_copy)
        session_form = HelperWorkoutSessionForm(data=post_copy)

        # If all the data is valid, save and redirect to log overview page
        if dateform.is_valid() and session_form.is_valid() and formset.is_valid():
            log_date = dateform.cleaned_data['date']

            if WorkoutSession.objects.filter(user=request.user, date=log_date).exists():
                session = WorkoutSession.objects.get(user=request.user, date=log_date)
                session_form = HelperWorkoutSessionForm(data=post_copy, instance=session)

            # Save the Workout Session only if there is not already one for this date
            instance = session_form.save(commit=False)
            if not WorkoutSession.objects.filter(user=request.user, date=log_date).exists():
                instance.date = log_date
                instance.user = request.user
                instance.workout = day.training
            else:
                session = WorkoutSession.objects.get(user=request.user, date=log_date)
                instance.instance = session
            instance.save()

            # Log entries (only the ones with actual content)
            instances = [i for i in formset.save(commit=False) if i.reps]
            for instance in instances:
                if not instance.weight:
                    instance.weight = 0
                instance.user = request.user
                instance.workout = day.training
                instance.date = log_date
                instance.save()

            return HttpResponseRedirect(reverse('manager:log:log', kwargs={'pk': day.training_id}))
    else:
        # Initialise the formset with a queryset that won't return any objects
        # (we only add new logs here and that seems to be the fastest way)
        user_weight_unit = 1 if request.user.userprofile.use_metric else 2
        formset = WorkoutLogFormSet(queryset=WorkoutLog.objects.none(),
                                    initial=[{'weight_unit': user_weight_unit,
                                              'repetition_unit': 1} for x in range(0, total_sets)])

        dateform = HelperDateForm(initial={'date': datetime.date.today()})

        # Depending on whether there is already a workout session for today, update
        # the current one or create a new one (this will be the most usual case)
        if WorkoutSession.objects.filter(user=request.user, date=datetime.date.today()).exists():
            session = WorkoutSession.objects.get(user=request.user, date=datetime.date.today())
            session_form = HelperWorkoutSessionForm(instance=session)
        else:
            session_form = HelperWorkoutSessionForm()

    # Pass the correct forms to the exercise list
    for exercise in exercise_list:

        form_id_from = min(exercise_list[exercise]['form_ids'])
        form_id_to = max(exercise_list[exercise]['form_ids'])
        exercise_list[exercise]['forms'] = formset[form_id_from:form_id_to + 1]

    template_data['day'] = day
    template_data['exercises'] = exercise_list
    template_data['exercise_list'] = exercise_list
    template_data['formset'] = formset
    template_data['dateform'] = dateform
    template_data['session_form'] = session_form
    template_data['form_action'] = reverse('manager:day:log', kwargs={'pk': pk})

    return render(request, 'day/log.html', template_data)

Example 66

Project: ed-questionnaire Source File: views.py
@commit_on_success
def questionnaire(request, runcode=None, qs=None):
    """
    Process submit answers (if present) and redirect to next page

    If this is a POST request, parse the submitted data in order to store
    all the submitted answers.  Then return to the next questionset or
    return a completed response.

    If this isn't a POST request, redirect to the main page.

    We only commit on success, to maintain consistency.  We also specifically
    rollback if there were errors processing the answers for this questionset.
    """
    if use_session:
        session_runcode = request.session.get('runcode', None)
        if session_runcode is not None:
            runcode = session_runcode

        session_qs = request.session.get('qs', None)
        if session_qs is not None:
            qs = session_qs

    # if runcode provided as query string, redirect to the proper page
    if not runcode:
        runcode = request.GET.get('runcode')
        if not runcode:
            return HttpResponseRedirect("/")
        else:
            if not use_session:
                args = [runcode, ]
            else:
                request.session['runcode'] = runcode
                args = []
            return HttpResponseRedirect(reverse("questionnaire", args=args))

    runinfo = get_runinfo(runcode)

    if not runinfo:
        commit()
        return HttpResponseRedirect('/')

    # let the runinfo have a piggy back ride on the request
    # so we can easily use the runinfo in places like the question processor
    # without passing it around
    request.runinfo = runinfo

    if not qs:
        # Only change the language to the subjects choice for the initial
        # questionnaire page (may be a direct link from an email)
        if hasattr(request, 'session'):
            request.session['django_language'] = runinfo.subject.language
            translation.activate(runinfo.subject.language)

    if 'lang' in request.GET:
        return set_language(request, runinfo, request.path)

    # --------------------------------
    # --- Handle non-POST requests ---
    # --------------------------------

    if request.method != "POST":
        if qs is not None:
            qs = get_object_or_404(QuestionSet, sortid=qs, questionnaire=runinfo.questionset.questionnaire)
            if runinfo.random.startswith('test:'):
                pass  # ok for testing
            elif qs.sortid > runinfo.questionset.sortid:
                # you may jump back, but not forwards
                return redirect_to_qs(runinfo, request)
            runinfo.questionset = qs
            runinfo.save()
            commit()
        # no questionset id in URL, so redirect to the correct URL
        if qs is None:
            return redirect_to_qs(runinfo, request)
        questionset_start.send(sender=None, runinfo=runinfo, questionset=qs)
        return show_questionnaire(request, runinfo)

    # -------------------------------------
    # --- Process POST with QuestionSet ---
    # -------------------------------------

    # if the submitted page is different to what runinfo says, update runinfo
    # XXX - do we really want this?
    qs = request.POST.get('questionset_id', qs)
    try:
        qsobj = QuestionSet.objects.filter(pk=qs)[0]
        if qsobj.questionnaire == runinfo.questionset.questionnaire:
            if runinfo.questionset != qsobj:
                runinfo.questionset = qsobj
                runinfo.save()
    except:
        pass

    questionnaire = runinfo.questionset.questionnaire
    questionset = runinfo.questionset

    # to confirm that we have the correct answers
    expected = questionset.questions()

    items = request.POST.items()
    extra = {}  # question_object => { "ANSWER" : "123", ... }

    # this will ensure that each question will be processed, even if we did not receive
    # any fields for it. Also works to ensure the user doesn't add extra fields in
    for x in expected:
        items.append((u'question_%s_Trigger953' % x.number, None))

    # generate the answer_dict for each question, and place in extra
    for item in items:
        key, value = item[0], item[1]
        if key.startswith('question_'):
            answer = key.split("_", 2)
            question = get_question(answer[1], questionnaire)
            if not question:
                logging.warn("Unknown question when processing: %s" % answer[1])
                continue
            extra[question] = ans = extra.get(question, {})
            if (len(answer) == 2):
                ans['ANSWER'] = value
            elif (len(answer) == 3):
                ans[answer[2]] = value
            else:
                logging.warn("Poorly formed form element name: %r" % answer)
                continue
            extra[question] = ans

    errors = {}
    for question, ans in extra.items():
        if not question_satisfies_checks(question, runinfo):
            continue
        if u"Trigger953" not in ans:
            logging.warn("User attempted to insert extra question (or it's a bug)")
            continue
        try:
            cd = question.getcheckdict()
            # requiredif is the new way
            depon = cd.get('requiredif', None) or cd.get('dependent', None)
            if depon:
                depparser = BooleanParser(dep_check, runinfo, extra)
                if not depparser.parse(depon):
                    # if check is not the same as answer, then we don't care
                    # about this question plus we should delete it from the DB
                    delete_answer(question, runinfo.subject, runinfo.runid)
                    if cd.get('store', False):
                        runinfo.set_cookie(question.number, None)
                    continue
            add_answer(runinfo, question, ans)
            if cd.get('store', False):
                runinfo.set_cookie(question.number, ans['ANSWER'])
        except AnswerException, e:
            errors[question.number] = e
        except Exception:
            logging.exception("Unexpected Exception")
            rollback()
            raise

    if len(errors) > 0:
        res = show_questionnaire(request, runinfo, errors=errors)
        rollback()
        return res

    questionset_done.send(sender=None, runinfo=runinfo, questionset=questionset)

    next = questionset.next()
    while next and not questionset_satisfies_checks(next, runinfo):
        next = next.next()
    runinfo.questionset = next
    runinfo.save()
    if use_session:
        request.session['prev_runcode'] = runinfo.random

    if next is None:  # we are finished
        return finish_questionnaire(request, runinfo, questionnaire)

    commit()
    return redirect_to_qs(runinfo, request)

Example 67

Project: Adlibre-TMS Source File: views.py
@login_required
def timesheets(request, data_id = None, template_name='tms/timesheets.html',
               form_template_name='tms/timesheets_form.html',
               entry_template_name='tms/timesheets_single_entry.html',
               post_save_redirect='tms_timesheets'):
    """Displaying/Adding/Editing existing Timesheet entry in database.

    Used with AJAX calls now. Main gear view for Timesheets.
    
    - GET to this view retrieves Whole timesheets page (form and entries paginated table)
    - POST to this view: 
        - Adds a new entry 
            (When request.POST['data_id'] is not given (equal to u('') or u(' ') ))
        - Edits an entry 
            (Upon request.POST['data_id'] is equal to some Timesheet PK)
            (Creates a form instance with model of provided PK and validates it)
    - returns single Timesheet entry when form is valid
    - returns single Timesheet entry when form is valid and item was edited
        (Response contains <div class="edited_item_returned"></div> in this case... 
        To check for editing/adding entry in AJAX side)
    - Returns form with errors in case some errors occurred in form validation
    
    """
    # storing sessin user position
    request.session['enter_url'] = reverse('tms_timesheets')
    #checking for the edit data_id exists in the call and selecting behavior
    if request.method == 'POST' and data_id != ('' or ' '):
        try:
            data_id = request.POST['data_id']
            timesheet = get_object_or_404(Timesheet, pk=data_id)
            form = TimesheetForm(request.POST or None, instance=timesheet)
            edit_ajax = True
        except:
            data_id = ' '
            edit_ajax = False
            form = TimesheetForm(request.POST or None)
    else:
        form = TimesheetForm(request.POST or None)
    # form validation
    if request.method == 'POST' and form.is_valid():
        if request.POST.get('save', None):
            # saving data with form
            obj = form.save(commit=False)
            employee, created = Employee.objects.get_or_create(user=request.user)
            obj.employee = employee
            obj.save()
            # Add message to admin
            messages.add_message(request, messages.INFO, 'Timesheet entry was added successfully')
            context = {
                       'object': obj,
                       'edit_ajax': edit_ajax,
                       'add_init': True
                       }
            return render_to_response(entry_template_name, context, context_instance=RequestContext(request))
    elif request.method == 'POST' and not form.is_valid():
        #returning form with errors
        context = {
                   'form': form,
                   'edit_pk': data_id,
                   }
        return render_to_response(form_template_name, context, context_instance=RequestContext(request))

    timesheets_list = Timesheet.objects.filter(employee__user=request.user,
                                        is_submitted=False,
                                        is_billed=False).order_by('-start_time')
    # adding context vars for proper form init (described in project Wiki/TimesheetEntry)
    latest_date = ''
    latest_job = ''
    timesheets_today = timesheets_list.filter(start_time__startswith=str(datetime.date.today())).order_by('-end_time')
    if timesheets_today:
        latest_date = timesheets_today[0].end_time
        latest_job = timesheets_today[0].job.pk
    #returning empty form
    context = {
        'form': form,
        'object_list': timesheets_list,
        'init_latest_date':  latest_date,
        'init_latest_job' : latest_job,
        }
    return render_to_response(template_name, context, context_instance=RequestContext(request))

Example 68

Project: eve-wspace Source File: views.py
@login_required
def add_pos(request, msID):
    """
    GET gets the add POS dialog, POST processes it.
    """

    if not request.is_ajax():
        raise PermissionDenied
    mapsystem = get_object_or_404(MapSystem, pk=msID)
    system = get_object_or_404(System, pk=mapsystem.system.pk)
    if request.method == 'POST':
        corp_name = request.POST.get('corp', None)
        if not corp_name:
            return HttpResponse('Corp cannot be blank!', status=400)

        try:
            corp = Corporation.objects.get(name=corp_name)
        except Corporation.DoesNotExist:
            # Corp isn't in our DB, get its ID and add it
            try:
                api = eveapi.EVEAPIConnection(cacheHandler=handler)
                corp_id = (api.eve.CharacterID(names=corp_name)
                           .characters[0].characterID)
                if corp_id == 0:
                    return HttpResponse('Corp does not exist!', status=404)
                corp = core_tasks.update_corporation(corp_id, True)
            except:
                # Error while talking to the EVE API
                return HttpResponse('Could not verify Corp name. Please try again later.', status=404)                
        else:
            # Have the async worker update the corp so that it is up to date
            core_tasks.update_corporation.delay(corp.id)

        if request.POST['auto'] == '1':
            fittings = []
            moon_distance = 150000000
            for i in request.POST['fitting'].splitlines():
                cols = i.split('\t')
                # ignore offgrid stuff
                if cols[2] != '-':
                    fittings.append(cols)
                    if cols[1] == 'Moon' and cols[2].endswith('km'):
                        # found a moon close by
                        distance = int(cols[2][:-3].replace(',', '')
                                       .replace('.', '').replace(u'\xa0', ''))
                        if distance < moon_distance:
                            # closest moon so far
                            moon_distance = distance
                            moon_name = cols[0]
            if moon_distance == 150000000:
                # No moon found
                return HttpResponse('No moon found in d-scan!', status=404)

            # parse POS location
            regex = '^%s ([IVX]+) - Moon ([0-9]+)$' % (system.name,)
            re_result = re.match(regex, moon_name)
            if not re_result:
                return HttpResponse(
                    'Invalid D-Scan! Do you have the right system?',
                    status=400)
            else:
                result = re_result.groups()
            NUMERALS = {'X': 10, 'V': 5, 'I': 1}
            planet = 0
            for i in range(len(result[0])):
                value = NUMERALS[result[0][i]]
                try:
                    next_value = NUMERALS[result[0][i+1]]
                except IndexError:
                    next_value = 0
                if value < next_value:
                    planet -= value
                else:
                    planet += value
            moon = int(result[1])

            pos = POS(system=system, planet=planet,
                      moon=moon, status=int(request.POST['status']),
                      corporation=corp)
            try:
                pos.fit_from_iterable(fittings)
            except AttributeError as e:
                return HttpResponse(e, status=404)

        else:
            tower = get_object_or_404(Type, name=request.POST['tower'], marketgroup__isnull=False)
            pos = POS(system=system, planet=int(request.POST['planet']),
                      moon=int(request.POST['moon']),
                      towertype=tower,
                      posname=request.POST['name'],
                      fitting=request.POST['fitting'],
                      status=int(request.POST['status']),
                      corporation=corp)
            if request.POST.get('dscan', None) == "1":
                pos.fit_from_dscan(request.POST['fitting'].encode('utf-8'))

        if pos.status == 3:
            if request.POST['rfdays'] == '':
                rf_days = 0
            else:
                rf_days = int(request.POST['rfdays'])
            if request.POST['rfhours'] == '':
                rf_hours = 0
            else:
                rf_hours = int(request.POST['rfhours'])
            if request.POST['rfminutes'] == '':
                rf_minutes = 0
            else:
                rf_minutes = int(request.POST['rfminutes'])
            delta = timedelta(days=rf_days,
                              hours=rf_hours,
                              minutes=rf_minutes)
            pos.rftime = datetime.now(pytz.utc) + delta
        pos.log(request.user, "Added", mapsystem)
        pos.save()

        return HttpResponse()
    else:
        return TemplateResponse(request, 'add_pos.html', {'system': system, 'mapsystem': mapsystem})

Example 69

Project: treeio Source File: views.py
@handle_response_format
@treeio_login_required
def messaging_view(request, message_id, response_format='html'):
    "Single message page"

    message = get_object_or_404(Message, pk=message_id)
    user = request.user.profile

    if not user.has_permission(message):
        return user_denied(request, message="You don't have access to this Message",
                           response_format=response_format)

    message.read_by.add(user)

    if request.POST and request.POST.get('body', False):
        "Unread message"

        reply = Message()
        reply.author = user.get_contact()
        if not reply.author:
            return user_denied(request,
                               message="You can't send message without a Contact Card assigned to you.",
                               response_format=response_format)
        reply.reply_to = message
        form = MessageReplyForm(
            user, message.stream_id, message, request.POST, instance=reply)
        if form.is_valid():
            reply = form.save()
            reply.set_user_from_request(request)
            # Add author to recipients
            reply.recipients.add(reply.author)
            message.read_by.clear()

            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module(
                            'treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(
                            pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST[
                        'multicomplete_recipients'].split(',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr):
                            contact, created = Contact.get_or_create_by_email(
                                emailstr, contact_type=default_contact_type)
                            reply.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass

            # Add each recipient of the reply to the original message
            for recipient in reply.recipients.all():
                message.recipients.add(recipient)

            # send email to all recipients
            reply.send_email()

            return HttpResponseRedirect(reverse('messaging_message_view', args=[message.id]))

    else:
        form = MessageReplyForm(
            request.user.profile, message.stream_id, message)

    replies = Object.filter_by_request(request,
                                       Message.objects.filter(reply_to=message).order_by('date_created'))

    context = _get_default_context(request)
    context.update({'message': message,
                    'messages': replies,
                    'form': form})

    return render_to_response('messaging/message_view', context,
                              context_instance=RequestContext(request),
                              response_format=response_format)

Example 70

Project: feedhq Source File: views.py
@login_required
def entries_list(request, page=1, mode=None, category=None, feed=None,
                 starred=False):
    """
    Displays a paginated list of entries.

    ``page``: the page number
    ``mode``: filters the list to display all / unread / starred items
    ``category``: (slug) if set, will filter the entries of this category
    ``feed``: (object_id) if set, will filter the entries of this feed

    Note: only set category OR feed. Not both at the same time.
    """
    page = int(page)
    user = request.user
    es_entries = es.manager.user(request.user).defer(
        'content', 'guid', 'tags', 'read_later_url',
        'author', 'broadcast', 'link', 'starred',
    ).query_aggregate('all_unread', read=False)
    if mode == 'unread':
        es_entries = es_entries.filter(read=False)
    elif mode == 'stars':
        es_entries = es_entries.filter(
            starred=True).query_aggregate('all_starred', starred=True)

    search = request.GET.get('q', '')
    if search:
        es_entries = es_entries.filter(query=search)

    if category is not None:
        category = get_object_or_404(user.categories, slug=category)
        all_url = reverse('feeds:category', args=[category.slug])
        unread_url = reverse('feeds:category', args=[category.slug, "unread"])
        stars_url = reverse('feeds:category', args=[category.slug, "stars"])
        es_entries = es_entries.filter(category=category.pk).query_aggregate(
            'all', category=category.pk).query_aggregate(
                'unread', category=category.pk, read=False)

    if feed is not None:
        feed = get_object_or_404(user.feeds.select_related('category'),
                                 pk=feed)
        all_url = reverse('feeds:feed', args=[feed.pk])
        unread_url = reverse('feeds:feed', args=[feed.pk, "unread"])
        stars_url = reverse('feeds:feed', args=[feed.pk, "stars"])

        category = feed.category
        es_entries = es_entries.filter(feed=feed.pk).query_aggregate(
            'all', feed=feed.pk).query_aggregate(
                'unread', feed=feed.pk, read=False)

    if starred is True:
        es_entries = es_entries.filter(starred=True).query_aggregate(
            'all', starred=True).query_aggregate(
                'unread', starred=True, read=False)
        all_url = reverse('feeds:entries', args=['stars'])
        unread_url = None
        stars_url = None

    if feed is None and category is None and starred is not True:
        all_url = reverse('feeds:entries')
        unread_url = reverse('feeds:entries', args=['unread'])
        stars_url = reverse('feeds:entries', args=['stars'])
        es_entries = es_entries.query_aggregate('all').query_aggregate(
            'unread', read=False)

    if user.oldest_first:
        es_entries = es_entries.order_by('timestamp', 'id')

    if request.method == 'POST':
        if request.POST['action'] in (ReadForm.READ_ALL, ReadForm.READ_PAGE):
            pages_only = request.POST['action'] == ReadForm.READ_PAGE
            form = ReadForm(es_entries, feed, category, user,
                            pages_only=pages_only, data=request.POST)
            if form.is_valid():
                pks = form.save()
                undo_form = loader.render_to_string('feeds/undo_read.html', {
                    'form': UndoReadForm(initial={
                        'pks': json.dumps(pks, separators=(',', ':'))}),
                    'action': request.get_full_path(),
                }, context_instance=RequestContext(request))
                message = ungettext(
                    '1 entry has been marked as read.',
                    '%(value)s entries have been marked as read.',
                    len(pks)) % {'value': len(pks)}
                messages.success(request,
                                 format_html(u"{0} {1}", message, undo_form))

        elif request.POST['action'] == 'undo-read':
            form = UndoReadForm(user, data=request.POST)
            if form.is_valid():
                count = form.save()
                messages.success(
                    request, ungettext(
                        '1 entry has been marked as unread.',
                        '%(value)s entries have been marked as unread.',
                        count) % {'value': count})

        if mode == 'unread':
            return redirect(unread_url)
        elif mode == 'stars':
            return redirect(stars_url)
        else:
            return redirect(all_url)

    try:
        entries = es_entries.fetch(page=page,
                                   per_page=user.entries_per_page,
                                   annotate=user)
    except RequestError as e:
        if 'No mapping found' not in e.error:  # index is empty
            raise
        entries = []
        user._unread_count = unread_count = total_count = 0
    else:
        aggs = entries['aggregations']
        entries = entries['hits']
        unread_count = aggs['entries']['unread']['doc_count']
        total_count = aggs['entries']['all']['doc_count']
        user._unread_count = aggs['entries']['all_unread']['doc_count']
    if mode == 'unread':
        card = unread_count
    elif mode == 'stars':
        card = aggs['entries']['all_starred']['doc_count']
    else:
        card = total_count
    num_pages = card // user.entries_per_page
    if card % user.entries_per_page:
        num_pages += 1
    entries = {
        'object_list': entries,
        'paginator': {
            'num_pages': num_pages,
        },
        'has_previous': page > 1,
        'has_next': page < num_pages,
        'previous_page_number': page - 1,
        'next_page_number': page + 1,
        'number': page,
    }
    request.session['back_url'] = request.get_full_path()

    # base_url is a variable that helps the paginator a lot. The drawback is
    # that the paginator can't use reversed URLs.
    if mode == 'unread':
        base_url = unread_url
    elif mode == 'stars':
        base_url = stars_url
    else:
        base_url = all_url

    context = {
        'category': category,
        'feed': feed,
        'entries': entries,
        'mode': mode,
        'unread_count': unread_count,
        'total_count': total_count,
        'all_url': all_url,
        'unread_url': unread_url,
        'stars_url': stars_url,
        'base_url': base_url,
        'stars': starred,
        'all_unread': aggs['entries']['unread']['doc_count'],
        'entries_template': 'feeds/entries_include.html',
        'search': search,
        'search_form': True,
    }
    if unread_count:
        context['read_all_form'] = ReadForm()
        context['read_page_form'] = ReadForm(pages_only=True, initial={
            'action': ReadForm.READ_PAGE,
            'pages': json.dumps([int(page)]),
        })
        context['action'] = request.get_full_path()
    if (
        len(entries['object_list']) == 0 and
        request.user.feeds.count() == 0
    ):
        context['noob'] = True

    if request.is_ajax():
        template_name = context['entries_template']
    else:
        template_name = 'feeds/entries_list.html'

    return render(request, template_name, context)

Example 71

Project: crowdata Source File: views.py
@render_to('organization_profile.html')
def organization_profile(request, organization_slug):
    """ Show Organization Profile """
    organization = get_object_or_404(models.Organization, slug=organization_slug)

    docuement_set_filter = request.GET.get('docuement_set_filter')
    if docuement_set_filter:
        try:
            docuement_set_filter = int(docuement_set_filter)
            docuement_form_entries_list = organization.docuementsetformentry_set.filter(docuement__docuement_set__id = docuement_set_filter)
        except ValueError:
            docuement_form_entries_list = organization.docuementsetformentry_set.all()
    else:
        docuement_form_entries_list = organization.docuementsetformentry_set.all()
        
    docuement_form_entries_list = docuement_form_entries_list.filter(docuement__docuement_set__published = True)

    docuement_form_entries_paginator = Paginator(docuement_form_entries_list, 10)
    reset_filter = request.GET.get('reset_filter')
    if reset_filter:
        organization_page = 1
    else:
        organization_page = request.GET.get('organization_page')
    show_docuements = request.GET.get('show_docuements')

    try:
        docuement_form_entries = docuement_form_entries_paginator.page(organization_page)
    except PageNotAnInteger:
        docuement_form_entries = docuement_form_entries_paginator.page(1)
    except EmptyPage:
        docuement_form_entries = docuement_form_entries_paginator.page(docuement_form_entries_paginator.num_pages)

    users_list = organization.users.all()
    users_paginator = Paginator(users_list, 10)        
    user_page = request.GET.get('user_page')
    show_users = request.GET.get('show_users')    
        
    try:
        users = users_paginator.page(user_page)
    except PageNotAnInteger:
        users = users_paginator.page(1)        
    except EmptyPage:
        users = users_paginator.page(users_paginator.num_pages)                

    already_member = None
    docuements_without_organization = None
    if request.user and request.user.is_authenticated():
        already_member = organization.users.filter(id = request.user.id).exists()
        docuements_without_organization = models.DocuementSetFormEntry.get_user_docuements_without_organization(request.user).count()
    
    docuement_sets = organization.docuementsetformentry_set.filter(docuement__docuement_set__published = True).values('docuement__docuement_set__name', 'docuement__docuement_set__id').distinct()
    
    return {
        'organization' : organization,
        'docuement_form_entries': docuement_form_entries,
        'already_member': already_member,
        'users': users,
        'show_users': show_users,
        'show_docuements': show_docuements,
        'docuements_without_organization': docuements_without_organization,
        'docuement_sets': docuement_sets,
        'docuement_set_filter': docuement_set_filter
    }

Example 72

Project: storyboard Source File: views.py
def thumbnail(request,key=None):
    if request.META.has_key('HTTP_IF_MODIFIED_SINCE'):
        return HttpResponseNotModified()
    s = get_object_or_404(Storage,pk=key)
    image_data = None

    if STORAGE_SERVICE == 'sina':
        import sae.storage
        sc = sae.storage.Client()
        ob = sc.get(STORAGE_BUCKET, s.path)
        if ob and ob.data:
            image_data = ob.data

    if STORAGE_SERVICE == 'baidu':
        import pybcs
        bcs = pybcs.BCS('http://bcs.duapp.com/', STORAGE_ACCESS_KEY, STORAGE_SECRET_ACCESS_KEY)
        bucket = bcs.bucket(STORAGE_BUCKET)
        obj_name = u'/%s'%(s.path)
        obj = bucket.object(obj_name.encode('utf8'))
        image_data = obj.get()['body']

    if STORAGE_SERVICE == 'gs':
        read_path =  '/%s/%s/%s'% (s.storage, s.bucket, s.path)
        #image_data = read_gs(read_path)
        src_uri = boto.storage_uri(s.bucket + '/' + s.path, 'gs')
        src_key = src_uri.get_key()
        tmp = tempfile.TemporaryFile()
        src_key.get_file(tmp)
        tmp.seek(0)
        image_data = tmp
        image_data = tmp.read()
    
    if image_data:
        # MIN_SIZE = 100
        # image = images.Image(image_data)
        # width = image.width
        # height = image.height
        # if width>height:
        #     rate = width*1.0/height
        # else:
        #     rate = height*1.0/width
        # size = int(MIN_SIZE*rate+1)
        # new_image = images.resize(image_data, width=size, height=size, output_encoding=images.PNG)      
        # image = images.Image(new_image)
        # right_x = round(MIN_SIZE*1.0/image.width,5)
        # if right_x>1:
        #     right_x = 1.0
        # else:
        #     left_x = (1- right_x)/2
        #     right_x = right_x + left_x
        # bottom_y = round(MIN_SIZE*1.0/image.height,5)
        # if bottom_y >1:
        #     bottom_y = 1.0
        # else:
        #     top_y = (1-bottom_y)/2
        #     bottom_y = bottom_y + top_y
        # new_image = images.crop(new_image, left_x, top_y, right_x, bottom_y, output_encoding=images.PNG)
        #return cache_response(image_data, s.mime)
        from PIL import Image,ImageOps
        import StringIO
        img = Image.open(StringIO.StringIO(image_data))
        #region = img.resize((100, 100),Image.ANTIALIAS)
        region = ImageOps.fit(img,(100, 100),Image.ANTIALIAS)
        response = HttpResponse(mimetype="image/png")
        format_str = '%a, %d %b %Y %H:%M:%S GMT'
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(365)
        expires_str = expires_date.strftime(format_str)
        last_modified_date = datetime.datetime.utcnow()
        last_modified_str = expires_date.strftime(format_str)
        response['Expires'] = expires_str #eg:'Sun, 08 Apr 2013 11:11:02 GMT'
        response["Last-Modified"] = last_modified_str #for 'If-Modified-Since'
        response['Cache-Control'] = 'max-age=172800'
        
        region.save(response, 'PNG', quality = 100)
        return response
    else:
        return HttpResponseNotFound()

Example 73

Project: timebank Source File: views2.py
    @login_required
    @csrf_protect
    def GET(self):
        form = ListServicesForm(self.request.GET)

        if not self.request.user.is_authenticated():
            del form.fields['mine']

        try:
            page = int(self.request.GET.get('page', '1'))
        except ValueError:
            page = 1

        services = Service.objects.filter(creator__is_active=True)

        if self.request.user.is_authenticated() and form.data.get("mine", ''):
            services = services.filter(creator=self.request.user)
            subtab = "my"
        else:
            services = services.filter(is_active=True)
            subtab = "find"

        if form.data.get("the_type", '') == "1":
            services = services.filter(is_offer=True)
        elif form.data.get("the_type", '') == "2":
            services = services.filter(is_offer=False)

        if form.data.get("category", ''):
            category = get_object_or_404(Category, id=int(form.data["category"]))
            services = services.filter(category=category)

        if form.data.get("area", ''):
            area = get_object_or_404(Area,
                id=int(form.data["area"]))
            services = services.filter(area=area)

        user_status = form.data.get("user_status", '0')
        if user_status != '0':
            if user_status == '1': # one day
                last_date = datetime.now() - timedelta(days=1)
            elif user_status == '2': # 1 week
                last_date = datetime.now() - timedelta(days=7)
            elif user_status == '3': # 1 month
                last_date = datetime.now() - timedelta(days=30)
            elif user_status == '4': # 3 months
                last_date = datetime.now() - timedelta(days=3*30)
            elif user_status == '5': # 6 months
                last_date = datetime.now() - timedelta(days=6*30)
            elif user_status == '6': # 1 year
                last_date = datetime.now() - timedelta(days=365)
            services = services.filter(creator__last_login__gt=last_date)

        if form.data.get("username", ''):
            username = form.data["username"]
            services = services.filter(creator__username__contains=username)

        if form.data.get("text", ''):
            text = form.data['text']
            services = services.filter(description__contains=text)

        paginator = Paginator(services, 10)
        try:
            services = paginator.page(page)
        except (EmptyPage, InvalidPage):
            services = paginator.page(paginator.num_pages)

        context = dict(
            services=services,
            current_tab="services",
            subtab=subtab,
            form=form
        )
        return self.context_response('serv/services.html', context)

Example 74

Project: wikinotes Source File: pages.py
@login_required
def create(request, department, number, page_type, semester=None):
    course = get_object_or_404(Course, department=department.upper(), number=int(number))

    if page_type not in page_types:
        raise Http404

    form_action = reverse('pages_create', args=[department, number, page_type])
    page_type_obj = page_types[page_type]
    data = {
        'form_action': form_action,
        'professors': Professor.objects.all(),
        'title': 'Create a page (%s)' % course,
        'course': course,
        'page_type': page_type_obj,
        'terms': terms,
        'field_templates': page_type_obj.get_uneditable_fields() + page_type_obj.get_editable_fields(),
        'years': years,
        'page_type_url': page_type_obj.get_url(course), # can't call it on page_type_obj directly
        'current_term': current_term,
        'current_year': current_year,
        'exam_types': exam_types,
        'current_exam_type': exam_types[0], # default
        'edit_mode': False,
        'course_series': course.series_set.all(),
    }

    if semester is not None:
        data['current_term'] = semester[0]
        data['current_year'] = int(semester[1])
        data['does_not_exist'] = True

    if request.method == 'POST':
        errors = page_type_obj.find_errors(request.POST)
        kwargs = page_type_obj.get_kwargs(request.POST)
        course_sem, created = CourseSemester.objects.get_or_create(term=request.POST['term'], year=request.POST['year'], course=course)

        existing_page = Page.objects.filter(course_sem=course_sem,
            slug=kwargs['slug'])
        if errors or existing_page: # it returns None only if nothing is wrong
            data['errors'] = errors
            if existing_page:
                data['errors'].append('A <a href="%s">page</a> with the same '
                    'slug already exists! Perhaps you meant to edit that one '
                    'instead? Alternatively, you could change the details '
                    'for this page.' % existing_page[0].get_absolute_url())

            # Keep the posted data
            data['current_term'] = request.POST['term']
            try:
                data['current_year'] = int(request.POST['year'])
            except ValueError:
                pass # defaults to the current year
            data['current_exam_type'] = request.POST['exam_type'] if 'exam_type' in request.POST else ''
            data['subject'] = request.POST['subject'] if 'subject' in request.POST else ''

            data['content'] = request.POST['content']
            data['message'] = request.POST['message']
            try:
                data['current_professor'] = int(request.POST['professor_id'])
            except (ValueError, KeyError):
                pass

            return render(request, 'pages/create.html', data)
        else:
            commit_message = request.POST['message'] if request.POST['message'] else 'Minor edit'
            # The title and subject are generated by the PageType object, in kwargs
            new_page = Page.objects.create(course_sem=course_sem, page_type=page_type, maintainer=request.user, **kwargs)
            username = request.user.username
            email = request.user.email
            hexsha = new_page.save_content(request.POST['content'], commit_message, username)

            # Add the history item - should be done automatically one day
            course.add_event(page=new_page, user=request.user, action='created',
                message=commit_message, hexsha=hexsha)
            data['page'] = new_page

            # If the user isn't watching the course already, start watching
            user = request.user.get_profile()
            if not user.is_watching(course):
                user.start_watching(course)

            # Create the SeriesPage if a series is specified, at the end of the
            # series. Temporary and very hacky solution, pls fix later
            series_id = request.POST.get('series_id')
            if series_id:
                series_query = Series.objects.filter(pk=series_id,
                                                     course=course)
                if series_query.exists():
                    series = series_query[0]
                    next_position = series.get_next_position()
                    series.seriespage_set.create(page=new_page, series=series,
                                                 position=next_position)

            return redirect(new_page.get_absolute_url())

    return render(request, 'pages/create.html', data)

Example 75

Project: django-userena Source File: views.py
Function: email_change
@secure_required
@permission_required_or_403('change_user', (get_user_model(), 'username', 'username'))
def email_change(request, username, email_form=ChangeEmailForm,
                 template_name='userena/email_form.html', success_url=None,
                 extra_context=None):
    """
    Change email address

    :param username:
        String of the username which specifies the current account.

    :param email_form:
        Form that will be used to change the email address. Defaults to
        :class:`ChangeEmailForm` supplied by userena.

    :param template_name:
        String containing the template to be used to display the email form.
        Defaults to ``userena/email_form.html``.

    :param success_url:
        Named URL where the user will get redirected to when successfully
        changing their email address.  When not supplied will redirect to
        ``userena_email_complete`` URL.

    :param extra_context:
        Dictionary containing extra variables that can be used to render the
        template. The ``form`` key is always the form supplied by the keyword
        argument ``form`` and the ``user`` key by the user whose email address
        is being changed.

    **Context**

    ``form``
        Form that is used to change the email address supplied by ``form``.

    ``account``
        Instance of the ``Account`` whose email address is about to be changed.

    **Todo**

    Need to have per-object permissions, which enables users with the correct
    permissions to alter the email address of others.

    """
    user = get_object_or_404(get_user_model(), username__iexact=username)
    prev_email = user.email
    form = email_form(user)

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

        if form.is_valid():
            form.save()

            if success_url:
                # Send a signal that the email has changed
                userena_signals.email_change.send(sender=None,
                                                  user=user,
                                                  prev_email=prev_email,
                                                  new_email=user.email)
                redirect_to = success_url
            else: redirect_to = reverse('userena_email_change_complete',
                                        kwargs={'username': user.username})
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    extra_context['profile'] = get_user_profile(user=user)
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)

Example 76

Project: dissemin Source File: views.py
Function: submit_deposit
@json_view
@require_POST
@user_passes_test(is_authenticated)
def submitDeposit(request, pk):
    paper = get_object_or_404(Paper, pk=pk)
    context = {'status': 'error'}
    form = PaperDepositForm(data=request.POST)
    if not form.is_valid():
        context['form'] = form.errors
        return context, 400

    # This validation could take place in the form (but we need access to the
    # paper and user?)
    repository = form.cleaned_data['radioRepository']
    protocol = repository.protocol_for_deposit(paper, request.user)
    if protocol is None:
        context['radioRepository'] = _(
            "This repository cannot be used for this paper.")
        return context, 400

    repositoryForm = protocol.get_bound_form(request.POST)

    if not repositoryForm.is_valid():
        request_context = RequestContext(request)
        form_html = render_crispy_form(repositoryForm, context=request_context)
        context['form_html'] = form_html
        return context, 400

    # Check that the paper has been uploaded by the same user
    pdf = form.cleaned_data['file_id']
    if pdf.user != request.user:
        context['message'] = _('Access to the PDF was denied.')
        return context, 400

    # Submit the paper to the repository
    path = os.path.join(MEDIA_ROOT, pdf.file.name)

    # Create initial record
    d = DepositRecord(
            paper=paper,
            user=pdf.user,
            repository=repository,
            upload_type=form.cleaned_data['radioUploadType'],
            file=pdf)
    d.save()

    submitResult = protocol.submit_deposit_wrapper(path, repositoryForm)

    d.request = submitResult.logs
    if not submitResult.success():
        context['message'] = submitResult.message
        d.save()
        return context, 400

    d.identifier = submitResult.identifier
    d.pdf_url = submitResult.pdf_url
    d.save()
    paper.update_availability()
    paper.save()

    context['status'] = 'success'
    # TODO change this (we don't need it)
    context['upload_id'] = d.id
    return context

Example 77

Project: django-lfs Source File: views.py
def refresh_cart(request):
    """
    Refreshes the cart after some changes has been taken place, e.g.: the
    amount of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country_iso = request.POST.get("country")
    if country_iso:
        selected_country = Country.objects.get(code=country_iso.lower())
        customer.selected_country_id = selected_country.id
        if customer.selected_shipping_address:
            customer.selected_shipping_address.country = selected_country
            customer.selected_shipping_address.save()
            customer.selected_shipping_address.save()
        if customer.selected_invoice_address:
            customer.selected_invoice_address.country = selected_country
            customer.selected_invoice_address.save()
            customer.selected_invoice_address.save()
        # NOTE: The customer has to be saved already here in order to calculate
        # a possible new valid shippig method below, which coulb be triggered by
        # the changing of the shipping country.
        customer.save()

    # Update Amounts
    message = ""
    for item in cart.get_items():
        amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0")
        amount = item.product.get_clean_quantity_value(amount, allow_zero=True)

        if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time:
            amount = item.product.stock_amount
            if amount < 0:
                amount = 0

            if amount == 0:
                message = _(u"Sorry, but '%(product)s' is not available anymore." % {"product": item.product.name})
            elif amount == 1:
                message = _(u"Sorry, but '%(product)s' is only one time available." % {"product": item.product.name})
            else:
                message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % {"product": item.product.name, "amount": amount}

        if item.product.get_active_packing_unit():
            item.amount = item.product.get_amount_by_packages(float(amount))
        else:
            item.amount = amount

        if amount == 0:
            item.delete()
        else:
            item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    shipping_method = get_object_or_404(ShippingMethod, pk=request.POST.get("shipping_method"))
    customer.selected_shipping_method = shipping_method

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request)

    # Update payment method
    payment_method = get_object_or_404(PaymentMethod, pk=request.POST.get("payment_method"))
    customer.selected_payment_method = payment_method

    # Last but not least we save the customer ...
    customer.save()

    result = json.dumps({
        "html": cart_inline(request),
        "message": message,
    }, cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')

Example 78

Project: django-simple-import Source File: views.py
@staff_member_required
def do_import(request, import_log_id):
    """ Import the data! """
    import_log = get_object_or_404(ImportLog, id=import_log_id)
    if import_log.import_type == "N" and 'undo' in request.GET and request.GET['undo'] == "True":
        import_log.undo()
        return HttpResponseRedirect(reverse(
                    do_import,
                    kwargs={'import_log_id': import_log.id}) + '?success_undo=True')

    if 'success_undo' in request.GET and request.GET['success_undo'] == "True":
        success_undo = True
    else:
        success_undo = False

    model_class = import_log.import_setting.content_type.model_class()
    import_data = import_log.get_import_file_as_list()
    header_row = import_data.pop(0)
    header_row_field_names = []
    header_row_default = []
    header_row_null_on_empty = []
    error_data = [header_row + ['Error Type', 'Error Details']]
    create_count = 0
    update_count = 0
    fail_count = 0
    if 'commit' in request.GET and request.GET['commit'] == "True":
        commit = True
    else:
        commit = False

    key_column_name = None
    if import_log.update_key and import_log.import_type in ["U", "O"]:
        key_match = import_log.import_setting.columnmatch_set.get(column_name=import_log.update_key)
        key_column_name = key_match.column_name
        key_field_name = key_match.field_name
    for i, cell in enumerate(header_row):
        match = import_log.import_setting.columnmatch_set.get(column_name=cell)
        header_row_field_names += [match.field_name]
        header_row_default += [match.default_value]
        header_row_null_on_empty += [match.null_on_empty]
        if key_column_name != None and key_column_name.lower() == cell.lower():
            key_index = i

    with transaction.atomic():
        sid = transaction.savepoint()
        for row in import_data:
            try:
                with transaction.atomic():
                    is_created = True
                    if import_log.import_type == "N":
                        new_object = model_class()
                    elif import_log.import_type == "O":
                        filters = {key_field_name: row[key_index]}
                        new_object = model_class.objects.get(**filters)
                        is_created = False
                    elif import_log.import_type == "U":
                        filters = {key_field_name: row[key_index]}
                        new_object = model_class.objects.filter(**filters).first()
                        if new_object == None:
                            new_object = model_class()
                            is_created = False

                    new_object.simple_import_m2ms = {} # Need to deal with these after saving
                    for i, cell in enumerate(row):
                        if header_row_field_names[i]: # skip blank
                            if not import_log.is_empty(cell) or header_row_null_on_empty[i]:
                                set_field_from_cell(import_log, new_object, header_row_field_names[i], cell)
                            elif header_row_default[i]:
                                set_field_from_cell(import_log, new_object, header_row_field_names[i], header_row_default[i])
                    new_object.save()

                    for i, cell in enumerate(row):
                        if header_row_field_names[i]: # skip blank
                            if not import_log.is_empty(cell) or header_row_null_on_empty[i]:
                                set_method_from_cell(import_log, new_object, header_row_field_names[i], cell)
                            elif header_row_default[i]:
                                set_method_from_cell(import_log, new_object, header_row_field_names[i], header_row_default[i])
                    new_object.save()

                    for key in new_object.simple_import_m2ms.keys():
                        value = new_object.simple_import_m2ms[key]
                        m2m = getattr(new_object, key)
                        m2m_model = type(m2m.model())
                        related_field_name = RelationalMatch.objects.get(import_log=import_log, field_name=key).related_field_name
                        m2m_object = m2m_model.objects.get(**{related_field_name:value})
                        m2m.add(m2m_object)

                    if is_created:
                        LogEntry.objects.log_action(
                            user_id         = request.user.pk,
                            content_type_id = ContentType.objects.get_for_model(new_object).pk,
                            object_id       = new_object.pk,
                            object_repr     = smart_text(new_object),
                            action_flag     = ADDITION
                        )
                        create_count += 1
                    else:
                        LogEntry.objects.log_action(
                            user_id         = request.user.pk,
                            content_type_id = ContentType.objects.get_for_model(new_object).pk,
                            object_id       = new_object.pk,
                            object_repr     = smart_text(new_object),
                            action_flag     = CHANGE
                        )
                        update_count += 1
                    ImportedObject.objects.create(
                        import_log = import_log,
                        object_id = new_object.pk,
                        content_type = import_log.import_setting.content_type)
            except IntegrityError:
                exc = sys.exc_info()
                error_data += [row + ["Integrity Error", smart_text(exc[1])]]
                fail_count += 1
            except ObjectDoesNotExist:
                exc = sys.exc_info()
                error_data += [row + ["No Record Found to Update", smart_text(exc[1])]]
                fail_count += 1
            except ValueError:
                exc = sys.exc_info()
                if str(exc[1]).startswith('invalid literal for int() with base 10'):
                    error_data += [row + ["Incompatible Data - A number was expected, but a character was used", smart_text(exc[1])]]
                else:
                    error_data += [row + ["Value Error", smart_text(exc[1])]]
                fail_count += 1
            except:
                error_data += [row + ["Unknown Error"]]
                fail_count += 1
        if not commit:
            transaction.savepoint_rollback(sid)


    if fail_count:
        from io import StringIO
        from django.core.files.base import ContentFile
        from openpyxl.workbook import Workbook
        from openpyxl.writer.excel import save_virtual_workbook

        wb = Workbook()
        ws = wb.worksheets[0]
        ws.title = "Errors"
        filename = 'Errors.xlsx'
        for row in error_data:
            ws.append(row)
        buf = StringIO()
        # Not Python 3 compatible
        #buf.write(str(save_virtual_workbook(wb)))
        import_log.error_file.save(filename, ContentFile(save_virtual_workbook(wb)))
        import_log.save()

    return render(
        request,
        'simple_import/do_import.html',
        {
            'error_data': error_data,
            'create_count': create_count,
            'update_count': update_count,
            'fail_count': fail_count,
            'import_log': import_log,
            'commit': commit,
            'success_undo': success_undo,},
    )

Example 79

Project: django-pki Source File: forms.py
    def clean(self):
        """Verify fields"""
        
        cleaned_data = self.cleaned_data
        
        name = cleaned_data.get('name')
        action = cleaned_data.get('action')
        parent = cleaned_data.get('parent')
        pf = cleaned_data.get('passphrase')
        pf_v = cleaned_data.get('passphrase_verify')
        p_pf = cleaned_data.get('parent_passphrase')
        extension = cleaned_data.get('extension')
        crl_dpoints = cleaned_data.get('crl_dpoints')
        
        enc_p_pf = None
        
        if name in PKI_CA_NAME_BLACKLIST:
            self._errors['name'] = ErrorList(['Name "%s" is blacklisted!' % name])
            return cleaned_data
        
        if action in ('create', 'renew'):
            if action == 'create':
                if not pf_v or pf != pf_v:
                    self.errors['passphrase_verify'] = ErrorList(['Passphrase mismtach!'])
                
                ## Verify that we're not creating a certificate that already exists
                if name and os.path.isdir(os.path.join(PKI_DIR, name)):
                    self._errors['name'] = ErrorList(['Name "%s" is already in use!' % name])
            
            ## Take care that parent is active when action is revoke
            if action == 'renew':
                ca = CertificateAuthority.objects.get(name='%s' % name)
                
                ## Prevent renewal when parent is disabled
                if ca.parent is not None and ca.parent.active is not True:
                    self._errors['action'] = ErrorList(['Cannot renew CA certificate when parent "%s" isn\'t active!' % ca.parent.name])
                    return cleaned_data
                
                ## Compare passphrase
                if not pf or (ca.passphrase != md5_constructor(pf).hexdigest()):
                    self._errors['passphrase'] = ErrorList(['Passphrase is wrong. Enter correct passphrase for CA "%s"' % cleaned_data.get('common_name')])
            
            if parent:                
                ca = CertificateAuthority.objects.get(name='%s' % parent.name)
                if p_pf:
                    enc_p_pf = md5_constructor(p_pf).hexdigest()
                
                ## Check if parent allows sub CA
                if ca.is_edge_ca():
                    self._errors['parent'] = ErrorList(['Parent\'s x509 extension doesn\'t allow a sub CA. Only non CA certificates can be created'])
                    
                ## Check parent passphrase if not RootCA
                if ca.passphrase != enc_p_pf:
                    self._errors['parent_passphrase'] = ErrorList(['Passphrase is wrong. Enter correct passphrase for CA "%s"' % parent])
            
            ## Verify CRL distribution settings
            x509 = get_object_or_404(x509Extension, name=extension)
            if x509.crl_distribution_point and not crl_dpoints:
                self._errors['crl_dpoints'] = ErrorList(['CRL Distribution Points are required by x509 extension "%s"' % extension])
        elif action == 'revoke':
            if parent:
                ca = CertificateAuthority.objects.get(name='%s' % parent.name)
                enc_p_pf = md5_constructor(cleaned_data.get('parent_passphrase')).hexdigest()
                
                ## Check parent passphrase
                if ca.passphrase != enc_p_pf:
                    self._errors['parent_passphrase'] = ErrorList(['Passphrase is wrong. Enter correct passphrase for CA "%s"' % parent])
            else:
                self._errors['action'] = ErrorList(['You cannot revoke a self-signed root certificate as there\'s no CA to revoke against. Delete it instead!'])
        
        return cleaned_data

Example 80

Project: foodnetwork Source File: views.py
@login_required
def new_process(request, process_type_id):
    try:
        foodnet = food_network()
    except FoodNetwork.DoesNotExist:
        return render_to_response('distribution/network_error.html')
    process_manager = get_producer(request)

    weekstart = next_delivery_date()
    weekend = weekstart + datetime.timedelta(days=5)
    expired_date = weekstart + datetime.timedelta(days=5)
    pt = get_object_or_404(ProcessType, id=process_type_id)

    input_types = pt.input_type.stockable_children()
    input_select_form = None
    input_create_form = None
    input_lot_qties = []
    if pt.use_existing_input_lot:
        input_lots = InventoryItem.objects.filter(
            product__in=input_types, 
            inventory_date__lte=weekend,
            expiration_date__gte=expired_date,
            remaining__gt=Decimal("0"))
        initial_data = {"quantity": Decimal("0")}

        for lot in input_lots:
            input_lot_qties.append([lot.id, float(lot.avail_qty())])
        if input_lots:
            initial_data = {"quantity": input_lots[0].remaining,}
        input_select_form = InputLotSelectionForm(input_lots, data=request.POST or None, prefix="inputselection", initial=initial_data)
    else:
        input_create_form = InputLotCreationForm(input_types, data=request.POST or None, prefix="inputcreation")

    # todo: default service provider to process_manager?
    service_label = "Processing Service"
    service_formset = None
    steps = pt.number_of_processing_steps
    if steps > 1:
        service_label = "Processing Services"
    ServiceFormSet = formset_factory(ProcessServiceForm, extra=0)
    initial_data = []
    for x in range(steps):
        initial_data.append({"from_whom": process_manager.id})
    print "initial_data", initial_data
    service_formset = ServiceFormSet(
        data=request.POST or None, 
        prefix="service",
        initial=initial_data,
    )

    output_types = pt.output_type.stockable_children()

    output_label = "Output Lot"
    output_formset = None
    outputs = pt.number_of_output_lots
    if outputs > 1:
        output_label = "Output Lots"
    OutputFormSet = formset_factory(OutputLotCreationFormsetForm, extra=outputs)
    output_formset = OutputFormSet(data=request.POST or None, prefix="output")
    for form in output_formset.forms:
        form.fields['product'].choices = [(prod.id, prod.long_name) for prod in output_types]

    process = None

    if request.method == "POST":
        #import pdb; pdb.set_trace()
        if input_create_form:
            if input_create_form.is_valid():
                data = input_create_form.cleaned_data
                lot = input_create_form.save(commit=False)
                producer = data["producer"]
                qty = data["planned"]
                process = Process(
                    process_type = pt,
                    process_date = weekstart,
                    managed_by = process_manager,
                )
                process.save()
                lot.inventory_date = weekstart
                lot.remaining = qty
                lot.save()
                issue = InventoryTransaction(
                    transaction_type = "Issue",
                    process = process,
                    # todo: is to_whom correct in all these process tx?
                    from_whom = producer, 
                    to_whom = producer, 
                    inventory_item = lot,
                    transaction_date = weekstart,
                    amount = qty)
                issue.save()

        elif input_select_form:
            if input_select_form.is_valid():
                data = input_select_form.cleaned_data
                lot_id = data['lot']
                lot = InventoryItem.objects.get(id=lot_id)
                producer = lot.producer
                qty = data["quantity"]
                process = Process(
                    process_type = pt,
                    process_date = weekstart,
                    managed_by = process_manager,
                )
                process.save()
                issue = InventoryTransaction(
                    transaction_type = "Issue",
                    process = process,
                    from_whom = producer, 
                    to_whom = producer, 
                    inventory_item = lot,
                    transaction_date = weekstart,
                    amount = qty)
                issue.save()

        if process:
            if service_formset:
                 # todo: shd be selective, or not?
                if service_formset.is_valid():
                    for service_form in service_formset.forms:
                        tx = service_form.save(commit=False)
                        tx.to_whom = foodnet
                        tx.process = process
                        tx.transaction_date = weekstart
                        tx.save()
            #import pdb; pdb.set_trace()
            if output_formset:
                for form in output_formset.forms:
                    if form.is_valid():
                        data = form.cleaned_data
                        qty = data["planned"]
                        if qty:
                            lot = form.save(commit=False)
                            producer = data["producer"]
                            lot.inventory_date = weekstart
                            lot.save()
                            tx = InventoryTransaction(
                                transaction_type = "Production",
                                process = process,
                                from_whom = producer, 
                                to_whom = producer, 
                                inventory_item = lot,
                                transaction_date = weekstart,
                                amount = qty)
                            tx.save()

            return HttpResponseRedirect('/%s/%s/'
               % ('producer/process', process.id))

    return render_to_response('distribution/new_process.html', {
        'input_lot_qties': input_lot_qties,
        'input_select_form': input_select_form,
        'input_create_form': input_create_form,
        'service_formset': service_formset,
        'service_label': service_label,
        'output_formset': output_formset,
        'output_label': output_label,
        'tabnav': "producer/producer_tabnav.html",
        }, context_instance=RequestContext(request))

Example 81

Project: site Source File: problem.py
@login_required
def problem_submit(request, problem=None, submission=None):
    if submission is not None and not request.user.has_perm('judge.resubmit_other') and \
                    get_object_or_404(Submission, id=int(submission)).user.user != request.user:
        raise PermissionDenied()

    profile = request.user.profile
    if request.method == 'POST':
        form = ProblemSubmitForm(request.POST, instance=Submission(user=profile))
        if form.is_valid():
            if (not request.user.has_perm('judge.spam_submission') and
                        Submission.objects.filter(user=profile, was_rejudged=False).exclude(
                            status__in=['D', 'IE', 'CE', 'AB']).count() > 2):
                return HttpResponse('<h1>You submitted too many submissions.</h1>', status=503)
            if not form.cleaned_data['problem'].allowed_languages.filter(
                    id=form.cleaned_data['language'].id).exists():
                raise PermissionDenied()
            if not form.cleaned_data['problem'].is_accessible_by(request.user):
                user_logger.info('Naughty user %s wants to submit to %s without permission',
                                 request.user.username, form.cleaned_data['problem'].code)
                return HttpResponseForbidden('<h1>Do you want me to ban you?</h1>')
            if not request.user.is_superuser and form.cleaned_data['problem'].banned_users.filter(
                    id=profile.id).exists():
                return generic_message(request, _('Banned from Submitting'),
                                       _('You have been declared persona non grata for this problem. '
                                         'You are permanently barred from submitting this problem.'))
            model = form.save()

            profile.update_contest()
            if profile.current_contest is not None:
                try:
                    contest_problem = model.problem.contests.get(contest=profile.current_contest.contest)
                except ContestProblem.DoesNotExist:
                    pass
                else:
                    contest = ContestSubmission(submission=model, problem=contest_problem,
                                                participation=profile.current_contest)
                    contest.save()

            model.judge()
            return HttpResponseRedirect(reverse('submission_status', args=[str(model.id)]))
        else:
            form_data = form.cleaned_data
    else:
        initial = {'language': profile.language}
        if problem is not None:
            initial['problem'] = get_object_or_404(Problem, code=problem)
            if not initial['problem'].is_accessible_by(request.user):
                raise Http404()
        if submission is not None:
            try:
                sub = get_object_or_404(Submission, id=int(submission))
                initial['source'] = sub.source
                initial['language'] = sub.language
            except ValueError:
                raise Http404()
        form = ProblemSubmitForm(initial=initial)
        form_data = initial
    if 'problem' in form_data:
        form.fields['language'].queryset = (form_data['problem'].usable_languages.order_by('name', 'key')
                                            .prefetch_related(
            Prefetch('runtimeversion_set', RuntimeVersion.objects.order_by('priority'))))
    if 'language' in form_data:
        form.fields['source'].widget.mode = form_data['language'].ace
    form.fields['source'].widget.theme = profile.ace_theme
    return render(request, 'problem/submit.jade', {
        'form': form,
        'title': _('Submit'),
        'langs': Language.objects.all(),
        'no_judges': not form.fields['language'].queryset,
        'ACE_URL': ACE_URL
    })

Example 82

Project: django-timepiece Source File: views.py
@login_required
def view_user_timesheet(request, user_id, active_tab):
    # User can only view their own time sheet unless they have a permission.
    user = get_object_or_404(User, pk=user_id)
    has_perm = request.user.has_perm('entries.view_entry_summary')
    if not (has_perm or user.pk == request.user.pk):
        return HttpResponseForbidden('Forbidden')

    FormClass = UserYearMonthForm if has_perm else YearMonthForm
    form = FormClass(request.GET or None)
    if form.is_valid():
        if has_perm:
            from_date, to_date, form_user = form.save()
            if form_user and request.GET.get('yearmonth', None):
                # Redirect to form_user's time sheet.
                # Do not use request.GET in urlencode to prevent redirect
                # loop caused by yearmonth parameter.
                url = reverse('view_user_timesheet', args=(form_user.pk,))
                request_data = {
                    'month': from_date.month,
                    'year': from_date.year,
                    'user': form_user.pk,  # Keep so that user appears in form.
                }
                url += '?{0}'.format(urlencode(request_data))
                return HttpResponseRedirect(url)
        else:  # User must be viewing their own time sheet; no redirect needed.
            from_date, to_date = form.save()
        from_date = utils.add_timezone(from_date)
        to_date = utils.add_timezone(to_date)
    else:
        # Default to showing this month.
        from_date = utils.get_month_start()
        to_date = from_date + relativedelta(months=1)

    entries_qs = Entry.objects.filter(user=user)
    month_qs = entries_qs.timespan(from_date, span='month')
    extra_values = ('start_time', 'end_time', 'comments', 'seconds_paused',
                    'id', 'location__name', 'project__name', 'activity__name',
                    'status')
    month_entries = month_qs.date_trunc('month', extra_values).order_by('start_time')
    # For grouped entries, back date up to the start of the week.
    first_week = utils.get_week_start(from_date)
    month_week = first_week + relativedelta(weeks=1)
    grouped_qs = entries_qs.timespan(first_week, to_date=to_date)
    intersection = grouped_qs.filter(
        start_time__lt=month_week, start_time__gte=from_date)
    # If the month of the first week starts in the previous
    # month and we dont have entries in that previous ISO
    # week, then update the first week to start at the first
    # of the actual month
    if not intersection and first_week.month < from_date.month:
        grouped_qs = entries_qs.timespan(from_date, to_date=to_date)
    totals = grouped_totals(grouped_qs) if month_entries else ''
    project_entries = month_qs.order_by().values(
        'project__name').annotate(sum=Sum('hours')).order_by('-sum')
    summary = Entry.summary(user, from_date, to_date)

    show_approve = show_verify = False
    can_change = request.user.has_perm('entries.change_entry')
    can_approve = request.user.has_perm('entries.approve_timesheet')
    if can_change or can_approve or user == request.user:
        statuses = list(month_qs.values_list('status', flat=True))
        total_statuses = len(statuses)
        unverified_count = statuses.count(Entry.UNVERIFIED)
        verified_count = statuses.count(Entry.VERIFIED)
        approved_count = statuses.count(Entry.APPROVED)
    if can_change or user == request.user:
        show_verify = unverified_count != 0
    if can_approve:
        show_approve = all([
            verified_count + approved_count == total_statuses,
            verified_count > 0,
            total_statuses != 0,
        ])

    return render(request, 'timepiece/user/timesheet/view.html', {
        'active_tab': active_tab or 'overview',
        'year_month_form': form,
        'from_date': from_date,
        'to_date': to_date - relativedelta(days=1),
        'show_verify': show_verify,
        'show_approve': show_approve,
        'timesheet_user': user,
        'entries': month_entries,
        'grouped_totals': totals,
        'project_entries': project_entries,
        'summary': summary,
    })

Example 83

Project: drawquest-web Source File: api.py
@api('share/create_for_channel')
def share_create_for_channel(request, channel, comment_id=None, quest_id=None, download_link=False, is_invite=False):
    ret = {}

    def download_share():
        return ShareTrackingUrl.create(request.user, 'http://example.com/download', channel)

    if not download_link and comment_id is not None and quest_id is not None:
        raise ValueError("Can't specify both a comment and quest to share.")

    if download_link:
        return {'share_url': download_share().url_for_channel()}

    if is_invite:
        if quest_id is None:
            share_url = download_share().url_for_channel()

            if channel == 'twitter':
                message = _(u"Come draw with me on @DrawQuest! %(url)s" % {'url': share_url})
            elif channel == 'email':
                follow_me_message = _("You can follow me in the app as \"%(username)s\"" % {'username': getattr(request.user, 'username')}) if request.user.is_authenticated() else ''
                message = _(u"""I'm using DrawQuest, a free creative drawing app for iPhone, iPod touch, and iPad. DrawQuest sends you daily drawing challenges and allows you to create your own to share with friends. %(follow_me_message)s

Download DrawQuest for free here: %(url)s""" % {'follow_me_message': follow_me_message, 'url': share_url})
            else:
                message = _(u"Come draw with me on DrawQuest! %(url)s" % {'url': share_url})
        else:
            quest = get_object_or_404(Quest, id=quest_id)

            if channel in ['twitter', 'facebook']:
                share_url = get_share_page_url_with_tracking(quest, request.user, channel, request=request)
            else:
                share_url = download_share().url_for_channel()

            if request.user.is_authenticated() and quest.author_id == request.user.id:
                if channel == 'twitter':
                    message = _(u"I just created a Quest on @DrawQuest! \"%(quest_title)s\" Come draw it with me: %(url)s" % {'quest_title': quest.title, 'url': share_url})
                else:
                    message = _(u"I just created a Quest on DrawQuest! \"%(quest_title)s\" Come draw it with me: %(url)s" % {'quest_title': quest.title, 'url': share_url})
            else:
                if channel == 'twitter':
                    message = _(u"Come draw \"%(quest_title)s\" with me on @DrawQuest! %(url)s" % {'quest_title': quest.title, 'url': share_url})
                else:
                    message = _(u"Come draw \"%(quest_title)s\" with me on DrawQuest! %(url)s" % {'quest_title': quest.title, 'url': share_url})

        return {
            'share_url': share_url,
            'message': message,
        }

    if comment_id is None and quest_id is None:
        share = ShareTrackingUrl.create(request.user, None, channel)
        ret['share_id'] = share.id
        url = share.url_for_channel()
    else:
        if quest_id is not None:
            shared_obj = get_object_or_404(Quest, id=quest_id)
            quest_title = shared_obj.title
        else:
            shared_obj = get_object_or_404(QuestComment, id=comment_id)
            quest_title = shared_obj.parent_comment.title

        author = User.objects.get(id=shared_obj.author_id)

        if channel in ['twitter', 'facebook']:
            url = get_share_page_url_with_tracking(shared_obj, request.user, channel, request=request)
        else:
            url = download_share().url_for_channel()

        if channel == 'twitter':
            if quest_id is not None:
                ret['tweet'] = _(u'Come draw "%(quest_title)s" with me on @DrawQuest! %(url)s' % {'quest_title': quest_title, 'url': url})
            else:
                ret['tweet'] = _(u'"%(quest_title)s" %(url)s via @DrawQuest' % {'quest_title': quest_title, 'url': url})

            if author.kv.twitter_privacy.get() == False:
                try:
                    author_screen_name = ret['twitter_screen_name'] = author.twitteruser.screen_name
                    if quest_id is not None:
                        ret['tweet'] = _(u'Come draw "%(quest_title)s" by @%(screen_name)s with me on @DrawQuest! %(url)s' % {'quest_title': quest_title, 'url': url, 'screen_name': author_screen_name})
                    else:
                        ret['tweet'] = _(u'"%(quest_title)s" %(url)s by @%(screen_name)s via @DrawQuest' % {'quest_title': quest_title, 'url': url, 'screen_name': author_screen_name})
                except (AttributeError, TwitterUser.DoesNotExist):
                    pass

            ret['message'] = ret['tweet']
        elif channel == 'email':
            if quest_id is not None:
                ret['message'] = _(u"""I'm using DrawQuest, a free creative drawing app for iPhone, iPod touch, and iPad. DrawQuest sends you daily drawing challenges and allows you to create your own to share with friends. I thought you might enjoy this Quest: \"%(quest_title)s\"

Download DrawQuest for free here: %(url)s""" % {'quest_title': quest_title, 'url': url})
            else:
                ret['message'] = _(u"""I thought you'd like this drawing made with DrawQuest, a free creative drawing app for iPhone, iPod touch, and iPad.

\"%(quest_title)s\" %(url)s

Download DrawQuest for free here: %(download_url)s""" % {'quest_title': quest_title, 'url': get_share_page_url_with_tracking(shared_obj, request.user, channel, request=request), 'download_url': url})
        else:
            if quest_id is not None:
                ret['message'] = _(u"Come draw \"%(quest_title)s\" with me on DrawQuest! %(url)s" % {'quest_title': quest_title, 'url': url})
            else:
                if channel == 'text_message':
                    ret['message'] = _(u"""Check out this drawing on DrawQuest: \"%(quest_title)s\" %(url)s

Download DrawQuest for free here: %(download_url)s""" % {'quest_title': quest_title, 'url': get_share_page_url_with_tracking(shared_obj, request.user, channel, request=request), 'download_url': url})
                else:
                    ret['message'] = _(u"Check out this drawing on DrawQuest: \"%(quest_title)s\" %(url)s" % {'quest_title': quest_title, 'url': url})

    if channel == 'facebook':
        url = 'http://example.com' + url

    if not ret.get('message'):
        if channel == 'twitter':
            ret['message'] = _(u"Come draw with me on @DrawQuest! %(url)s" % {'url': url})
        else:
            ret['message'] = _(u"Come draw with me on DrawQuest! %(url)s" % {'url': url})

    ret['share_url'] = url

    return ret

Example 84

Project: treeio Source File: forms.py
    def __init__(self, user, liability_id=None, order_id=None, *args, **kwargs):
        super(TransactionForm, self).__init__(*args, **kwargs)

        self.fields['name'].label = _("Description")
        self.fields['category'].label = _("Category")
        self.fields['source'].label = _("Source")
        self.fields['target'].label = _("Target")
        self.fields['account'].label = _("Bank Account")
        self.fields['datetime'].label = _("Date & Time")
        self.fields['value_currency'].label = _("Currency")
        self.fields['value_currency'].widget.attrs.update(
            {'popuplink': reverse('finance_currency_add')})
        self.fields['value_currency'].initial = Currency.objects.get(
            is_default=True)
        self.fields['value_display'].label = _("Value")
        self.fields['details'].label = _("Details")

        self.fields['source'].queryset = Object.filter_permitted(
            user, Contact.objects)
        self.fields['target'].queryset = Object.filter_permitted(
            user, Contact.objects)

        self.fields['source'].widget.attrs.update({'class': 'autocomplete',
                                                   'callback': reverse('identities_ajax_contact_lookup')})
        self.fields['target'].widget.attrs.update({'class': 'autocomplete',
                                                   'callback': reverse('identities_ajax_contact_lookup')})

        self.fields['source'].widget.attrs.update(
            {'popuplink': reverse('identities_contact_add')})
        self.fields['target'].widget.attrs.update(
            {'popuplink': reverse('identities_contact_add')})

        self.fields['datetime'].widget.attrs.update(
            {'class': 'datetimepicker'})

        self.fields['account'].queryset = Object.filter_permitted(
            user, Account.objects)

        try:
            conf = ModuleSetting.get_for_module(
                'treeio.finance', 'default_account')[0]
            self.fields['account'].initial = long(conf.value)
        except Exception:
            pass

        self.fields['liability'].queryset = Object.filter_permitted(
            user, Liability.objects)
        self.fields['liability'].label = _("Liability / Receivable")

        if order_id:
            order = get_object_or_404(SaleOrder, pk=order_id)
            self.fields['name'].initial = order.reference
            if order.client:
                self.fields['source'].initial = order.client

            # default company
            try:
                conf = ModuleSetting.get_for_module(
                    'treeio.finance', 'my_company')[0]
                self.fields['target'].initial = Contact.objects.get(
                    pk=long(conf.value))

            except Exception:
                pass
            self.fields['details'].initial = order.details
            self.fields['value_display'].initial = order.balance_due()
            self.fields['value_currency'].initial = order.currency

        if liability_id:
            self.fields['liability'].initial = liability_id
            liability = get_object_or_404(Liability, pk=liability_id)
            self.fields['name'].initial = liability.name
            self.fields['source'].initial = liability.source
            self.fields['target'].initial = liability.target
            self.fields['details'].initial = liability.details
            self.fields['category'].initial = liability.category
            self.fields['account'].initial = liability.account
            self.fields['value_display'].initial = liability.value_display
            self.fields['value_currency'].initial = liability.value_currency

Example 85

Project: editorsnotes-server Source File: projects.py
@login_required
@reversion.create_revision()
def project_roster(request, project_slug):
    o = {}
    user = request.user


    project_qs = Project.objects\
            .prefetch_related('roles__group__permissions')\
            .select_related('roles__group__permissions',
                            'roles__group__users')
    project = get_object_or_404(project_qs, slug=project_slug)

    o['breadcrumb'] = (
        (project.name, project.get_absolute_url()),
        ('Roster', None)
    )

    can_view = user.has_project_perm(project, 'main.view_project_roster')
    if not can_view:
        return HttpResponseForbidden(VIEW_ERROR_MSG.format(project))
    can_change = user.has_project_perm(project, 'main.change_project_roster')

    ProjectRosterFormSet = forms.make_project_roster_formset(project)
    ProjectInvitationFormSet = forms.make_project_invitation_formset(project)

    if request.method == 'POST':

        if not can_change:
            return HttpResponseForbidden(CHANGE_ERROR_MSG.format(project))

        if request.POST.get('roster-TOTAL_FORMS'):
            o['roster_formset'] = ProjectRosterFormSet(request.POST, prefix='roster')
            if o['roster_formset'].is_valid():
                o['roster_formset'].save()
                messages.add_message(request, messages.SUCCESS,
                                     'Roster for {} saved.'.format(project.name))
                return HttpResponseRedirect(request.path)
            else:
                o['invitation_formset'] = ProjectInvitationFormSet(prefix='invitation')

        elif request.POST.get('invitation-TOTAL_FORMS'):
            o['invitation_formset'] = ProjectInvitationFormSet(request.POST,
                                                               prefix='invitation')
            if o['invitation_formset'].is_valid():
                for form in o['invitation_formset']:
                    if form.cleaned_data.get('DELETE', False):
                        if form.instance:
                            form.instance.delete()
                        continue
                    obj = form.save(commit=False)
                    if not obj.id:
                        if 'email' not in form.cleaned_data:
                            continue
                        obj.creator = request.user
                        obj.project = project
                    obj.save()
                messages.add_message(request, messages.SUCCESS,
                                     'Roster for {} saved.'.format(project.name))
                return HttpResponseRedirect(request.path)
            else:
                o['roster_formset'] = ProjectRosterFormSet(prefix='roster')
        else:
            return HttpResponseBadRequest()


    elif can_change:
        o['roster_formset'] = ProjectRosterFormSet(prefix='roster')
        o['invitation_formset'] = ProjectInvitationFormSet(prefix='invitation')

    o['project'] = project
    o['roster'] = [(u, project.get_role_for(u))
                   for u in project.members.order_by('-last_login')]

    return render_to_response(
        'project_roster.html', o, context_instance=RequestContext(request))

Example 86

Project: cdr-stats Source File: views.py
@login_required
@check_user_detail('accountcode')
def customer_detail_change(request):
    """User Detail change on Customer UI

    **Attributes**:

        * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, UserPasswordChangeForm
        * ``template`` - 'user_profile/user_detail_change.html'

    **Logic Description**:

        * User is able to change their details.
    """
    user_detail = get_object_or_404(User, username=request.user)

    try:
        user_detail_extened = UserProfile.objects.get(user=user_detail)
    except UserProfile.DoesNotExist:
        # create UserProfile
        user_detail_extened = UserProfile(user=user_detail)
        # DEMO / Disable
        if not settings.DEMO_MODE:
            user_detail_extened.save()

    user_detail_form = UserChangeDetailForm(request.user, instance=user_detail)
    user_detail_extened_form = UserChangeDetailExtendForm(request.user, instance=user_detail_extened)

    user_password_form = UserPasswordChangeForm(user=request.user)

    msg_detail = ''
    msg_pass = ''
    error_detail = ''
    error_pass = ''
    action = ''

    if 'action' in request.GET:
        action = request.GET['action']

    if request.method == 'POST':
        if request.POST['form-type'] == "change-detail":
            user_detail_form = UserChangeDetailForm(request.user, request.POST, instance=user_detail)
            user_detail_extened_form = UserChangeDetailExtendForm(request.user, request.POST, instance=user_detail_extened)
            action = 'tabs-1'
            if user_detail_form.is_valid() and user_detail_extened_form.is_valid():
                # DEMO / Disable
                if not settings.DEMO_MODE:
                    user_detail_form.save()
                    user_detail_extened_form.save()
                msg_detail = _('detail has been changed.')
            else:
                error_detail = _('please correct the errors below.')
        else:
            # change-password
            user_password_form = UserPasswordChangeForm(user=request.user, data=request.POST)
            action = 'tabs-2'
            if user_password_form.is_valid():
                # DEMO / Disable
                if not settings.DEMO_MODE:
                    user_password_form.save()
                msg_pass = _('your password has been changed.')
            else:
                error_pass = _('please correct the errors below.')
    data = {
        'user_detail_form': user_detail_form,
        'user_detail_extened_form': user_detail_extened_form,
        'user_password_form': user_password_form,
        'msg_detail': msg_detail,
        'msg_pass': msg_pass,
        'error_detail': error_detail,
        'error_pass': error_pass,
        'action': action,
    }
    return render_to_response('user_profile/user_detail_change.html', data, context_instance=RequestContext(request))

Example 87

Project: approval_frame Source File: views.py
@require_http_methods(['POST'])
def vote(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)

    # Get the type of vote method required for this poll.
    # Type 1 - No restriction on the number of ballots.
    # Type 2 - Only users with registered accounts are allowed to vote.
    # Type 3 - Only users with the invitation email link (& poll owner) are allowed to vote.
    poll_vtype = poll.vtype

    if poll_vtype == 1:
        if not poll.is_closed():
            ballot = poll.ballot_set.create(timestamp=timezone.now())
            for counter, choice in enumerate(poll.choice_set.all()):
                if 'choice' + str(counter + 1) in request.POST:
                    ballot.vote_set.create(choice=choice)
                    ballot.save()
            for key, value in request.POST.items():
                if key + 'txt' in request.POST:
                    choice_txt = request.POST[key + 'txt'].strip()
                    if choice_txt:
                        choice = poll.choice_set.filter(choice_text=choice_txt)
                        if not choice:
                            if 'linkurl-' + key in request.POST:
                                choicelink_txt = request.POST['linkurl-' + key].strip()
                            if choicelink_txt:
                                choice = poll.choice_set.create(
                                    choice_text=choice_txt,
                                    choice_link=choicelink_txt
                                    )
                            else:
                                choice = poll.choice_set.create(choice_text=choice_txt)
                            ballot_exist = ballot.vote_set.filter(choice=choice)
                            if not ballot_exist:
                                ballot.vote_set.create(choice=choice)
                                ballot.save()
            poll.save()
            return HttpResponseRedirect(
                reverse('approval_polls:results', args=(poll.id,))
            )
        else:
            return HttpResponseRedirect(
                reverse('approval_polls:detail', args=(poll.id,))
                )
    elif poll_vtype == 2:
        # Type 2 poll - the user is required to login to vote.
        if request.user.is_authenticated():
            # Check if a poll is closed
            if not poll.is_closed():
                # Check if a ballot exists under the users name.
                existing_ballots = Ballot.objects.filter(
                    poll_id=poll_id,
                    user_id=request.user
                )
                if not existing_ballots:
                    # Add the user as the foreign key
                    ballot = poll.ballot_set.create(
                        timestamp=timezone.now(),
                        user=request.user
                    )

                    for counter, choice in enumerate(poll.choice_set.all()):
                        if 'choice' + str(counter + 1) in request.POST:
                            ballot.vote_set.create(choice=choice)
                            ballot.save()
                    for key, value in request.POST.items():
                        if key + 'txt' in request.POST:
                            choice_txt = request.POST[key + 'txt'].strip()
                            if choice_txt:
                                choice = poll.choice_set.filter(choice_text=choice_txt)
                                if not choice:
                                    if 'linkurl-' + key in request.POST:
                                        choicelink_txt = request.POST['linkurl-' + key].strip()
                                    if choicelink_txt:
                                        choice = poll.choice_set.create(
                                            choice_text=choice_txt,
                                            choice_link=choicelink_txt
                                            )
                                    else:
                                        choice = poll.choice_set.create(choice_text=choice_txt)
                                    ballot_exist = ballot.vote_set.filter(choice=choice)
                                    if not ballot_exist:
                                        ballot.vote_set.create(choice=choice)
                                        ballot.save()
                    poll.save()
                    return HttpResponseRedirect(
                        reverse('approval_polls:results', args=(poll.id,))
                    )
                else:
                    ballot = poll.ballot_set.get(user=request.user)
                    for counter, choice in enumerate(poll.choice_set.all()):
                        if 'choice' + str(counter + 1) in request.POST:
                            ballot_exist = ballot.vote_set.filter(
                                choice=choice
                                )
                            if not ballot_exist:
                                ballot.vote_set.create(choice=choice)
                                ballot.save()
                        else:
                            ballot_exist = ballot.vote_set.filter(
                                choice=choice
                                )
                            if ballot_exist:
                                ballot_exist.delete()
                                ballot.save()
                    for key, value in request.POST.items():
                        if key + 'txt' in request.POST:
                            choice_txt = request.POST[key + 'txt'].strip()
                            if choice_txt:
                                choice = poll.choice_set.filter(choice_text=choice_txt)
                                if not choice:
                                    if 'linkurl-' + key in request.POST:
                                        choicelink_txt = request.POST['linkurl-' + key].strip()
                                    if choicelink_txt:
                                        choice = poll.choice_set.create(
                                            choice_text=choice_txt,
                                            choice_link=choicelink_txt
                                            )
                                    else:
                                        choice = poll.choice_set.create(choice_text=choice_txt)
                                    ballot_exist = ballot.vote_set.filter(choice=choice)
                                    if not ballot_exist:
                                        ballot.vote_set.create(choice=choice)
                                        ballot.save()
                    poll.save()
                    return HttpResponseRedirect(
                        reverse('approval_polls:results', args=(poll.id,))
                        )
            else:
                return HttpResponseRedirect(
                    reverse('approval_polls:detail', args=(poll.id,))
                    )
        else:
            return HttpResponseRedirect(
                reverse('auth_login') + '?next=' +
                reverse('approval_polls:detail', args=(poll.id,))
            )
    elif poll_vtype == 3:
        # Type 3 - Vote through the email invitation link.
        invitations = []
        auth_user = None
        ballot = None

        # Find the appropriate ballot and user
        if 'invitation_key' in request.POST and 'invitation_email' in request.POST:
            invitations = VoteInvitation.objects.filter(
                key=request.POST['invitation_key'],
                email=request.POST['invitation_email'],
                poll_id=poll.id,
            )
            if invitations:
                ballot = invitations[0].ballot

            # Check for the same email for an existing user in the database.
            users = User.objects.filter(email=request.POST['invitation_email'])
            if users:
                auth_user = users[0]

        elif request.user.is_authenticated():
            auth_user = request.user
            invitations = VoteInvitation.objects.filter(
                email=request.user.email,
                poll_id=poll.id,
            )
            if invitations:
                ballot = invitations[0].ballot
            elif request.user == poll.user:
                # The owner of this poll is allowed to vote by default
                ballots = poll.ballot_set.filter(user=auth_user)
                if ballots:
                    ballot = ballots[0]

        if invitations or request.user == poll.user:
            if not poll.is_closed():
                if ballot is None:
                    ballot = poll.ballot_set.create(timestamp=timezone.now(), user=auth_user)
                    for counter, choice in enumerate(poll.choice_set.all()):
                        if 'choice' + str(counter + 1) in request.POST:
                            ballot.vote_set.create(choice=choice)
                            ballot.save()
                else:
                    for counter, choice in enumerate(poll.choice_set.all()):
                        if 'choice' + str(counter + 1) in request.POST:
                            ballot_exist = ballot.vote_set.filter(
                                choice=choice
                            )
                            if not ballot_exist:
                                ballot.vote_set.create(choice=choice)
                                ballot.save()
                        else:
                            ballot_exist = ballot.vote_set.filter(
                                choice=choice
                            )
                            if ballot_exist:
                                ballot_exist.delete()
                                ballot.save()
                if poll.show_write_in:
                    for key, value in request.POST.items():
                        if key + 'txt' in request.POST:
                            choice_txt = request.POST[key + 'txt'].strip()
                            if choice_txt:
                                choice = poll.choice_set.filter(choice_text=choice_txt)
                                if not choice:
                                    if 'linkurl-' + key in request.POST:
                                        choicelink_txt = request.POST['linkurl-' + key].strip()
                                    if choicelink_txt:
                                        choice = poll.choice_set.create(
                                            choice_text=choice_txt,
                                            choice_link=choicelink_txt
                                            )
                                    else:
                                        choice = poll.choice_set.create(choice_text=choice_txt)
                                    ballot_exist = ballot.vote_set.filter(choice=choice)
                                    if not ballot_exist:
                                        ballot.vote_set.create(choice=choice)
                                        ballot.save()
                poll.save()
                if invitations:
                    invitations[0].ballot = ballot
                    invitations[0].save()
                return HttpResponseRedirect(
                    reverse('approval_polls:results', args=(poll.id,))
                )
            else:
                return HttpResponseRedirect(
                    reverse('approval_polls:detail', args=(poll.id,))
                )
        else:
            return HttpResponseRedirect(
                reverse('approval_polls:detail', args=(poll.id,))
                )

Example 88

Project: wger Source File: workout.py
@login_required
def timer(request, day_pk):
    '''
    The timer view ("gym mode") for a workout
    '''

    day = get_object_or_404(Day, pk=day_pk, training__user=request.user)
    canonical_day = day.canonical_representation
    context = {}
    step_list = []
    last_log = LastWeightHelper(request.user)

    # Go through the workout day and create the individual 'pages'
    for set_dict in canonical_day['set_list']:

        if not set_dict['is_superset']:
            for exercise_dict in set_dict['exercise_list']:
                exercise = exercise_dict['obj']
                for key, element in enumerate(exercise_dict['reps_list']):
                    reps = exercise_dict['reps_list'][key]
                    rep_unit = exercise_dict['repetition_units'][key]
                    weight_unit = exercise_dict['weight_units'][key]
                    default_weight = last_log.get_last_weight(exercise,
                                                              reps,
                                                              exercise_dict['weight_list'][key])

                    step_list.append({'current_step': uuid.uuid4().hex,
                                      'step_percent': 0,
                                      'step_nr': len(step_list) + 1,
                                      'exercise': exercise,
                                      'type': 'exercise',
                                      'reps': reps,
                                      'rep_unit': rep_unit,
                                      'weight': default_weight,
                                      'weight_unit': weight_unit})
                    if request.user.userprofile.timer_active:
                        step_list.append({'current_step': uuid.uuid4().hex,
                                          'step_percent': 0,
                                          'step_nr': len(step_list) + 1,
                                          'type': 'pause',
                                          'time': request.user.userprofile.timer_pause})

        # Supersets need extra work to group the exercises and reps together
        else:
            total_reps = len(set_dict['exercise_list'][0]['reps_list'])
            for i in range(0, total_reps):
                for exercise_dict in set_dict['exercise_list']:
                    reps = exercise_dict['reps_list'][i]
                    rep_unit = exercise_dict['repetition_units'][i]
                    weight_unit = exercise_dict['weight_units'][i]
                    default_weight = exercise_dict['weight_list'][i]
                    exercise = exercise_dict['obj']

                    step_list.append({'current_step': uuid.uuid4().hex,
                                      'step_percent': 0,
                                      'step_nr': len(step_list) + 1,
                                      'exercise': exercise,
                                      'type': 'exercise',
                                      'reps': reps,
                                      'rep_unit': rep_unit,
                                      'weight_unit': weight_unit,
                                      'weight': last_log.get_last_weight(exercise,
                                                                         reps,
                                                                         default_weight)})

                if request.user.userprofile.timer_active:
                    step_list.append({'current_step': uuid.uuid4().hex,
                                      'step_percent': 0,
                                      'step_nr': len(step_list) + 1,
                                      'type': 'pause',
                                      'time': 90})

    # Remove the last pause step as it is not needed. If the list is empty,
    # because the user didn't add any repetitions to any exercise, do nothing
    try:
        step_list.pop()
    except IndexError:
        pass

    # Go through the page list and calculate the correct value for step_percent
    for i, s in enumerate(step_list):
        step_list[i]['step_percent'] = (i + 1) * 100.0 / len(step_list)

    # Depending on whether there is already a workout session for today, update
    # the current one or create a new one (this will be the most usual case)
    if WorkoutSession.objects.filter(user=request.user, date=datetime.date.today()).exists():
        session = WorkoutSession.objects.get(user=request.user, date=datetime.date.today())
        url = reverse('manager:session:edit', kwargs={'pk': session.pk})
        session_form = WorkoutSessionHiddenFieldsForm(instance=session)
    else:
        today = datetime.date.today()
        url = reverse('manager:session:add', kwargs={'workout_pk': day.training_id,
                                                     'year': today.year,
                                                     'month': today.month,
                                                     'day': today.day})
        session_form = WorkoutSessionHiddenFieldsForm()

    # Render template
    context['day'] = day
    context['step_list'] = step_list
    context['canonical_day'] = canonical_day
    context['workout'] = day.training
    context['session_form'] = session_form
    context['form_action'] = url
    context['weight_units'] = WeightUnit.objects.all()
    context['repetition_units'] = RepetitionUnit.objects.all()
    return render(request, 'workout/timer.html', context)

Example 89

Project: django-machina Source File: admin.py
    def editpermissions_index_view(self, request, forum_id=None):
        """
        Display a form to select a user or a group in order to edit its
        permissions for the considered forum.
        """
        forum = get_object_or_404(Forum, pk=forum_id) if forum_id \
            else None

        # Set up the context
        context = self.get_forum_perms_base_context(request, forum)
        context['forum'] = forum
        context['title'] = _('Forum permissions') if forum \
            else _('Global forum permissions')

        # Handles "copy permission from" form
        permissions_copied = False
        if forum and request.method == 'POST':
            forum_form = PickForumForm(request.POST)
            if forum_form.is_valid() and forum_form.cleaned_data['forum']:
                self._copy_forum_permissions(forum_form.cleaned_data['forum'], forum)
                self.message_user(request, _('Permissions successfully copied'))
                permissions_copied = True
            context['forum_form'] = forum_form
        elif forum:
            context['forum_form'] = PickForumForm()

        # Handles user or group selection
        if request.method == 'POST' and not permissions_copied:
            user_form = PickUserForm(request.POST, admin_site=self.admin_site)
            group_form = PickGroupForm(request.POST, admin_site=self.admin_site)

            if user_form.is_valid() and group_form.is_valid():
                user = user_form.cleaned_data.get('user', None) \
                    if user_form.cleaned_data else None
                anonymous_user = user_form.cleaned_data.get('anonymous_user', None) \
                    if user_form.cleaned_data else None
                group = group_form.cleaned_data.get('group', None) \
                    if group_form.cleaned_data else None

                if not user and not anonymous_user and not group:
                    user_form._errors[NON_FIELD_ERRORS] = user_form.error_class(
                        [_('Choose either a user ID, a group ID or the anonymous user'), ])
                elif user:
                    # Redirect to user
                    url_kwargs = {'forum_id': forum.id, 'user_id': user.id} if forum \
                        else {'user_id': user.id}
                    return redirect(reverse(
                        'admin:forum_forum_editpermission_user', kwargs=url_kwargs))
                elif anonymous_user:
                    # Redirect to anonymous user
                    url_kwargs = {'forum_id': forum.id} if forum else {}
                    return redirect(reverse(
                        'admin:forum_forum_editpermission_anonymous_user', kwargs=url_kwargs))
                elif group:
                    # Redirect to group
                    url_kwargs = {'forum_id': forum.id, 'group_id': group.id} if forum \
                        else {'group_id': group.id}
                    return redirect(reverse(
                        'admin:forum_forum_editpermission_group', kwargs=url_kwargs))

            context['user_errors'] = helpers.AdminErrorList(user_form, [])
            context['group_errors'] = helpers.AdminErrorList(group_form, [])
        else:
            user_form = PickUserForm(admin_site=self.admin_site)
            group_form = PickGroupForm(admin_site=self.admin_site)

        context['user_form'] = user_form
        context['group_form'] = group_form

        return render(
            request, self.editpermissions_index_view_template_name, context)

Example 90

Project: 1flow Source File: share.py
def share_one(request, item_id):
    """ Base view for sharing an article / read. """

    user = request.user

    def format_recipients(recipients):

        def pretty_name(recipient):
            return recipient.username \
                if recipient.is_active else recipient.email

        first = recipients.pop(0)

        recipients_len = len(recipients)

        if recipients_len == 0:
            return pretty_name(first)

        if recipients_len > 1:
            return _(u'{0} and {1} other persons').format(
                pretty_name(first), recipients_len)

        return _(u'{0} and another person').format(
            pretty_name(first))

    if not request.is_ajax():
        return HttpResponseBadRequest(u'Ajax is needed for this…')

    try:
        item = get_object_or_404(BaseItem, id=int(item_id))
        read = request.user.reads.get(item=item)

    except:
        LOGGER.exception(u'Could not load things to share item #%s',
                         item_id)
        return HttpResponseTemporaryServerError('BOOM')

    user_share_lock = user.share_lock
    user_share_lock.acquire()

    if request.POST:
        form = ReadShareForm(request.POST, user=request.user)

        if form.is_valid():
            message, recipients = form.save()

            if recipients:
                # Creating new friends on the fly will make
                # new accounts active by default. New friends
                # will be able to login straight ahead.
                recipients = User.get_from_emails(recipients,
                                                  create_active=True)

                try:
                    # HEADS UP: we NEED to create a new poke if the message
                    # changed. This gracefully handles the case where user A
                    # shares item I with user B with a personnal/confidential
                    # message, then shares it again with user C with a more
                    # standard message.
                    #
                    # Without the `message` field, user C will get the private
                    # message redacted for user B, which absolutely not what we
                    # want.
                    #
                    # But, if user A doesn't change the message between pokes,
                    # we can pack the recipients on the same poke in database,
                    # which seems always a good thing to save some space and
                    # avoid DB scans.

                    poke = Poke.objects.get(user=request.user,
                                            attachments=item,
                                            # `message` is *very* important,
                                            # see comment above.
                                            message=message)
                    created = False

                except Poke.DoesNotExist:
                    poke = Poke.create_poke(
                        sender=request.user,
                        message=message,
                        recipients=recipients,
                        attachments=[item],
                    )
                    created = True

                except Exception, e:
                    LOGGER.exception('sharing article via poke failed')
                    messages.warning(
                        request, _(u'Sharing article failed: {0}').format(e),
                        extra_tags='sticky safe')
                    poke = None

                if poke is not None:
                    if not created:
                        new_recipients = [r for r in recipients
                                          if r not in poke.recipients.all()]

                        if new_recipients:
                            poke.resend(recipients=new_recipients)

                    messages.info(request,
                                  _(u'Successfully shared <em>{0}</em> '
                                    u'with {1}').format(
                                      read.item.name,
                                      format_recipients(list(recipients)[:])),
                                  extra_tags='safe')

                user_share_lock.release()

            else:
                messages.success(
                    request,
                    _(u'OK, I will tenderly keep <em>{0}</em> '
                      u'for yourself only.').format(read.item.name),
                    extra_tags='safe')

            return render(request, u'snippets/share/share-one-result.html')

    else:
        form = ReadShareForm(user=request.user)

    user_share_lock.release()

    return render(request, u'snippets/share/share-one.html',
                  {'read': read, 'form': form})

Example 91

Project: Arkestra Source File: views.py
def contacts_and_people(request, slug):
    slug = slug or getattr(Entity.objects.base_entity(), "slug", None)
    entity = get_object_or_404(Entity, slug=slug, external_url=None)

    # for the menu, because next we mess up the path
    request.auto_page_url = request.path

    # for the menu, so it knows where we are
    # request.path = entity.get_website.get_absolute_url()
    request.current_page = entity.get_website
    template = entity.get_template()

    # meta values - title and meta
    title = "Contact information for %s" % entity
    meta = {
        "description": """
            Addresses, phone numbers, staff lists and other contact information
            """,
        }

    people, initials = entity.get_people_and_initials()

    # only show pagetitle if there are people
    if people:
        pagetitle = u"Contacts & people"
    else:
        pagetitle = u""

    # are there Key People to show? show key roles, plus list
    if entity.get_key_people():
        people_list_heading = _(u"Also")
        # now remove the Key People from the people list
        people = [
            person for person in people if person not in set(
                [role.person for role in entity.get_key_people()]
            )
        ]
    else:  # otherwise, just a list of the people with roles
        people_list_heading = _(u"People")
    # convert the list of Persons into a list of Members
    people = entity.get_roles_for_members(people)
    search_fields = [
        {
            "field_name": "name",
            "field_label": "Name",
            "placeholder": "Surname or first name",
            "search_keys": [
                "given_name__icontains",
                "surname__icontains",
                ],
            },
        {
            "field_name": "role",
            "field_label": "Roles",
            "placeholder": "All roles",
            "search_keys": [
                "member_of__role__icontains",
                ]
            }
        ]

    people_qs = entity.get_people()
    search = False

    for search_field in search_fields:
        field_name = search_field["field_name"]
        if field_name in request.GET:
            query = request.GET[field_name]
            search_field["value"] = query
            if query:
                search = True

            q_object = Q()
            for search_key in search_field["search_keys"]:
                lookup = {search_key: query}
                q_object |= Q(**lookup)
            people_qs = people_qs.distinct().filter(q_object)

    if search:
        people_qs = entity.get_roles_for_members(people_qs)

    return render_to_response(
        # this is a catch-all template, that then uses includes to bring in
        # extra information
        "contacts_and_people/contacts_and_people.html",
        {
            "entity": entity,
            "pagetitle": pagetitle,
            "entity.website.template": template,
            "email": entity.email,
            "title": title,
            "meta": meta,
            "precise_location": entity.precise_location,
            "access_note": entity.access_note,
            "intro_page_placeholder": entity.contacts_page_intro,
            "phone": entity.phone_contacts.all(),
            "full_address": entity.get_full_address,
            "building": entity.get_building,
            "people": people,
            "people_list_heading": people_list_heading,
            "initials_list": initials,
            "search_fields": search_fields,
            "people_qs": people_qs,
            "search": search,
        },
        RequestContext(request),
        )

Example 92

Project: transifex Source File: project.py
@login_required
@one_perm_required_or_403(pr_project_add_change,
    (Project, 'slug__exact', 'project_slug'))
def project_access_control_edit(request, project_slug):
    project = get_object_or_404(Project, slug=project_slug)
    outsourced = project.outsource
    if request.method == 'POST':
        form = ProjectAccessControlForm(request.POST, instance=project,
            user=request.user)
        if form.is_valid():
            access_control = form.cleaned_data['access_control']
            project_type = form.cleaned_data['project_type']
            project = form.save(commit=False)
            project_hub = project.outsource
            hub_request = None

            # TODO call signal project_outsourced_changed
            if 'outsourced' != project_type:
                project.outsource = None
            else:
                check = ProjectPermission(request.user)
                if not (check.maintain(project) and check.maintain(project_hub)):
                    # If the user is not maintainer of both projects it does
                    # not associate the outsource project directly.
                    # It does a request instead.
                    try:
                        hub_request = HubRequest.objects.get(project=project)
                    except ObjectDoesNotExist:
                        hub_request = HubRequest(project=project)
                    hub_request.project_hub = project_hub
                    hub_request.user = request.user
                    hub_request.save()

                    messages.success(request,
                        _("Requested to join the '%s' project hub.") % project_hub)
                    # ActionLog & Notification
                    # TODO: Use signals
                    nt = 'project_hub_join_requested'
                    context = {'hub_request': hub_request,
                               'sender': request.user}

                    # Logging action
                    action_logging(request.user, [project, project_hub], nt, context=context)

                    if settings.ENABLE_NOTICES:
                        # Send notification for project hub maintainers
                        notification.send(project_hub.maintainers.all(), nt, context)

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


            if 'hub' == project_type:
                project.is_hub = True
            else:
                project.is_hub = False

            if ('free_for_all' == access_control and
                project_type != "outsourced"):
                project.anyone_submit = True
            else:
                project.anyone_submit = False

            # Check if cla form exists before sending the signal
            if 'limited_access' == access_control and \
            form.cleaned_data.has_key('cla_license_text'):
                # send signal to save CLA
                signals.cla_create.send(
                    sender='project_access_control_edit_view',
                    project=project,
                    license_text=form.cleaned_data['cla_license_text'],
                    request=request
                )

            project.save()
            form.save_m2m()
            handle_stats_on_access_control_edit(project)
            project_outsourced_changed.send(sender=project_hub)

            if outsourced and not project.outsource:
                # Drop resources from all-resources release of the hub project
                update_all_release(outsourced)

                # Logging action
                nt = 'project_hub_left'
                context = {'project': project, 'project_hub': outsourced,
                           'sender': request.user}
                action_logging(request.user, [project, outsourced], nt, context=context)

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

    else:
        form = ProjectAccessControlForm(instance=project, user=request.user)

    return render_to_response('projects/project_form_access_control.html', {
        'project_permission': True,
        'project': project,
        'form': form,
    }, context_instance=RequestContext(request))

Example 93

Project: Arkestra Source File: views.py
Function: place
def place(request, slug, active_tab=""):
    """
    Receives active_tab from the slug.

    The template receives "_" + active_tab to identify the correct template
    (from includes).
    """
    place = get_object_or_404(Building, slug=slug)
    # information for each kind of place page
    tabs_dict = {
        "about": {
            "tab": "about",
            "title": "About",
            "address": "",
            "meta_description_content": place.summary,
        },
        "map": {
            "tab": "map",
            "title": "Map",
            "address": "map",
            "meta_description_content": "Map for " + place.__unicode__(),
        },
        "getting-here": {
            "tab": "getting-here",
            "title": "Getting here",
            "address": "getting-here",
            "meta_description_content": "How to get to " + place.__unicode__(),
        },
        "events": {
            "tab": "events",
            "title": "What's on here",
            "address": "events",
            "meta_description_content": "What's on at " + place.__unicode__(),
        },
    }

    if active_tab and not active_tab in tabs_dict:
        raise Http404

    # mark the active tab, if there is one
    if active_tab in tabs_dict:
        tabs_dict[active_tab]["active"] = True

    # add tabs to the list of tabs
    tabs = [tabs_dict["about"]]
    if place.has_map():
        tabs.append(tabs_dict["map"])
    if (
        place.getting_here and place.getting_here.cmsplugin_set.all()
        ) or (
        place.access_and_parking and
        place.access_and_parking.cmsplugin_set.all()
    ):
        tabs.append(tabs_dict["getting-here"])
    if place.events.lists:
        tabs.append(tabs_dict["events"])

    if not active_tab:
        # find out what to add to the url for this tab
        active_tab = tabs[0]["address"]
        # mark the tab as active for the template
        tabs[0]["active"] = True
    # fewer than 2? not worth having tabs!
    if len(tabs) == 1:
        tabs = []

    meta_description_content = tabs_dict[
        active_tab or "about"
        ]["meta_description_content"]

    if active_tab:
        active_tab = "_" + active_tab

    meta = {"description": meta_description_content}
    page = Entity.objects.base_entity().get_website
    # request.current_page = page
    template = page.get_template()

    return render_to_response(
        "contacts_and_people/place%s.html" % active_tab,
        {
            "place": place,
            "tabs": tabs,
            "tab_object": place,
            "active_tab": active_tab,
            "template": template,
            "meta": meta,
        },
        RequestContext(request),
    )

Example 94

Project: 1flow Source File: __init__.py
def edit_field(request, klass, oid, form_class):
    """ Edit any object field, with minimal permissions checking, via Ajax.

    For permission to succeed, request.user must be staff or the owner
    of the object.

    The form class can define an optional ``redirect_url`` attribute. This
    attribute will be used after form save (when valid) to redirect the user
    instead of just displaying him/her a notification and staying on the
    current page.
    """

    if not request.is_ajax():
        return HttpResponseBadRequest('This request needs Ajax')

    try:
        obj_class = globals()[klass]

    except KeyError:
        LOGGER.exception(u'KeyError on “%s” in edit! Model not imported?',
                         klass)
        return HttpResponseTemporaryServerError()

    if 'history_id' in (x.name for x in obj_class._meta.fields):
        obj = get_object_or_404(obj_class, history_id=oid)

    else:
        obj = get_object_or_404(obj_class, id=oid)

    try:
        if obj.user != request.user \
                and not request.user.is_staff_or_superuser_and_enabled:
            return HttpResponseForbidden(u'Not owner nor superuser/staff')

    except AttributeError:
        if not request.user.is_staff_or_superuser_and_enabled:
            return HttpResponseForbidden(
                u'Not superuser/staff and no owner/creator field on instance')
    try:
        instance_name = obj.name

    except:
        instance_name = unicode(obj)

    form_klass = getattr(forms, form_class)

    if request.POST:
        form_get_args = request.GET.copy()

        if bool(form_get_args):
            form = form_klass(request.POST, instance=obj,
                              form_get_args=form_get_args)

        else:
            form = form_klass(request.POST, instance=obj)

        redirect_url = None

        if form.is_valid():
            obj = form.save(request.user)

            try:
                redirect_url = form.redirect_url

            except AttributeError:
                # The form didn't set it, this is a supported behavior.
                # Just do as usual and simply render the JS template.
                pass

        return render(request,
                      'snippets/edit_field/result.html',
                      {
                          'instance_name': instance_name,
                          'form': form,
                          'obj': obj,
                          'field_name': [f for f in form][0].name,
                          'form_class': form_class,
                          'klass': klass,
                          'redirect_url': redirect_url,
                      })

    else:
        form_get_args = request.GET.copy()

        if bool(form_get_args):
            form = form_klass(instance=obj, form_get_args=form_get_args)

        else:
            form = form_klass(instance=obj)

    return render(request,
                  'snippets/edit_field/modal.html',
                  {
                      'instance_name': instance_name,
                      'form': form,
                      'obj': obj,
                      'field_name': [f for f in form][0].name,
                      'form_class': form_class,
                      'klass': klass,
                  })

Example 95

Project: zorna Source File: views.py
def create_calendar_event(request):
    start = request.GET.get('start', None)
    end = request.GET.get('end', None)
    title = request.GET.get('title', None)

    initial_data = {}
    if title:
        initial_data['title'] = title

    if start:
        try:
            start = datetime.datetime.fromtimestamp(float(start))
            initial_data['start'] = start
            if end:
                initial_data[
                    'end'] = datetime.datetime.fromtimestamp(float(end))
            else:
                initial_data['end'] = start + datetime.timedelta(minutes=30)
        except TypeError:
            raise Http404
        except ValueError:
            raise Http404

    calendars = get_user_calendars(request.user, ['manager', 'creator'])
    if not calendars:
        return HttpResponseRedirect(reverse('view_calendar', args=[]))

    if request.method == 'POST':
        form = EditEventForm(data=request.POST)
        form_details = EditEventDetailsForm(data=request.POST)
        calendar_id = request.POST.get('calendar_id', None)
        if calendar_id and form.is_valid():
            calendar = get_object_or_404(ZornaCalendar, pk=calendar_id)
            if not calendar.pk in [c.pk for c in calendars]:
                # TODO Display warning message
                return HttpResponseRedirect(reverse('view_calendar', args=[]))
            event = form.save(commit=False)
            event.creator = request.user
            event.calendar = calendar.calendar
            if 'end_recurring_period' in form.cleaned_data and form.cleaned_data['end_recurring_period']:
                event.end_recurring_period = event.end_recurring_period + \
                    datetime.timedelta(days=1, seconds= -1)

            if request.POST['rule'] != '':
                params = "interval:" + request.POST['interval']
                if request.POST['rule'] == 'WEEKLY':
                    weekdays = request.POST.getlist('weekdays')
                    if not weekdays:
                        weekdays = [str((int(
                            event.start.strftime('%w')) + 6) % 7)]
                    params += ";byweekday:" + ",".join(weekdays)
                rule = Rule(name=request.POST['rule'],
                            frequency=request.POST['rule'],
                            params=params
                            )
                rule.save()
                event.rule = rule

            event.save()
            evtd = form_details.save(commit=False)
            evtd.ct = ContentType.objects.get_for_model(type(event))
            evtd.object_id = event.pk
            evtd.content_object = event
            evtd.save()
            return HttpResponseRedirect(reverse('view_calendar', args=[]))
        else:
            form = EditEventForm(data=request.POST)
            form_details = EditEventDetailsForm(data=request.POST)
    else:
        form = EditEventForm(initial=initial_data)
        form_details = EditEventDetailsForm()

    extra_context = {
        'form': form,
        'boccurrence': False,
        'event': None,
        'form_details': form_details,
        'calendars': calendars,
        'calendar': get_personal_calendar(request.user),
    }

    context = RequestContext(request)
    return render_to_response('calendars/calendar_edit.html', extra_context, context_instance=context)

Example 96

Project: transifex Source File: views.py
@login_required
def push_translation(request, project_slug, lang_code, *args, **kwargs):
    """
    Client pushes an id and a translation string.

    Id is considered to be of the source translation string and the string is
    in the target_lang.

    FIXME: Docuement in detail the form of the 'strings' POST variable.
    """

    logger.debug("POST data when saving translation: %s" % request.POST)
    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    if not request.POST:
        return HttpResponseBadRequest()

    data = simplejson.loads(request.raw_post_data)
    strings = data["strings"]

    try:
        target_language = Language.objects.by_code_or_alias(lang_code)
    except Language.DoesNotExist:
        raise Http404

    # This dictionary will hold the results of the save operation and will map
    # status code for each translation pushed, to indicate the result on each
    # translation push separately.
    push_response_dict = {}

    # Form the strings dictionary, get as Json object
    # The fields are the following:
    # id-> source_entity id
    # translations-> translation strings (includes all plurals)
    # context-> source_entity context
    # occurrence-> occurrence (not yet well supported)
    # Iterate through all the row data that have been sent.
    for row in strings:
        source_id = int(row['id'])
        try:
            source_string = Translation.objects.select_related(depth=1).get(
                id=source_id
            )
        except Translation.DoesNotExist:
            # TODO: Log or inform here
            push_response_dict[source_id] = { 'status':400,
                 'message':_("Source string cannot be identified in the DB")}
            # If the source_string cannot be identified in the DB then go to next
            # translation pair.
            continue

        if not source_string.resource.accept_translations:
            push_response_dict[source_id] = { 'status':400,
                 'message':_("The resource of this source string is not "
                    "accepting translations.") }

        # If the translated source string is pluralized check that all the
        # source language supported rules have been filled in, else return error
        # and donot save the translations.
        if source_string.source_entity.pluralized:
            error_flag = False
            for rule in target_language.get_pluralrules():
                if rule in row['translations'] and row['translations'][rule] != "":
                    continue
                else:
                    error_flag = True
            if error_flag:
                error_flag = False
                # Check also if all of them are "". If yes, delete all the plurals!
                for rule in target_language.get_pluralrules():
                    if rule in row['translations'] and row['translations'][rule] == "":
                        continue
                    else:
                        error_flag = True
            if error_flag:
                push_response_dict[source_id] = { 'status':400,
                    'message':(_("Cannot save unless plural translations are either "
                               "completely specified or entirely empty!"))}
                # Skip the save as we hit on an error.
                continue
        try:
            msgs = _save_translation(
                source_string, row['translations'],
                target_language, request.user
            )
            if not msgs:
                push_response_dict[source_id] = {'status': 200}
            else:
                push_response_dict[source_id] = {
                    'status': 200, 'message': msgs[-1]
                }
        except LotteBadRequestError, e:
            push_response_dict[source_id] = {
                'status': 400, 'message': e.message
            }
        except Exception, e:
            logger.error(
                "Unexpected exception raised: %s" % e.message, exc_info=True
            )
            push_response_dict[source_id] = {
                'status': 400, 'message': e.message
            }

    json_dict = simplejson.dumps(push_response_dict)
    return HttpResponse(json_dict, mimetype='application/json')

Example 97

Project: pootle Source File: decorators.py
def get_path_obj(func):
    @wraps(func)
    def wrapped(request, *args, **kwargs):
        if request.is_ajax():
            pootle_path = request.GET.get('path', None)
            if pootle_path is None:
                raise Http400(_('Arguments missing.'))

            language_code, project_code, dir_path, filename = \
                split_pootle_path(pootle_path)
            kwargs['dir_path'] = dir_path
            kwargs['filename'] = filename

            # Remove potentially present but unwanted args
            try:
                del kwargs['language_code']
                del kwargs['project_code']
            except KeyError:
                pass
        else:
            language_code = kwargs.pop('language_code', None)
            project_code = kwargs.pop('project_code', None)

        if language_code and project_code:
            try:
                path_obj = TranslationProject.objects.get_for_user(
                    user=request.user,
                    language_code=language_code,
                    project_code=project_code,
                )
            except TranslationProject.DoesNotExist:
                path_obj = None

            if path_obj is None:
                if not request.is_ajax():
                    # Explicit selection via the UI: redirect either to
                    # ``/language_code/`` or ``/projects/project_code/``
                    user_choice = request.COOKIES.get('user-choice', None)
                    if user_choice and user_choice in ('language', 'project',):
                        url = {
                            'language': reverse('pootle-language-browse',
                                                args=[language_code]),
                            'project': reverse('pootle-project-browse',
                                               args=[project_code, '', '']),
                        }
                        response = redirect(url[user_choice])
                        response.delete_cookie('user-choice')

                        return response

                raise Http404
        elif language_code:
            user_projects = Project.accessible_by_user(request.user)
            language = get_object_or_404(Language, code=language_code)
            children = language.children \
                               .filter(project__code__in=user_projects)
            language.set_children(children)
            path_obj = language
        elif project_code:
            try:
                path_obj = Project.objects.get_for_user(project_code,
                                                        request.user)
            except Project.DoesNotExist:
                raise Http404
        else:  # No arguments: all user-accessible projects
            user_projects = Project.objects.for_user(request.user)
            path_obj = ProjectSet(user_projects)

        request.ctx_obj = path_obj
        request.ctx_path = path_obj.pootle_path
        request.resource_obj = path_obj
        request.pootle_path = path_obj.pootle_path

        return func(request, path_obj, *args, **kwargs)

    return wrapped

Example 98

Project: foodnetwork Source File: views.py
@login_required
def planning_table(request, member_id, list_type, from_date, to_date):
    member = get_object_or_404(Party, pk=member_id)
    role = "producer"
    plan_type = "Production"
    if member.is_customer():
        role = "consumer"
        plan_type = "Consumption"

    try:
        from_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date()
        to_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date()
    except ValueError:
            raise Http404
    # force from_date to Monday, to_date to Sunday
    from_date = from_date - datetime.timedelta(days=datetime.date.weekday(from_date))
    to_date = to_date - datetime.timedelta(days=datetime.date.weekday(to_date)+1)
    to_date = to_date + datetime.timedelta(days=7)
    products = None
    if list_type == "M":
        if role == "consumer":
            products = CustomerProduct.objects.filter(customer=member, planned=True)
        else:
            products = ProducerProduct.objects.filter(producer=member, planned=True)
    if not products:
        products = Product.objects.filter(plannable=True)
        list_type = "A"
    plan_table = plan_weeks(member, products, from_date, to_date)
    forms = create_weekly_plan_forms(plan_table.rows, data=request.POST or None)
    if request.method == "POST":
        #import pdb; pdb.set_trace()
        for row in forms:
            if row.formset.is_valid():
                for form in row.formset.forms:
                    data = form.cleaned_data
                    qty = data['quantity']
                    plan_id = data['plan_id']
                    from_dt = data['from_date']
                    to_dt = data['to_date']
                    product_id = data['product_id']
                    plan = None
                    if plan_id:
                        # what if plan was changed by prev cell?
                        plan = ProductPlan.objects.get(id=plan_id)
                        if plan.to_date < from_dt or plan.from_date > to_dt:
                            plan = None
                    if qty:
                        if plan:
                            #import pdb; pdb.set_trace()
                            if not qty == plan.quantity:
                                #import pdb; pdb.set_trace()
                                if plan.from_date >= from_dt and plan.to_date <= to_dt:
                                    plan.quantity = qty
                                    plan.save()
                                else:
                                    if plan.from_date < from_dt:
                                        new_to_dt = from_dt - datetime.timedelta(days=1)
                                        earlier_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=plan.quantity,
                                            from_date=plan.from_date,
                                            to_date=new_to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                        )
                                        earlier_plan.save()
                                    if plan.to_date > to_dt:
                                        new_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=qty,
                                            from_date=from_dt,
                                            to_date=to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                        )
                                        new_plan.save()
                                        plan.from_date = to_dt + datetime.timedelta(days=1)
                                        plan.save()
                                    else:
                                        plan.from_date=from_dt
                                        plan.quantity=qty
                                        plan.save()      
                        else:
                            product = Product.objects.get(id=product_id)
                            new_plan = ProductPlan(
                                member=member,
                                product=product,
                                quantity=qty,
                                from_date=from_dt,
                                to_date=to_dt,
                                role=role,
                                #inventoried=True,
                                #distributor,
                            )
                            new_plan.save()
                            #import pdb; pdb.set_trace()
                            if role == "producer":
                                listed_product, created = ProducerProduct.objects.get_or_create(
                                    product=product, producer=member)
                            #elif role == "consumer":
                                #todo: shd these be auto-created at all?
                                # and if so, what MemberProductList?
                            #    listed_product, created = CustomerProduct.objects.get_or_create(
                            #        product=product, customer=member)

                    else:
                        if plan:
                            if plan.from_date >= from_dt and plan.to_date <= to_dt:
                                #pass
                                plan.delete()
                            else:
                                #import pdb; pdb.set_trace()
                                if plan.to_date > to_dt:
                                    early_from_dt = plan.from_date              
                                    if plan.from_date < from_dt:
                                        early_to_dt = from_dt - datetime.timedelta(days=1)
                                        earlier_plan = ProductPlan(
                                            member=plan.member,
                                            product=plan.product,
                                            quantity=plan.quantity,
                                            from_date=early_from_dt,
                                            to_date=early_to_dt,
                                            role=plan.role,
                                            inventoried=plan.inventoried,
                                            distributor=plan.distributor,
                                         )
                                        earlier_plan.save()
                                    plan.from_date = to_dt + datetime.timedelta(days=1)
                                    plan.save()
                                else:
                                    plan.to_date= from_dt - datetime.timedelta(days=1)
                                    plan.save()
        from_date = from_date.strftime('%Y_%m_%d')
        to_date = to_date.strftime('%Y_%m_%d')
        return HttpResponseRedirect('/%s/%s/%s/%s/'
                    % ('customer/customerplans', from_date, to_date, member_id))
    return render_to_response('distribution/planning_table.html', 
        {
            'from_date': from_date,
            'to_date': to_date,
            'plan_table': plan_table,
            'forms': forms,
            'plan_type': plan_type,
            'member': member,
            'list_type': list_type,
            'tabnav': "customer/customer_tabnav.html",
        }, context_instance=RequestContext(request))

Example 99

Project: django-simple-import Source File: views.py
@staff_member_required
def match_columns(request, import_log_id):
    """ View to match import spreadsheet columns with database fields
    """
    import_log = get_object_or_404(ImportLog, id=import_log_id)

    if not request.user.is_superuser and import_log.user != request.user:
        raise SuspiciousOperation("Non superuser attempting to view other users import")

    # need to generate matches if they don't exist already
    existing_matches = import_log.get_matches()

    MatchFormSet = inlineformset_factory(ImportSetting, ColumnMatch, form=MatchForm, extra=0)

    import_data = import_log.get_import_file_as_list()
    header_row = [x.lower() for x in import_data[0]] # make all lower
    try:
        sample_row = import_data[1]
    except IndexError:
        messages.error(request, 'Error: Spreadsheet was empty.')
        return redirect('simple_import-start_import')

    errors = []

    model_class = import_log.import_setting.content_type.model_class()
    field_names = get_all_field_names(model_class)
    for field_name in field_names:
        field_object = model_class._meta.get_field(field_name)
        # We can't add a new AutoField and specify it's value
        if import_log.import_type == "N" and isinstance(field_object, AutoField):
            field_names.remove(field_name)

    if request.method == 'POST':
        formset = MatchFormSet(request.POST, instance=import_log.import_setting)
        if formset.is_valid():
            formset.save()
            if import_log.import_type in ["U", "O"]:
                update_key = request.POST.get('update_key', '')

                if update_key:
                    field_name = import_log.import_setting.columnmatch_set.get(column_name=update_key).field_name
                    if field_name:
                        field_object = model_class._meta.get_field(field_name)
                        direct = field_object.concrete

                        if direct and field_object.unique:
                            import_log.update_key = update_key
                            import_log.save()
                        else:
                            errors += ['Update key must be unique. Please select a unique field.']
                    else:
                        errors += ['Update key must matched with a column.']
                else:
                    errors += ['Please select an update key. This key is used to linked records for updating.']
            errors += validate_match_columns(
                import_log,
                model_class,
                header_row)

            all_field_names = []
            for clean_data in formset.cleaned_data:
                if clean_data['field_name']:
                    if clean_data['field_name'] in all_field_names:
                        errors += ["{0} is duplicated.".format(clean_data['field_name'])]
                    all_field_names += [clean_data['field_name']]
            if not errors:
                return HttpResponseRedirect(reverse(
                    match_relations,
                    kwargs={'import_log_id': import_log.id}))
    else:
        formset = MatchFormSet(instance=import_log.import_setting, queryset=existing_matches)

    field_choices = (('', 'Do Not Use'),)
    for field_name in field_names:
        field_object = model_class._meta.get_field(field_name)
        direct = field_object.concrete
        m2m = field_object.many_to_many
        add = True

        if direct:
            field_verbose = field_object.verbose_name
        else:
            field_verbose = field_name

        if direct and not field_object.blank:
            field_verbose += " (Required)"
        if direct and field_object.unique:
            field_verbose += " (Unique)"
        if m2m or isinstance(field_object, ForeignKey):
            field_verbose += " (Related)"
        elif not direct:
            add = False
        if is_foreign_key_id_name(field_name, field_object):
            add = False

        if add:
            field_choices += ((field_name, field_verbose),)

    # Include defined methods
    # Model must have a simple_import_methods defined
    if hasattr(model_class, 'simple_import_methods'):
        for import_method in model_class.simple_import_methods:
            field_choices += (("simple_import_method__{0}".format(import_method),
                               "{0} (Method)".format(import_method)),)
    # User model should allow set password
    if issubclass(model_class, User):
        field_choices += (("simple_import_method__{0}".format('set_password'),
                               "Set Password (Method)"),)

    for i, form in enumerate(formset):
        form.fields['field_name'].widget = forms.Select(choices=(field_choices))
        form.sample = sample_row[i]

    return render(
        request,
        'simple_import/match_columns.html',
        {'import_log': import_log, 'formset': formset, 'errors': errors},
    )

Example 100

Project: django-lfs Source File: properties.py
@permission_required("core.manage_shop")
def manage_properties(request, product_id, template_name="manage/product/properties.html"):
    """Displays the UI for manage the properties for the product with passed
    product_id.
    """
    product = get_object_or_404(Product, pk=product_id)

    # Generate lists of properties. For entering values.
    display_configurables = False
    display_filterables = False
    display_displayables = False
    configurables = []
    filterables = []
    displayables = []
    product_variant_properties = []

    # Configurable
    if not product.is_product_with_variants():
        for property_group in product.property_groups.all():
            properties = []
            for prop in property_group.properties.filter(configurable=True).order_by("groupspropertiesrelation"):
                display_configurables = True

                try:
                    ppv = ProductPropertyValue.objects.get(property=prop,
                                                           property_group=property_group,
                                                           product=product,
                                                           type=PROPERTY_VALUE_TYPE_DEFAULT)
                except ProductPropertyValue.DoesNotExist:
                    ppv_id = None
                    ppv_value = ""
                else:
                    ppv_id = ppv.id
                    ppv_value = ppv.value

                # Mark selected options
                options = []
                for option in prop.options.all():
                    if str(option.id) == ppv_value:
                        selected = True
                    else:
                        selected = False

                    options.append({
                        "id": option.id,
                        "name": option.name,
                        "selected": selected,
                    })

                properties.append({
                    "id": prop.id,
                    "name": prop.name,
                    "title": prop.title,
                    "type": prop.type,
                    "options": options,
                    "display_number_field": prop.type == PROPERTY_NUMBER_FIELD,
                    "display_text_field": prop.type == PROPERTY_TEXT_FIELD,
                    "display_select_field": prop.type == PROPERTY_SELECT_FIELD,
                    "value": ppv_value,
                })

            if properties:
                configurables.append({
                    "id": property_group.id,
                    "name": property_group.name,
                    "properties": properties,
                })

        # Filterable
        for property_group in product.property_groups.all():
            properties = []
            for prop in property_group.properties.filter(filterable=True).order_by("groupspropertiesrelation"):

                display_filterables = True

                # Try to get the value, if it already exists.
                ppvs = ProductPropertyValue.objects.filter(property=prop,
                                                           property_group=property_group,
                                                           product=product,
                                                           type=PROPERTY_VALUE_TYPE_FILTER)
                value_ids = [ppv.value for ppv in ppvs]

                # Mark selected options
                options = []
                for option in prop.options.all():

                    if str(option.id) in value_ids:
                        selected = True
                    else:
                        selected = False

                    options.append({
                        "id": option.id,
                        "name": option.name,
                        "selected": selected,
                    })

                value = ""
                if prop.type == PROPERTY_SELECT_FIELD:
                    display_select_field = True
                else:
                    display_select_field = False
                    try:
                        value = value_ids[0]
                    except IndexError:
                        pass

                properties.append({
                    "id": prop.id,
                    "name": prop.name,
                    "title": prop.title,
                    "type": prop.type,
                    "options": options,
                    "value": value,
                    "display_on_product": prop.display_on_product,
                    "display_number_field": prop.type == PROPERTY_NUMBER_FIELD,
                    "display_text_field": prop.type == PROPERTY_TEXT_FIELD,
                    "display_select_field": display_select_field,
                })
            if properties:
                filterables.append({
                    "id": property_group.id,
                    "name": property_group.name,
                    "properties": properties,
                })

        # Displayable
        for property_group in product.property_groups.all():
            properties = []
            for prop in property_group.properties.filter(display_on_product=True).order_by("groupspropertiesrelation"):

                display_displayables = True

                # Try to get the value, if it already exists.
                ppvs = ProductPropertyValue.objects.filter(property=prop,
                                                           property_group=property_group,
                                                           product=product,
                                                           type=PROPERTY_VALUE_TYPE_DISPLAY)
                value_ids = [ppv.value for ppv in ppvs]

                # Mark selected options
                options = []
                for option in prop.options.all():

                    if str(option.id) in value_ids:
                        selected = True
                    else:
                        selected = False

                    options.append({
                        "id": option.id,
                        "name": option.name,
                        "selected": selected,
                    })

                value = ""
                if prop.type == PROPERTY_SELECT_FIELD:
                    display_select_field = True
                else:
                    display_select_field = False
                    try:
                        value = value_ids[0]
                    except IndexError:
                        pass

                properties.append({
                    "id": prop.id,
                    "name": prop.name,
                    "title": prop.title,
                    "type": prop.type,
                    "options": options,
                    "value": value,
                    "filterable": prop.filterable,
                    "display_number_field": prop.type == PROPERTY_NUMBER_FIELD,
                    "display_text_field": prop.type == PROPERTY_TEXT_FIELD,
                    "display_select_field": display_select_field,
                })

            if properties:
                displayables.append({
                    "id": property_group.id,
                    "name": property_group.name,
                    "properties": properties,
                })

    if product.is_variant():
        product_variant_properties_dict = {}
        qs = ProductPropertyValue.objects.filter(product=product, type=PROPERTY_VALUE_TYPE_VARIANT)
        for ppv in qs:
            try:
                property_option = PropertyOption.objects.get(property_id=ppv.property_id, pk=ppv.value)
                property_group_name = ppv.property_group.name if ppv.property_group_id else ''
                group_dict = product_variant_properties_dict.setdefault(ppv.property_group_id or 0,
                                                                       {'property_group_name': property_group_name,
                                                                        'properties': []})
                group_dict['properties'].append(property_option)
            except (ProductPropertyValue.DoesNotExist, PropertyOption.DoesNotExist):
                continue

        groups = product_variant_properties_dict.values()
        sorted_groups = sorted(groups, key=lambda group: group['property_group_name'])
        for group in sorted_groups:
            product_variant_properties.append(group)

    # Generate list of all property groups; used for group selection
    product_property_group_ids = [p.id for p in product.property_groups.all()]
    shop_property_groups = []
    for property_group in PropertyGroup.objects.all():

        shop_property_groups.append({
            "id": property_group.id,
            "name": property_group.name,
            "selected": property_group.id in product_property_group_ids,
        })

    return render_to_string(template_name, RequestContext(request, {
        "product": product,
        "filterables": filterables,
        "display_filterables": display_filterables,
        "configurables": configurables,
        "display_configurables": display_configurables,
        "displayables": displayables,
        "display_displayables": display_displayables,
        "product_property_groups": product.property_groups.all(),
        "shop_property_groups": shop_property_groups,
        "product_variant_properties": product_variant_properties
    }))
See More Examples - Go to Next Page
Page 1 Page 2 Selected Page 3 Page 4