Example #1
1
def reservations(request):
    message = request.session.pop("message", None)
    message_type = request.session.pop("message_type", None)
    current_user = request.user
    m_user = get_object_or_404(ExtendedUser, main_user=current_user)
    try:
        a_user = get_object_or_404(AdminUser, extended_user=m_user)
        admin_user = True
    except:
        admin_user = False
    now = datetime.datetime.now()
    outgoing_requests = ResMessage.objects.filter(message__sender=current_user, res_date__gte=now).order_by("res_date")
    incoming_requests = ResMessage.objects.filter(message__receiver=current_user, has_responded=False).order_by(
        "res_date"
    )
    history = ResMessage.objects.filter(message__sender=current_user, res_date__lte=now, is_approved=True).order_by(
        "res_date"
    )
    return render(
        request,
        "reservations.html",
        {
            "admin_user": admin_user,
            "incoming_requests": incoming_requests,
            "message": message,
            "message_type": message_type,
            "outgoing_requests": outgoing_requests,
            "history": history,
        },
    )
Example #2
1
def survey_update(
    request,
    survey_slug,
    group_slug=None,
    group_slug_field=None,
    group_qs=None,
    template_name="survey/survey_add.html",
    extra_context=None,
    *args,
    **kw
):
    if request.method == "POST":
        request_post = request.POST.copy()
        survey = get_object_or_404(Survey, slug=survey_slug)
        survey_form = SurveyForm(instance=survey, data=request_post)
        if survey_form.is_valid():
            new_survey = survey_form.save(commit=False)
            new_survey.created_by = request.user
            new_survey.editable_by = request.user
            new_survey.slug = slugify(new_survey.title)
            new_survey.save()
            return HttpResponseRedirect(reverse("survey-edit", None, (), {"survey_slug": survey_slug}))

    else:
        survey = get_object_or_404(Survey, slug=survey_slug)
        survey_form = SurveyForm(instance=survey)
    return render_to_response(
        template_name,
        {"title": _("Update '%s'") % survey.title, "survey": survey, "form": survey_form},
        context_instance=RequestContext(request),
    )
Example #3
1
def choice_update(
    request,
    question_id,
    choice_id,
    group_slug=None,
    group_slug_field=None,
    group_qs=None,
    template_name="survey/choice_add.html",
    extra_context=None,
    *args,
    **kw
):
    question = get_object_or_404(Question, id=question_id)
    choice = get_object_or_404(Choice, id=choice_id)
    if choice not in question.choices.iterator():
        raise Http404()
    if request.method == "POST":
        request_post = request.POST.copy()
        choice_form = ChoiceForm(instance=choice, data=request_post, files=request.FILES)
        if choice_form.is_valid():
            new_choice = choice_form.save(commit=False)
            new_choice.question = question
            new_choice.save()
            return HttpResponseRedirect(reverse("survey-edit", None, (), {"survey_slug": question.survey.slug}))
    else:
        choice_form = ChoiceForm(instance=choice)
    return render_to_response(
        template_name,
        {"title": _("Update choice"), "choice": choice, "model_string": "Choice", "form": choice_form},
        context_instance=RequestContext(request),
    )
Example #4
1
    def sync(self, request, pk=None):
        """
        :returns
            {
                "date": "Y-m-d H:M:s",
                "user": {
                    "id": x,
                    "name": "xxx",
                    "fullname": "xxxxx"
                },
                "attributes": [
                    {
                        "id": x,
                        "value": "xxx",
                        "description": "xxxxx",
                        "total_computers"; xx,
                        "property_att": {
                            "id": x,
                            "prefix": "xxx"
                        }
                    },
                    ...
                ]
            }
        """
        computer = get_object_or_404(models.Computer, pk=pk)
        sync_data = get_object_or_404(models.Login, computer__id=computer.id)
        serializer = serializers.ComputerSyncSerializer(sync_data)

        return Response(serializer.data, status=status.HTTP_200_OK)
Example #5
1
def create(request, to=None, reply_to=None):
    if to is not None:
        to = get_object_or_404(Player, pk=to)
    if reply_to is not None:
        reply_to = get_object_or_404(Message, pk=reply_to)
        subject = "Re: " + reply_to.subject if not reply_to.subject.startswith("Re: ") else reply_to.subject
    else:
        subject = ""

    error = ""
    if request.method == "POST":
        form = ComposeForm(request.POST)
        if form.is_valid():
            m = Message.send(
                request.user.get_profile(),
                form.cleaned_data["to"],
                form.cleaned_data["subject"],
                form.cleaned_data["text"],
                reply_to=reply_to.id if reply_to else None,
            )
            if m is None:
                return HttpResponseRedirect(reverse("messaging"))
            else:
                error = m
        # else:
        #   print form, form.is_valid(), request.POST
    return render_to_response(
        "messaging/create.html",
        {"error": error, "to": to, "reply_to": reply_to, "subject": subject},
        context_instance=RequestContext(request),
    )
Example #6
1
def api_variant(request, slug, version_slug, variant_slug):
    package = get_object_or_404(Package, slug=slug)
    if version_slug is None:
        version = package.latest_version
        version_slug = "latest"
    else:
        version = get_object_or_404(Version, package=package, slug=version_slug)
    variant = get_object_or_404(Variant, version=version, slug=variant_slug)
    return {
        "slug": variant.slug,
        "name": variant.name,
        "version": variant.version.slug,
        "usefile": urlresolvers.reverse(
            "nirvana.pkg.views.usefile",
            kwargs={"slug": slug, "version_slug": version_slug, "variant_slug": variant.slug, "usefile": slug},
        ),
        "checksums": urlresolvers.reverse(
            "nirvana.pkg.views.checksums",
            kwargs={"slug": slug, "version_slug": version_slug, "variant_slug": variant.slug, "checksums": slug},
        ),
        "checksums_signature": urlresolvers.reverse(
            "nirvana.pkg.views.checksums_signature",
            kwargs={
                "slug": slug,
                "version_slug": version_slug,
                "variant_slug": variant.slug,
                "checksums_signature": slug,
            },
        ),
    }
Example #7
0
def groupmembership_delete(request, group_slug, user_id, template_name="user_groups/member_delete.html"):
    group = get_object_or_404(Group, slug=group_slug)
    user = get_object_or_404(User, pk=user_id)
    group_membership = get_object_or_404(GroupMembership, group=group, member=user)
    if not has_perm(request.user, "user_groups.delete_groupmembership", group_membership):
        raise Http403

    if request.method == "POST":
        log_defaults = {
            "event_id": 223000,
            "event_data": "%s (%d) deleted by %s"
            % (group_membership._meta.object_name, group_membership.pk, request.user),
            "description": "%s deleted" % group_membership._meta.object_name,
            "user": request.user,
            "request": request,
            "instance": group_membership,
        }
        EventLog.objects.log(**log_defaults)
        group_membership.delete()
        messages.add_message(
            request, messages.SUCCESS, "Successfully removed %s from group %s" % (user.get_full_name(), group)
        )
        return HttpResponseRedirect(group.get_absolute_url())

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Example #8
0
def issue_close(request, id):
    if not request.user.is_superuser:
        issue = get_object_or_404(
            Issue, pk=id, owner=request.user, category__in=[ISSUE_CATEGORY_BUG, ISSUE_CATEGORY_FEATURE]
        )
    else:
        issue = get_object_or_404(Issue, pk=id, category__in=[ISSUE_CATEGORY_BUG, ISSUE_CATEGORY_FEATURE])

    if request.method == "POST":
        commentForm = CommentForm(request.POST)
        if commentForm.is_valid():
            comment = commentForm.save(commit=False)
            comment.update_date = datetime.datetime.now()
            comment.issue = issue
            comment.owner = request.user
            comment.save()
            issue.state = ISSUE_STATE_CLOSED
            issue.save()
            Vote.objects.filter(issue=issue).delete()
            messages.success(request, _("The issue has been closed successfully"))
            return redirect(reverse("issue_list"))
    else:
        commentForm = CommentForm()

    return render_to_response(
        "comment/edit.html",
        {"active": "settings", "title": _("Close an issue"), "form": commentForm},
        context_instance=RequestContext(request),
    )
Example #9
0
def issue_reopen(request, id):
    if not request.user.is_superuser:
        issue = get_object_or_404(
            Issue, pk=id, owner=request.user, category__in=[ISSUE_CATEGORY_BUG, ISSUE_CATEGORY_FEATURE]
        )
    else:
        issue = get_object_or_404(Issue, pk=id, category__in=[ISSUE_CATEGORY_BUG, ISSUE_CATEGORY_FEATURE])

    if request.method == "POST":
        commentForm = CommentForm(request.POST)
        if commentForm.is_valid():
            comment = commentForm.save(commit=False)
            comment.update_date = datetime.datetime.now()
            comment.issue = issue
            comment.owner = request.user
            comment.save()
            issue.state = ISSUE_STATE_OPEN
            issue.save()
            domain = Site.objects.get_current().domain
            mail_subject = _("An issue has been reopened")
            mail_message = _("%(issue_subject)s : %(issue_url)s") % {
                "issue_subject": issue.subject,
                "issue_url": "https://%s%s" % (domain, reverse("issue_detail", kwargs={"id": issue.id})),
            }
            mail_admins(mail_subject, mail_message, fail_silently=(not settings.DEBUG))
            messages.success(request, _("The issue has been reopened successfully"))
            return redirect(reverse("issue_list"))
    else:
        commentForm = CommentForm()

    return render_to_response(
        "comment/edit.html",
        {"active": "settings", "title": _("Reopen an issue"), "form": commentForm},
        context_instance=RequestContext(request),
    )
Example #10
0
def edit_eptitude_for_book_card(
    request, card_id, eptitude_id, book_id, eptitude_form=EptitudeForm, template_name="card/edit_eptitude.html"
):

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

    eptitude = get_object_or_404(CardEptitude, pk=eptitude_id)

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

    else:

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

    current_site = get_current_site(request)

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

    return TemplateResponse(request, template_name, context)
Example #11
0
 def get_object(self, request, *args, **kwargs):
     user_id = kwargs.get("user")
     try:
         self.user = UserProfile.objects.get(mnemonic=user_id)
     except UserProfile.DoesNotExist:
         pass
     org_id = kwargs.get("org")
     try:
         self.org = Organization.objects.get(mnemonic=org_id)
     except Organization.DoesNotExist:
         pass
     if not (self.user or self.org):
         raise Http404("Source owner does not exist")
     source_id = kwargs.get("source")
     if self.user:
         self.source = get_object_or_404(
             Source,
             mnemonic=source_id,
             parent_id=self.user.id,
             parent_type=ContentType.objects.get_for_model(UserProfile),
         )
     else:
         self.source = get_object_or_404(
             Source,
             mnemonic=source_id,
             parent_id=self.org.id,
             parent_type=ContentType.objects.get_for_model(Organization),
         )
     concept_id = kwargs.get("concept")
     self.updated_since = request.GET.get("updated_since", None)
     self.limit = request.GET.get("limit", None)
     return get_object_or_404(Concept, parent_id=self.source.id, mnemonic=concept_id)
Example #12
0
def claim(user, worldname):
    # TODO: write tests for this
    if not re.match("\w+$", worldname):
        raise ClaimException, "Invalid world name."
        # world, new = World.get_or_create(worldname)
    get_object_or_404(World, name=worldname)
    # if new:
    # return do_claim(user, world)
    # if world.owner:
    # raise ClaimException, "That world already has an owner."
    editors = set(world.edit_set.all().values_list("user", flat=True))
    if not editors:
        return do_claim(user, world)
    if len(editors) > 2:
        raise ClaimException, "Too many people have edited that world."
    if len(editors) == 2:
        if editors == set([user, None]):
            return do_claim(user, world)
        else:
            raise ClaimException, "Too many people have edited that world."
    assert len(editors) == 1
    obj = editors.pop()
    if obj == user:
        return do_claim(user, world)
    if obj is not None:
        raise ClaimException, "Too many people have edited that world."
    if world.created_at > datetime.datetime.now() - datetime.timedelta(minutes=5):
        raise ClaimException, "That world has been around too long to claim."
    return do_claim(user, world)
Example #13
0
def post_edit(request, blog_slug, username, post_slug):
    blog = get_object_or_404(Blog, slug=blog_slug)
    post = get_object_or_404(Post, blog__slug=blog_slug, user__username=username, slug=post_slug)
    is_post_owner = request.user.is_staff or request.user == User.objects.get(username=username)
    if not is_post_owner:
        return HttpResponse("You are not allowed to edit this post.")

    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post.title = form.cleaned_data["title"]
            post.body = form.cleaned_data["body"]
            post.save()
            for asset in post.asset_set.all():
                if request.POST.has_key("asset-%s" % asset.id):
                    asset.delete()
            _handle_upload(post, request.FILES.get("image_1"), 1)
            _handle_upload(post, request.FILES.get("image_2"), 2)
            _handle_upload(post, request.FILES.get("image_3"), 3)
            return redirect(post)
    else:
        form = PostForm({"title": post.title, "body": post.body})

    return render_to_response(
        "blog/post_edit.html",
        {"user": request.user, "blog": blog, "post": post, "form": form},
        context_instance=RequestContext(request),
    )
def archive_detail(request, newsletter_slug, year, month, day, slug):
    my_newsletter = get_object_or_404(Newsletter.on_site, slug=newsletter_slug, visible=True)

    submission = get_object_or_404(
        Submission,
        newsletter=my_newsletter,
        publish=True,
        publish_date__year=year,
        publish_date__month=month,
        publish_date__day=day,
        message__slug=slug,
    )

    message = submission.message
    (subject_template, text_template, html_template) = EmailTemplate.get_templates("message", message.newsletter)

    if not html_template:
        raise Http404(_("No HTML template associated with the newsletter this message belongs to."))

    c = Context(
        {
            "message": message,
            "site": Site.objects.get_current(),
            "newsletter": message.newsletter,
            "date": datetime.now(),
        }
    )

    return HttpResponse(html_template.render(c))
Example #15
0
def variant_new(request, slug, version_slug):
    package = get_object_or_404(Package, slug=slug)
    version = get_object_or_404(Version, slug=version_slug, package=package)
    if request.method == "POST":
        form = NewVariantForm(request.POST)
        # required for validation!
        form.package = package
        form.request = request
        if form.is_valid():
            if Variant.objects.filter(slug=form.cleaned_data["slug"], version=version):
                raise Http404("A variant like this already exists.")  # TODO: nicer error.
            # get object, save package
            variant = form.save(commit=False)
            variant.version = version
            variant.set_signature()
            variant.save()
            # TODO: check usefile.
            # TODO: check version slug
            return redirect(
                "nirvana.pkg.views.variant", slug=package.slug, version_slug=version.slug, variant_slug=variant.slug
            )
    else:
        form = NewVariantForm()
    # if it's invalid or initial, display it.
    return render_to_response("pkg/variant_new.html", {"form": form}, context_instance=RequestContext(request))
Example #16
0
    def goto_next(cls, order_id, role, order_action, item_action, item_id, **kwargs):
        if order_action:
            # if there is no order yet, and the action is from Buyer 'create order', then create the order
            if not order_id and role == "B" and order_action == "create order":
                # TODO: remove below?
                order_id = Order.create_order()
                order = get_object_or_404(Order, id=order_id)
            else:
                order = get_object_or_404(Order, id=order_id)
                order.goto_next(role, order_action)
        if item_action:
            # if item_action, this will only affect the item that is acted on
            order = get_object_or_404(Order, id=order_id)
            ocr = order.order_item_rel_set.get(item_id=item_id)
            ocr.goto_next(role, item_action)

            if not Refund_Sheet.objects.filter(item_id=ocr.id).exists():  # not ocr.refund_sheet:
                if ocr.state == "WR":
                    rs_type = ""
                    if item_action == "request refund":
                        rs_type = "RO"
                    if item_action == "request refund with return":
                        rs_type = "RR"
                    rs = Refund_Sheet.create_refund_sheet(ocr.id, rs_type)
                    rl = Refund_Log(
                        refund_sheet_id=rs.id,
                        refund_type=rs.refund_type,
                        action=item_action,
                        reason=kwargs.get("reason", ""),
                        memo=kwargs.get("memo", ""),
                        operator=kwargs.get("operator", ""),
                        refund_fee=kwargs.get("refund_fee", None),
                    )
                    rl.save()
            else:
                rs = get_object_or_404(Refund_Sheet, item_id=ocr.id)
                next_state, post_action = rs.goto_next(role, item_action)
                # TODO:make below into post_action
                if item_action == "ship back":
                    rs.express_company = kwargs.get("express_company", "")
                    rs.express_tracking_no = kwargs.get("express_tracking_no", "")
                    rs.save()
                if item_action == "change refund request":
                    rs_type = kwargs.get("refund_type", "")
                    if rs_type:
                        rs.refund_type = rs_type
                        rs.save()
                if next_state:
                    rl = Refund_Log(
                        refund_sheet_id=rs.id,
                        refund_type=kwargs.get("refund_type", ""),
                        action=item_action,
                        reason=kwargs.get("reason", ""),
                        memo=kwargs.get("memo", ""),
                        operator=kwargs.get("operator", ""),
                        refund_fee=kwargs.get("refund_fee", None),
                    )
                    rl.save()

        return {"order": order, "admin_actions": admin_actions, "input_actions": input_actions}
Example #17
0
def variant_edit(request, slug, version_slug, variant_slug):
    package = get_object_or_404(Package, slug=slug)
    version = get_object_or_404(Version, slug=version_slug, package=package)
    variant = get_object_or_404(Variant, slug=variant_slug, version=version)
    if not package.is_authorized_for_variant(request.user, variant.slug):
        raise Http404("You are not authorized to edit this variant.")
    if request.method == "POST":
        form = EditVariantForm(request.POST, instance=variant)
        # required for validation!
        form.package = package
        form.request = request
        if form.is_valid():
            # get object, save package
            variant = form.save(commit=False)
            variant.version = version
            variant.set_signature()
            variant.save()
            # TODO: check usefile.
            # TODO: check version slug
            return redirect(
                "nirvana.pkg.views.variant", slug=package.slug, version_slug=version.slug, variant_slug=variant.slug
            )
    else:
        form = EditVariantForm(instance=variant)
    # if it's invalid or initial, display it.
    return render_to_response("pkg/variant_edit.html", {"form": form}, context_instance=RequestContext(request))
Example #18
0
def group_event_details(request, project, group_id, event_id):
    group = get_object_or_404(Group, pk=group_id)

    if group.project and group.project != project:
        return HttpResponseRedirect(
            reverse(
                "sentry-group-event",
                kwargs={"group_id": group.pk, "project_id": group.project_id, "event_id": event_id},
            )
        )

    event = get_object_or_404(group.event_set, pk=event_id)

    return render_to_response(
        "sentry/groups/event.html",
        {
            "project": project,
            "page": "event_list",
            "group": group,
            "event": event,
            "interface_list": _get_rendered_interfaces(event),
            "json_data": event.data.get("extra", {}),
            "version_data": event.data.get("modules", None),
        },
        request,
    )
Example #19
0
def group_membership_self_remove(request, slug, user_id):
    group = get_object_or_404(Group, slug=slug)

    if not has_view_perm(request.user, "user_groups.view_group", group) and not group.allow_self_remove:
        raise Http403

    user = get_object_or_404(User, pk=user_id)

    group_membership = GroupMembership.objects.filter(member=user, group=group)

    if group_membership:
        group_membership = group_membership[0]
        if group_membership.member == user:
            log_defaults = {
                "event_id": 223000,
                "event_data": "%s (%d) deleted by %s"
                % (group_membership._meta.object_name, group_membership.pk, request.user),
                "description": "%s deleted" % group_membership._meta.object_name,
                "user": request.user,
                "request": request,
                "instance": group_membership,
            }
            EventLog.objects.log(**log_defaults)
            group_membership.delete()
            messages.add_message(request, messages.SUCCESS, "Successfully removed yourself from group %s" % group)
    else:
        messages.add_message(request, messages.INFO, "You are not in the group %s" % group)

    return HttpResponseRedirect(reverse("group.search"))
Example #20
0
def edit_wormhole(request, map_id, wh_id):
    """
    A GET request gets the edit wormhole dialog pre-filled with current info.
    A POST request saves the posted data as the new info.
    POST values are topType, bottomType, massStatus, timeStatus, topBubbled,
    and bottomBubbled.
    """
    if not request.is_ajax():
        raise PermissionDenied
    wormhole = get_object_or_404(Wormhole, pk=wh_id)
    if request.method == "GET":
        return TemplateResponse(request, "edit_wormhole.html", {"wormhole": wormhole})
    if request.method == "POST":
        wormhole.mass_status = int(request.POST.get("massStatus", 0))
        wormhole.time_status = int(request.POST.get("timeStatus", 0))
        wormhole.top_type = get_object_or_404(WormholeType, name=request.POST.get("topType", "K162"))
        wormhole.bottom_type = get_object_or_404(WormholeType, name=request.POST.get("bottomType", "K162"))
        wormhole.top_bubbled = request.POST.get("topBubbled", "1") == "1"
        wormhole.bottom_bubbled = request.POST.get("bottomBubbled", "1") == "1"
        wormhole.save()
        wormhole.map.add_log(
            request.user,
            (
                "Updated the wormhole between %s(%s) and %s(%s)."
                % (
                    wormhole.top.system.name,
                    wormhole.top.friendlyname,
                    wormhole.bottom.system.name,
                    wormhole.bottom.friendlyname,
                )
            ),
        )
        return HttpResponse()

    raise PermissiondDenied
Example #21
0
def url_transform_edit(request, id, transform_id):
    match = get_object_or_404(URLMatch, id=id)
    transform = get_object_or_404(URLTransform, id=transform_id, match=match)
    transform.find = request.POST["find"]
    transform.replace_with = request.POST["replace_with"]
    transform.save()
    return True
Example #22
0
def move_choose_destination(request, page_to_move_id, viewed_page_id=None):
    page_to_move = get_object_or_404(Page, id=page_to_move_id)
    page_perms = page_to_move.permissions_for_user(request.user)
    if not page_perms.can_move():
        raise PermissionDenied

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

    viewed_page.can_choose = page_perms.can_move_to(viewed_page)

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

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

        child_pages.append(target)

    return render(
        request,
        "wagtailadmin/pages/move_choose_destination.html",
        {"page_to_move": page_to_move, "viewed_page": viewed_page, "child_pages": child_pages},
    )
Example #23
0
def compare(request, document_slug, document_locale):
    """
    Compare two wiki document revisions.

    The ids are passed as query string parameters (to and from).
    """
    locale = request.GET.get("locale", document_locale)
    doc = get_object_or_404(Document, locale=locale, slug=document_slug)

    if "from" not in request.GET or "to" not in request.GET:
        raise Http404

    try:
        from_id = smart_int(request.GET.get("from"))
        to_id = smart_int(request.GET.get("to"))
    except:
        # Punt any errors in parameter handling to a 404
        raise Http404

    revisions = Revision.objects.prefetch_related("document")
    revision_from = get_object_or_404(revisions, id=from_id, document=doc)
    revision_to = get_object_or_404(revisions, id=to_id, document=doc)

    context = {"document": doc, "revision_from": revision_from, "revision_to": revision_to}

    if request.GET.get("raw", False):
        template = "wiki/includes/revision_diff_table.html"
    else:
        template = "wiki/compare_revisions.html"

    return render(request, template, context)
Example #24
0
def update(request):
    user = get_object_or_404(User, pk=request.user.id)
    profile = get_object_or_404(Profile, user=request.user.id)
    if request.method == method.GET:
        form_user = UserUpdateForm(instance=user)
        form_profile = ProfileUpdateForm(instance=profile)
    if request.method == method.POST:
        form_user = UserUpdateForm(request.POST.copy(), instance=user)
        form_profile = ProfileUpdateForm(request.POST.copy(), instance=profile)
        if form_user.is_valid() and form_profile.is_valid():
            user = form_user.save(True)
            form_user.data["old_password"] = ""
            form_user.data["new_password1"] = ""
            form_user.data["new_password2"] = ""
            profile = form_profile.save(True)
            flash_success(request, _("Your profile was updated successfully."))
            return set_language(request)
        else:
            form_wrong = form_user if not form_user.is_valid() else form_profile
            flash_form_error(request, form_wrong)
            # print 'language = ' + repr(form.base_fields['language'].initial)
    context_instance = RequestContext(request)
    template_name = "profiles/update.html"
    extra_context = {
        "menu": "",
        "form_user": form_user,
        "form_profile": form_profile,
        "show_debug": "debug" in request.GET,
    }
    return render_to_response(template_name, extra_context, context_instance)
Example #25
0
def inc_desc(sign, request, pk):
    """
    Need doc
    """
    ple = get_object_or_404(PlaylistEntry, pk=pk)
    key = "ple_{}_{}".format(request.user.id, ple.pk)
    song_key = "song_{}".format(ple.song.pk)

    if cache.get(key):
        return HttpResponse(json.dumps({"message": "Do not try this with me"}), mimetype="application/json")
    else:
        cache.set(key, True)
        cache.set(song_key, True)

    song = get_object_or_404(Song, pk=ple.song.id)

    if sign == "plus":
        ple.score += 1
        song.global_score += 1
        vte = +1
    else:
        ple.score -= 1
        song.global_score -= 1
        vte = -1
    ple.save()
    song.save()
    # create a vote for this song
    Vote.objects.create(song=song, user=request.user, vote=vte)

    resp = {"score": ple.score, "id": ple.pk}
    return HttpResponse(json.dumps({"entry": resp}), mimetype="application/json")
Example #26
0
def registration(req, pk=None):
    contact = None
    connection = None
    bulk_form = None

    if pk is not None:
        contact = get_object_or_404(Contact, pk=pk)
        connection = get_object_or_404(Connection, contact__name=contact.name)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(reverse(registration))

        elif "bulk" in req.FILES:
            # TODO use csv module
            # reader = csv.reader(open(req.FILES["bulk"].read(), "rb"))
            # for row in reader:
            for line in req.FILES["bulk"]:
                line_list = line.split(",")
                name = line_list[0].strip()
                backend_name = line_list[1].strip()
                identity = line_list[2].strip()

                contact = Contact(name=name)
                contact.save()
                # TODO deal with errors!
                backend = Backend.objects.get(name=backend_name)

                connection = Connection(backend=backend, identity=identity, contact=contact)
                connection.save()

            return HttpResponseRedirect(reverse(registration))
        else:
            contact_form = ContactForm(instance=contact, data=req.POST)
            connection_form = ConnectionForm(req.POST, instance=connection)

            if contact_form.is_valid() and connection_form.is_valid():
                contact = contact_form.save()
                connection = connection_form.save(commit=False)
                connection.contact = contact
                connection.save()
                return HttpResponseRedirect(reverse(registration))

    else:
        contact_form = ContactForm(instance=contact)
        bulk_form = BulkRegistrationForm()
        connection_form = ConnectionForm(instance=connection)

    return render_to_response(
        "registration/dashboard.html",
        {
            "contacts_table": ContactTable(Contact.objects.all(), request=req),
            "contact_form": contact_form,
            "connection_form": connection_form,
            "bulk_form": bulk_form,
            "contact": contact,
        },
        context_instance=RequestContext(req),
    )
Example #27
0
def question_update(
    request,
    survey_slug,
    question_id,
    group_slug=None,
    group_slug_field=None,
    group_qs=None,
    template_name="survey/question_add.html",
    extra_context=None,
    *args,
    **kw
):
    survey = get_object_or_404(Survey, slug=survey_slug)
    question = get_object_or_404(Question, id=question_id)
    if question not in survey.questions.iterator():
        raise Http404()

    if request.method == "POST":
        request_post = request.POST.copy()
        question_form = QuestionForm(instance=question, data=request_post, files=request.FILES)

        if question_form.is_valid():
            new_question = question_form.save(commit=False)
            new_question.survey = survey
            new_question.save()
            return HttpResponseRedirect(reverse("survey-edit", None, (), {"survey_slug": survey_slug}))
    else:
        question_form = QuestionForm(instance=question)

    return render_to_response(
        template_name,
        {"title": _("Update question"), "question": question, "model_string": "Question", "form": question_form},
        context_instance=RequestContext(request),
    )
Example #28
0
def version_edit(request, slug, version_slug):
    package = get_object_or_404(Package, slug=slug)
    if version_slug is None:  # display latest version
        version = package.latest_version
    else:
        version = get_object_or_404(Version, package=package, slug=version_slug)
    if request.user != package.author:
        # oh oh! hacker! let's confuse him with a 404.
        raise Http404()
    else:
        if request.method == "POST":
            form = EditVersionForm(request.POST, instance=version)
            if form.is_valid():
                if version.slug != form.cleaned_data["slug"] and Version.objects.filter(
                    slug=form.cleaned_data["slug"], package=package
                ):
                    raise Http404("A version like this already exists.")  # TODO: nicer error.
                version = form.save(commit=False)
                if version.latest:
                    version.make_latest()
                version.save()
                # TODO: check version slug
                return redirect("nirvana.pkg.views.version", slug=package.slug, version_slug=version.slug)
        else:
            form = EditVersionForm(instance=version)
        # if it's invalid or initial, display it.
        return render_to_response("pkg/version_edit.html", {"form": form}, context_instance=RequestContext(request))
Example #29
0
def table_edit(request, pk):
    if request.method == "POST":
        adds = None
        removes = None
        if "adds[]" in request.POST:
            adds = request.POST.getlist("adds[]")
        if "removes[]" in request.POST:
            removes = request.POST.getlist("removes[]")
        table = get_object_or_404(Table, pk=pk)
        if adds is not None:
            for user_id in adds:
                person = get_object_or_404(Person, user_id=user_id)
                table.people.add(person)
        if removes is not None:
            for user_id in removes:
                person = get_object_or_404(Person, user_id=user_id)
                table.people.remove(person)
        table.save()
        return table_detail(request, pk=pk)
    else:
        from django.core import serializers

        table = Table.objects.get(pk=pk)
        members = table.people.all()
        followees = Followees.objects.get(user=request.user).people.all()
        others = followees.exclude(pk__in=members)
        members = serializers.serialize("json", members)
        others = serializers.serialize("json", others)
        return render(request, "table_edit.html", {"table": table, "members": members, "others": others})
Example #30
0
def group_membership_self_add(request, slug, user_id):
    group = get_object_or_404(Group, slug=slug)
    user = get_object_or_404(User, pk=user_id)

    if not has_view_perm(request.user, "user_groups.view_group", group) and not group.allow_self_add:
        raise Http403

    group_membership = GroupMembership.objects.filter(member=user, group=group)

    if not group_membership:
        group_membership = GroupMembership()

        group_membership.group = group
        group_membership.member = user
        group_membership.creator_id = user.id
        group_membership.creator_username = user.username
        group_membership.owner_id = user.id
        group_membership.owner_username = user.username

        group_membership.save()

        EventLog.objects.log(instance=group_membership)

        if group_membership.is_newsletter_subscribed:
            group_membership.subscribe_to_newsletter()

        messages.add_message(
            request, messages.SUCCESS, _("Successfully added yourself to group %(grp)s" % {"grp": group})
        )
    else:
        messages.add_message(request, messages.INFO, _("You are already in the group %(grp)s" % {"grp": group}))

    return HttpResponseRedirect(reverse("group.search"))