django.template.RequestContext

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

167 Examples 7

Example 1

Project: transifex Source File: views.py
@login_required
def translate(request, project_slug, lang_code, resource_slug=None,
                     *args, **kwargs):
    """
    Main lotte view.
    """

    # 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)

    resources = []
    if resource_slug:
        resource_list = [get_object_or_404(Resource, slug=resource_slug,
            project=project)]
    else:
        resource_list = Resource.objects.filter(project=project)

        # Return a page explaining that the project has multiple source langs and
        # cannot be translated as a whole.
        if resource_list.values('source_language').distinct().count() > 1:
            messages.info(request,_(
                          "There are multiple source languages for this project. "
                          "You will only be able to translate resources for one "
                          "source language at a time."))
            return HttpResponseRedirect(reverse('project_detail',
                                        args=[project_slug]),)

    # Filter resources that are not accepting translations
    for resource in resource_list:
        if resource.accept_translations:
            resources.append(resource)

    # If no resource accepting translations, raise a 403
    if not resources:
        return permission_denied(request)

    target_language = Language.objects.by_code_or_alias_or_404(lang_code)

    # If it is an attempt to edit the source language, redirect the user to
    # resource_detail and show him a message explaining the reason.
    if target_language == get_source_language(resources):
        messages.error(request,_(
                       "Cannot edit the source language because this would "
                       "result in translation mismatches! If you want to "
                       "update the source strings consider using the transifex "
                       "command-line client."))
        if resource_slug:
            return HttpResponseRedirect(reverse('resource_detail',
                                                args=[project_slug,
                                                      resource_slug]),)
        else:
            return HttpResponseRedirect(reverse('project_detail',
                                                args=[project_slug]),)

    total_strings = SourceEntity.objects.filter(
        resource__in = resources).count()

    translated_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5).count()

    reviewed_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5,
        reviewed=True).count()

    # Include counting of pluralized entities
    for pluralized_entity in SourceEntity.objects.filter(resource__in = resources,
                                                         pluralized=True):
        plurals_translated = Translation.objects.filter(
            language=target_language,
            source_entity=pluralized_entity).count()
        if plurals_translated == len(target_language.get_pluralrules()):
            translated_strings += 1

    if len(resources) > 1:
        translation_resource = None
    else:
        translation_resource = resources[0]

    contributors = User.objects.filter(pk__in=Translation.objects.filter(
        resource__in = resources,
        language = target_language,
        rule = 5).values_list("user", flat=True))

    lotte_init.send(None, request=request, resources=resources,
        language=target_language)

    if target_language in [team.language for team in project.available_teams]:
        team_language = True
    else:
        team_language = False

    GtModel = get_model('gtranslate', 'Gtranslate')
    try:
        auto_translate = GtModel.objects.get(project=project)
    except GtModel.DoesNotExist:
        auto_translate = None
    """
    if cache.get('lotte_%s' % request.session.session_key, None):
        cache.delete('lotte_%s' % request.session.session_key)
    """

    #Set rtl to True if target_language is an RTL language
    rtl = False
    if target_language.code in settings.RTL_LANGUAGE_CODES:
        rtl = True

    return render_to_response("translate.html", {
        'project': project,
        'resource': translation_resource,
        'target_language': target_language,
        'translated_strings': translated_strings,
        'reviewed_strings': reviewed_strings,
        'untranslated_strings': total_strings - translated_strings,
        'contributors': contributors,
        'resources': resources,
        'resource_slug': resource_slug,
        'languages': Language.objects.all(),
        'auto_translate': auto_translate,
        'spellcheck_supported_langs': SPELLCHECK_SUPPORTED_LANGS,
        'team_language': team_language,
        'RTL': rtl,
    }, context_instance = RequestContext(request))

Example 2

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 3

Project: syndicate Source File: views.py
@authenticate
def create(request):
    '''
    View to handle creation of RG's
    '''
    session = request.session
    username = session['login_email']
    user = db.read_user( username )

    # Helper method used to simplify error-handling. When fields are entered incorrectly,
    # a session message is set and this method is called.
    def give_create_form(username, session):
        message = session.pop('message', "")
        form = gatewayforms.CreateRG()
        t = loader.get_template('gateway_templates/create_replica_gateway.html')
        c = RequestContext(request, {'username':username,'form':form, 'message':message})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.CreateRG(request.POST, request.FILES)
        if form.is_valid():
            kwargs = {}
            
            # Try and load JSON config file/data, if present. First check uploaded files, then
            # the text box.
            if "json_config" in request.FILES:
                if request.FILES['json_config'].multiple_chunks():
                    session['message'] = "Uploaded file too large; please make smaller than 2.5M"
                    return give_create_form(username, session)
                config = request.FILES['json_config'].read()
                try:
                    kwargs['config'] = json.loads(config)
                except Exception as e:
                    logging.info("Possible JSON load error: %s" % e)
                    try:
                        kwargs['config'] = json.loads("\"" + config + "\"")
                    except Exception as e:
                        logging.error("Definite JSON load error %s" % e)
                        session['message'] = "Error parsing given JSON text."
                        return give_create_form(username, session)

            # No upload, check text-box
            elif "json_config_text" in form.cleaned_data:
                try:
                    kwargs['config'] = json.loads(form.cleaned_data['json_config_text'])
                except Exception as e:
                    logging.info("Possible JSON load error: %s" % e)
                    try:
                        kwargs['config'] = json.loads("\"" + str(form.cleaned_data['json_config_text']) + "\"")
                    except Exception as e:
                        logging.error("Definite JSON load error %s" % e)
                        session['message'] = "Error parsing given JSON text."
                        return give_create_form(username, session)     


            try:
                kwargs['ms_username'] = form.cleaned_data['g_name']
                kwargs['port'] = form.cleaned_data['port']
                kwargs['host'] = form.cleaned_data['host']
                kwargs['ms_password'] = form.cleaned_data['g_password']
                kwargs['private'] = form.cleaned_data['private']
                new_RG = db.create_replica_gateway(user, **kwargs)
            except Exception as E:
                session['message'] = "RG creation error: %s" % E
                return give_create_form(username, session)

            session['new_change'] = "Your new gateway is ready."
            session['next_url'] = '/syn/RG/allgateways/'
            session['next_message'] = "Click here to see all replica gateways."
            return redirect('/syn/thanks/')
        else:
            # Prep returned form values (so they don't have to re-enter stuff)
            if 'g_name' in form.errors:
                oldname = ""
            else:
                oldname = request.POST['g_name']
            if 'host' in form.errors:
                oldhost = ""
            else:
                oldhost = request.POST['host']
            if 'port' in form.errors:
                oldport = ""
            else:
                oldport = request.POST['port']
            oldjson = request.POST['json_config_text']

            # Prep error message
            message = "Invalid form entry: "

            for k, v in form.errors.items():
                message = message + "\"" + k + "\"" + " -> " 
                for m in v:
                    message = message + m + " "

            # Give then the form again
            form = gatewayforms.CreateRG(initial={'g_name': oldname,
                                       'host': oldhost,
                                       'port': oldport,
                                       'json_config_text':oldjson,
                                       })
            t = loader.get_template('gateway_templates/create_replica_gateway.html')
            c = RequestContext(request, {'username':username,'form':form, 'message':message})
            return HttpResponse(t.render(c))

    else:
        # Not a POST, give them blank form
        return give_create_form(username, session)

Example 4

Project: WIPSTER Source File: views.py
def upload_form(request):

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
#            handle_uploaded_file(request.FILES['file'])
#            newsample = Sample(sample = request.FILES['sample'])
            f = request.FILES['sample']

            
            newsample = Sample(
                sample = f,
                ticket = request.POST['ticket'],
                filename = f.name,
                size = f.size,
#                type = f.content_type,
                type = handler.get_filetype(f),
                md5 = handler.get_md5(f),
                sha1 = handler.get_sha1(f),
                sha256 = handler.get_sha256(f),
                fuzzy = handler.get_fuzzy(f),
            )
            #breakdebug
            newsample.save()

            #Do post-processing stuff here
            s = Sample.objects.filter().order_by('-id')[0]
            #s.exif = handler.get_exif(s.sample).encode('ascii', errors='replace')
            #s.exif = unicode(handler.get_exif(s.sample))
            s.exif = handler.get_exif(s.sample)
            
            s.strings = handler.get_strings(s.sample)
            s.balbuzard = handler.get_balbuzard(s.sample)
            s.trid = handler.get_trid(s.sample)

            #SSDEEP/Fuzzy hash comparison
            s.ssdeep_compare = handler.ssdeep_compare(s.fuzzy, s.md5)

            #VirusTotal Search
            vt_res, vt_short_res = handler.get_vt(s.md5)
            if vt_res:
                s.vt = vt_res
                s.vt_short = vt_short_res

            #If EXE file, run EXE-specific checks
            if "PE32" and "Windows" in s.type:
                s.peframe = handler.get_peframe(s.sample)
                s.pescanner = handler.get_pescanner(s.sample)

            #If PDF file, run PDF-specific checks
            if "PDF" in s.type:
                s.pdfid = handler.get_pdfid(s.sample)
                s.peepdf = handler.get_peepdf(s.sample)
                s.pdf_strings = handler.get_pdfstrings(s.sample)

            #If DOC file, run DOC-specific checks
            if "Docuement File V2" in s.type:
                s.oleid = handler.get_oleid(s.sample)
                #If valid OLE file, run OLEMETA
                olematch = re.compile(r'\|\s+OLE format\s+\|\s+True\s+\|')
                if olematch.search(s.oleid):
                    s.olemeta = handler.get_olemeta(s.sample)
                #If VBA code detected, run OLEVBA
                vbamatch = re.compile(r'\|\s+VBA Macros\s+\|\s+True\s+\|')
                if vbamatch.search(s.oleid):
                    s.olevba = handler.get_olevba(s.sample)

            #If RTF file, run RTFOBJ
            if "Rich Text Format" in s.type:
                rtfobj, rtflist = handler.get_rtfobj(s.sample)
                s.rtfobj = rtfobj

            #If Objects found, run strings/balbuzard against them
            #REMOVED - TOO RESOURCE-INTENSIVE
#            if rtflist:
#                s.rtfobj_str = handler.get_rtfobj_str(rtflist)
#                s.rtfobj_balbuz = handler.get_rtfobj_balbuz(rtflist)
            
            

            s.save()

            newpage = "/sanalysis/md5/" + s.md5 + "/?upload=True"

            return HttpResponseRedirect(newpage)
        else:
            form = UploadFileForm()
            sample = Sample.objects.filter(created__lte=timezone.now()).order_by('-id')[:25]
            return render(request, 'sanalysis/upload_form.html', {'form': form, 'sample': sample},
                            context_instance = RequestContext(request))

#            return HttpResponseRedirect('/sanalysis/')

#            return render(request, 'sanalysis/sample_page.html', {'sample': sample,
#                                                                  'savename': savename,
#                                                                  'ta_use': ta_use,
#                                                                  'ta_analyses': ta_analyses,
#                                                                  'ta_risks': ta_risks,
#                                                                  'ta_network': ta_network,
#                                                                  'ta_ips': ta_ips,
#                                                                  'ta_domains': ta_domains,
#                                                                  'ta_commands': ta_commands,
#                                                                  'ta_submit': ta_submit,
#                                                                  'crits_use': crits_use,
#                                                                  'crits': crits_dict,
#                                                                  'crits_submit': crits_submit, })


    else:
        form = UploadFileForm()
        sample = Sample.objects.filter(created__lte=timezone.now()).order_by('-id')[:25]
        return render(request, 'sanalysis/upload_form.html', {'form': form, 'sample': sample})

Example 5

Project: jaikuenginepatch Source File: views.py
@alternate_nick
def actor_item(request, nick=None, item=None, format='html'):
  # The nick passed in the url looks ugly with the escaped @ in it and is
  # generally just shorter if we only use the lead part of the nick
  # however the entire system expects full nicks so we should expand this
  # as soon as possible
  nick = clean.nick(nick)

  # Most pages have the concept of a viewer and an actor being viewed,
  # in all cases the viewer is `request.user` and the actor being viewed
  # should be named `view`
  view = api.actor_lookup_nick(request.user, nick)

  if not view:
    raise exception.UserDoesNotExistError(nick, request.user)

  # With very few exceptions, whenever we are referring to a an
  # instance that is an entity from the datastore we append `_ref`
  # to the variable name to distinguish it from the variable that
  # is simply a string identifier.
  # In the code below `stream_ref` and `entry_ref` are both entity
  # references, while `entry` is simply the string key_name of an entry
  stream_ref = api.stream_get_presence(request.user, view.nick)
  if not stream_ref:
    raise http.Http404()

  if item == 'last':
    entry_ref = api.entry_get_last(request.user, stream_ref.keyname())
    return http.HttpResponseRedirect(entry_ref.url())
  else:
    entry = '%s/%s' % (stream_ref.key().name(), item)
    entry_ref = api.entry_get_safe(request.user, entry)

  # Most api calls will return None if the entity being looked up does
  # not exist so we usually want to verify the return values
  if not entry_ref:
    raise http.Http404()


  # When handling user actions the following pattern more or less applies
  # if 'parameter_unique_to_action' in request.(POST|GET|REQUEST):
  #   try:
  #     validate.nonce(request, 'nonce_action')
  #     validate.anything_else_that_is_related_to_ui_rather_than_call()
  #
  #     local_variable = request.(POST|GET|REQUEST).get('request_arg')
  #     # or
  #     params = util.query_dict_to_keywords(request.(POST|GET|REQUEST))
  #
  #     # Our goal is to have most of the logic for any action translate
  #     # directly into an api call on behalf of the requesting user
  #     # such that the api call is responsible for validating all input
  #     # and raising any applicable errors
  #     result = api.some_api_method(request.user,
  #                                  method_variable=local_variable,
  #                                  ...)
  #     # or
  #     result = api.some_api_method(request.user,  **params)
  #
  #     # All actions should issue a redirect with a success message
  #     return util.RedirectFlash('some_url', 'some success message')
  #   except:
  #     exception.handle_exception(request)
  #
  # When an exception occurs we expect the rest of the page to be able
  # to be processed normally as if no action had been taken, the error
  # handling section of the template should display the errors caught
  # by the exception.handle_exception() call

  handled = common_views.handle_view_action(
      request,
      {'entry_add_comment': entry_ref.url(request=request),
       'entry_remove': view.url(request=request),
       'entry_remove_comment': entry_ref.url(request=request),
       'entry_mark_as_spam': entry_ref.url(request=request)
       }
      )
  if handled:
    return handled

  comments = api.entry_get_comments(request.user, entry_ref.key().name())

  # To minimize the number of lookups to the datastore once we know
  # all the data we will be displaying on a page we attempt to make
  # a list of all the actors associated with that data so that we can
  # fetch them all at once
  actor_nicks = [entry_ref.owner, entry_ref.actor] + [c.actor for c in comments]
  actors = api.actor_get_actors(request.user, actor_nicks)
  
  # Creates a copy of actors with lowercase keys (Django #6904: template filter
  # dictsort sorts case sensitive), excluding the currently logged in user.
  participants = {}
  for k, v in actors.iteritems():
    if (v and
        not (hasattr(request.user, 'nick') and request.user.nick == v.nick)):
      participants[k.lower()] = v

  # Due to restrictions on Django's templating language most of the time
  # we will have to take an additional step of preparing all of our data
  # for display, this usually translates to attaching references to
  # actor or stream entities.
  # Functions that handle this preparation should be added to the
  # common.display module
  entry = display.prep_entry(entry_ref,
                             {stream_ref.key().name(): stream_ref}, actors)
  comments = display.prep_comment_list(comments, actors)

  # Additionally, to minimize more logic in the templates some variables
  # can be defined to configure the output, these are usually template specific
  # though some are common variables for anything that inherits from the
  # base templates
  green_top = True
  sidebar_green_top = True

  # The quickest way to make sure we are getting all of the things we care
  # about passed to the template without the temptation of making last minute
  # changes is just to pass `locals()` to the template context
  c = template.RequestContext(request, locals())

  # Ideally this is all that should be necessary to add additional output
  # formats, in practice it is yet to be seen whether additional data
  # preparation will be necessary before outputting in JSON or ATOM formats
  if format == 'html':

    # We always use the full path to the template to prevent naming conflicts
    # and difficult searches.
    t = loader.get_template('item.html')
    return http.HttpResponse(t.render(c))

  elif format == 'json':
    t = loader.get_template('item.json')
    r = http.HttpResponse(t.render(c))
    r['Content-type'] = 'text/javascript'
    return r

Example 6

Project: baruwa Source File: views.py
@login_required
def report(request, report_kind):
    "displays a report"
    report_kind = int(report_kind)
    template = "reports/piereport.html"
    active_filters = []
    if report_kind == 1:
        data = run_query('from_address', {'from_address__exact': ""},
            '-num_count', request, active_filters)
        pie_data = pack_json_data(data, 'from_address', 'num_count')
        report_title = _("Top senders by quantity")
    elif report_kind == 2:
        data = run_query('from_address', {'from_address__exact': ""},
            '-total_size', request, active_filters)
        pie_data = pack_json_data(data, 'from_address', 'total_size')
        report_title = _("Top senders by volume")
    elif report_kind == 3:
        data = run_query('from_domain', {'from_domain__exact': ""},
            '-num_count', request, active_filters)
        pie_data = pack_json_data(data, 'from_domain', 'num_count')
        report_title = _("Top sender domains by quantity")
    elif report_kind == 4:
        data = run_query('from_domain', {'from_domain__exact': ""},
            '-total_size', request, active_filters)
        pie_data = pack_json_data(data, 'from_domain', 'total_size')
        report_title = _("Top sender domains by volume")
    elif report_kind == 5:
        data = run_query('to_address', {'to_address__exact': ""},
            '-num_count', request, active_filters)
        pie_data = pack_json_data(data, 'to_address', 'num_count')
        report_title = _("Top recipients by quantity")
    elif report_kind == 6:
        data = run_query('to_address', {'to_address__exact': ""},
            '-total_size', request, active_filters)
        pie_data = pack_json_data(data, 'to_address', 'total_size')
        report_title = _("Top recipients by volume")
    elif report_kind == 7:
        data = run_query('to_domain', {'to_domain__exact': "",
            'to_domain__isnull': False}, '-num_count', request,
            active_filters)
        pie_data = pack_json_data(data, 'to_domain', 'num_count')
        report_title = _("Top recipient domains by quantity")
    elif report_kind == 8:
        data = run_query('to_domain', {'to_domain__exact': "",
            'to_domain__isnull': False}, '-total_size',
            request, active_filters)
        pie_data = pack_json_data(data, 'to_domain', 'total_size')
        report_title = _("Top recipient domains by volume")
    elif report_kind == 9:
        from baruwa.messages.models import SpamScores

        filter_list = []
        addrs = []
        counts = []
        scores = []
        act = 3

        if not request.user.is_superuser:
            addrs = request.session['user_filter']['addresses']
            act = request.session['user_filter']['account_type']

        if request.session.get('filter_by', False):
            filter_list = request.session.get('filter_by')
            get_active_filters(filter_list, active_filters)

        data = SpamScores.objects.all(request.user, filter_list, addrs, act)
        for index, row in enumerate(data):
            value = index + 1
            scores.append({'value': value, 'text': str(row.score)})
            counts.append({'y': int(row.count),
            'tooltip': 'Score ' + str(row.score) + ': ' + str(row.count)})

        if request.is_ajax():
            data = [obj.obj_to_dict() for obj in data]

        pie_data = {'scores': scores, 'count': counts}
        template = "reports/barreport.html"
        report_title = _("Spam Score distribution")
    elif report_kind == 10:
        data = run_hosts_query(request, active_filters)
        pie_data = pack_json_data(data, 'clientip', 'num_count')
        if request.is_ajax():
            from baruwa.messages.templatetags.messages_extras import \
                tds_geoip, tds_hostname
            for row in data:
                row['country'] = tds_geoip(row['clientip'])
                row['hostname'] = tds_hostname(row['clientip'])
        report_title = _("Top mail hosts by quantity")
        template = "reports/relays.html"
    elif report_kind == 11:
        from baruwa.messages.models import MessageTotals

        filter_list = []
        addrs = []
        dates = []
        mail_total = []
        spam_total = []
        virus_total = []
        size_total = []
        act = 3

        if not request.user.is_superuser:
            addrs = request.session['user_filter']['addresses']
            act = request.session['user_filter']['account_type']

        if request.session.get('filter_by', False):
            filter_list = request.session.get('filter_by')
            get_active_filters(filter_list, active_filters)

        data = MessageTotals.objects.all(request.user, filter_list, addrs, act)

        for row in data:
            dates.append(str(row.date))
            mail_total.append(int(row.mail_total))
            spam_total.append(int(row.spam_total))
            virus_total.append(int(row.virus_total))
            size_total.append(int(row.size_total))

        pie_data = {'dates': [{'value': index + 1, 'text': date}
                    for index, date in enumerate(dates)],
                    'mail': [{'y': total,
                    'tooltip': 'Mail totals on ' + dates[index] + ': ' + str(total)}
                    for index, total in enumerate(mail_total)],
                    'spam': [{'y': total,
                    'tooltip': 'Spam totals on ' + dates[index] + ': ' + str(total)}
                    for index, total in enumerate(spam_total)],
                    'virii': [{'y': total,
                    'tooltip': 'Virus totals on ' + dates[index] + ': ' + str(total)}
                    for index, total in enumerate(virus_total)],
                    'volume': size_total,
                    #'volume_labels': [{'value': total,
                    #'text': str(filesizeformat(total))} for total in size_total],
                    'mail_total': sum(mail_total),
                    'spam_total': sum(spam_total),
                    'virus_total': sum(virus_total),
                    'volume_total': sum(size_total)}
        try:
            vpct = "%.1f" % ((1.0 * sum(virus_total) / sum(mail_total)) * 100)
            spct = "%.1f" % ((1.0 * sum(spam_total) / sum(mail_total)) * 100)
        except ZeroDivisionError:
            vpct = "0.0"
            spct = "0.0"
        pie_data['vpct'] = vpct
        pie_data['spct'] = spct
        #graph_totals = {}
        if request.is_ajax():
            data = [obj.obj_to_dict() for obj in data]

        report_title = _("Total messages [ After SMTP ]")
        template = "reports/listing.html"
    filter_form = FilterForm()

    if request.is_ajax():
        response = anyjson.dumps({'items': list(data), 'pie_data': pie_data})
        return HttpResponse(response,
            content_type='application/javascript; charset=utf-8')
    else:
        if not report_kind in [9, 11]:
            pie_data = anyjson.dumps(pie_data)
        return render_to_response(template, {'pie_data': pie_data,
            'top_items': data, 'report_title': report_title,
            'report_kind': report_kind, 'active_filters': active_filters,
            'form': filter_form}, context_instance=RequestContext(request))

Example 7

Project: daywatch Source File: views.py
@catch_error
@log_activity
@login_required
@permission_required
def history_listings_div(request):
    #prepare the params
    context = get_status(request)
    form = HistoryPanelExportForm(user=request.user, data=request.GET)

    if form.is_valid():
        request.session['form_session'] = form.cleaned_data
        period = form.cleaned_data['period']
        style = get_style()
        style_ref = get_style_ref(style)
        user = request.user

        # Convert date parameters
        end_date = datetime.now()
        if period == 'last_30_d':
            start_date = datetime.now() - timedelta(days=30)
        elif period == 'last_15_d':
            start_date = datetime.now() - timedelta(days=15)
        elif period == 'last_7_d':
            start_date = datetime.now() - timedelta(days=7)
        elif period == 'custom':
            d = form.cleaned_data['start_date']
            start_date = datetime(d.year, d.month, d.day)
            d = form.cleaned_data['end_date']
            end_date = datetime(d.year, d.month, d.day, 23, 59)

        country = form.cleaned_data['country']
        context['use_local_currency'] = country in LOCAL_CURRENCY_COUNTRIES
        context['local_currency'] = CURRENCY_DICT[country]

        history_limit = 0
        out_of_range_error = False
        out_of_range_warning = False
        if not user.has_full_access_for_country(country):
            if user.week_history_limit > 0:
                #user is history limited, limit start and end dates
                week_limit = user.week_history_limit
                history_limit = datetime.now() - timedelta(weeks=week_limit)
                if end_date < history_limit:
                    out_of_range_error = True
                elif start_date < history_limit:
                    start_date = history_limit
                    out_of_range_warning = True
                history_limit = history_limit.date()

        # Get deals for this query
        if not out_of_range_error:
            player_ids = form.cleaned_data['players']
            player_ids = [int(p_id) for p_id in player_ids]

            if form.cleaned_data['all_categories']:
                items = DayWatchItem.objects.filter(
                    site__id__in=player_ids,
                    date_time__gte=start_date,
                    date_time__lte=end_date
                )
                categories = Category.objects.all()
                category_ids = []
                for category in categories:
                    if category.name != 'root':
                        category_ids.append(category.id)
            else:
                category_ids = form.cleaned_data['categories']
                category_ids = [int(c_id) for c_id in category_ids]
                items = DayWatchItem.objects.filter(
                    site__id__in=player_ids,
                    category__id__in=category_ids,
                    date_time__gte=start_date,
                    date_time__lte=end_date
                )
        else:
            items = DayWatchItem.objects.none()

        # Prepare and return results to upper layers
        context['items'] = items
        context['country'] = country
        context['style_ref'] = style_ref

        context['history_limit'] = history_limit
        context['out_of_range_error'] = out_of_range_error
        context['out_of_range_warning'] = out_of_range_warning

    # excel button clicked
    if form.data.get('excel'):
        if not request.user.premium_access:
            msg = " Sorry, Excel exports are limited to Premium Users."
            return warningResponse(request, _(msg))

        if not user.is_staff:
            # We limit exportable deals to a month and a half from today
            floor_date = datetime.now() - timedelta(weeks=7)
            context['items'] = context['items'].filter(
                                        start_date_time__gte=floor_date)

            if start_date < floor_date:
                context['floor_date_warn'] = floor_date

        filename = "DayWatch_report_%s" % (
            datetime.now().strftime("%d-%m-%Y_%H-%M"),
        )
        result = render_to_string(
            'includes/history_table_xls.html',
            context,
            context_instance=RequestContext(request)
        )
        response = HttpResponse(
            result,
            content_type='application/vnd.ms-excel;charset=utf-8'
        )
        content_disposition = 'attachment; filename="%s.xls"' % (filename,)
        response['Content-Disposition'] = content_disposition

        return response

    # Normal results rendering
    # col_index_name_map is required for correct sorting behavior
    index_name_map = {
        0: 'offer',
        1: 'company',
        2: 'start_date_time',
        3: 'end_date_time',
        4: 'price',
        5: 'price_usd',
        6: 'discount',
        7: 'category',
        8: 'is_main_deal',
        9: 'sold_count',
        10: 'total_sales_usd',
        11: 'merchant_name',
    }
    if context['use_local_currency']:
        index_name_map[10] = 'total_sales_local'

    json_template = 'includes/history_table_json.txt'

    return get_datatables_records(
        request, context['items'],
        index_name_map, context, json_template
    )

Example 8

Project: readthedocs.org Source File: views.py
def create_profile(request, form_class, success_url=None,
                   template_name='profiles/private/create_profile.html',
                   extra_context=None):
    """
    Create a profile for the current user, if one doesn't already
    exist.

    If the user already has a profile, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view.

    **Optional arguments:**

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.

    ``success_url``
        The URL to redirect to after successful profile creation. If
        this argument is not supplied, this will default to the URL of
        :view:`profiles.views.profile_detail` for the newly-created
        profile object.

    ``template_name``
        The template to use when displaying the profile-creation
        form. If not supplied, this will default to
        :template:`profiles/create_profile.html`.

    **Context:**

    ``form``
        The profile-creation form.

    **Template:**

    ``template_name`` keyword argument, or
    :template:`profiles/create_profile.html`.

    """
    try:
        profile_obj = request.user.profile
        return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass

    #
    # We set up success_url here, rather than as the default value for
    # the argument. Trying to do it as the argument's default would
    # mean evaluating the call to reverse() at the time this module is
    # first imported, which introduces a circular dependency: to
    # perform the reverse lookup we need access to profiles/urls.py,
    # but profiles/urls.py in turn imports this module.
    #

    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={'username': request.user.username})
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            profile_obj = form.save(commit=False)
            profile_obj.user = request.user
            profile_obj.save()
            if hasattr(form, 'save_m2m'):
                form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)

Example 9

Project: django-goflow Source File: views.py
@login_required
def edit_model(request, id, form_class, cmp_attr=None,template=None, template_def='goflow/edit_model.html', title="",
               redirect='home', submit_name='action', ok_values=('OK',), save_value=None, cancel_value='Cancel',
               extra_context={}):
    '''
    generic handler for editing a model.
    
    parameters:

    id
        workitem id (required)
    form_class
        model form based on goflow.apptools.forms.BaseForm (required)
    cmp_attr
        edit obj.cmp_attr attribute instead of obj - default=None
    template 
        default: 'goflow/edit_%s.html' % model_lowercase
    template_def
        used if template not found - default: 'goflow/edit_model.html'
    title
        default=""
    redirect
        default='home'
    submit_name
        name for submit buttons - default='action'
    ok_values
        submit buttons values - default=('OK',)
    save_value
        save button value - default='Save'
    cancel_value
        cancel button value - default='Cancel'
    extra_context
        default={}
    '''
    if not template: template = 'goflow/edit_%s.html' % form_class._meta.model._meta.object_name.lower()
    model_class = form_class._meta.model
    workitem = WorkItem.objects.get_safe(int(id), user=request.user)
    instance = workitem.instance
    activity = workitem.activity
    
    obj = instance.wfobject()
    obj_context = obj
    # objet composite intermédiaire
    if cmp_attr:
        obj = getattr(obj, cmp_attr)
    
    template = override_app_params(activity, 'template', template)
    redirect = override_app_params(activity, 'redirect', redirect)
    submit_name = override_app_params(activity, 'submit_name', submit_name)
    ok_values = override_app_params(activity, 'ok_values', ok_values)
    cancel_value = override_app_params(activity, 'cancel_value', cancel_value)

    if request.method == 'POST':
        form = form_class(request.POST, instance=obj)
        submit_value = request.POST[submit_name]
        if submit_value == cancel_value:
            return HttpResponseRedirect(redirect)
        
        if form.is_valid():
            if (submit_value == save_value):
                # just save
                #ob = form.save()
                try:
                    ob = form.save(workitem=workitem, submit_value=submit_value)
                except Exception, v:
                    raise Exception(str(v))
                return HttpResponseRedirect(redirect)
            
            if submit_value in ok_values:
                # save and complete activity
                #ob = form.save()
                try:
                    ob = form.save(workitem=workitem, submit_value=submit_value)
                except Exception, v:
                    raise Exception(str(v))
                instance.condition = submit_value
                instance.save()
                workitem.complete(request.user)
                return HttpResponseRedirect(redirect)
    else:
        form = form_class(instance=obj)
        # precheck
        form.pre_check(obj_context, user=request.user)
    
    context = {  'form': form, 'object':obj, 'object_context':obj_context,
                 'instance':instance, 'workitem':workitem,
                 'submit_name':submit_name, 'ok_values':ok_values,
                 'save_value':save_value, 'cancel_value':cancel_value,
                 'title':title}
    context.update(extra_context)
    return render_to_response((template, template_def), context,
                              context_instance=RequestContext(request))

Example 10

Project: snowy Source File: admin.py
    def render_revision_form(self, request, obj, version, revision, context, template, redirect_url):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        ordered_objects = opts.get_ordered_objects()
        app_label = opts.app_label
        object_version = version.object_version
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            for FormSet in self.get_formsets(request, new_object):
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object)
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)
                change_message = _(u"Reverted to previous version, saved on %(datetime)s") % {"datetime": format(version.revision.date_created, _(settings.DATETIME_FORMAT))}
                self.log_change(request, new_object, change_message)
                self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": opts.verbose_name, "name": unicode(obj)})
                return HttpResponseRedirect(redirect_url)
        else:
            initial = deserialized_model_to_dict(object_version, revision)
            form = ModelForm(instance=obj, initial=initial)
            for FormSet in self.get_formsets(request, obj):
                formset = FormSet(instance=obj)
                try:
                    attname = FormSet.fk.attname
                except AttributeError:
                    # This is a GenericInlineFormset, or similar.
                    attname = FormSet.ct_fk_field_name
                pk_name = FormSet.model._meta.pk.name
                initial_overrides = dict([(getattr(version.object, pk_name), version) for version in revision if version.object.__class__ == FormSet.model and unicode(getattr(version.object, attname)) == unicode(object_id)])
                initial = formset.initial
                for initial_row in initial:
                    pk = initial_row[pk_name]
                    if pk in initial_overrides:
                         initial_row.update(deserialized_model_to_dict(initial_overrides[pk], revision))
                         del initial_overrides[pk]
                    else:
                       initial_row["DELETE"] = True
                initial.extend([deserialized_model_to_dict(override, revision) for override in initial_overrides.values()])
                # HACK: no way to specify initial values.
                formset._total_form_count = len(initial)
                formset.initial = initial
                formset._construct_forms()
                formsets.append(formset)
        # Generate the context.
        adminForm = admin.helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
        media = self.media + adminForm.media
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = admin.helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        context.update({"adminform": adminForm,
                        "object_id": obj.pk,
                        "original": obj,
                        "is_popup": False,
                        "media": mark_safe(media),
                        "inline_admin_formsets": inline_admin_formsets,
                        "errors": admin.helpers.AdminErrorList(form, formsets),
                        "root_path": self.admin_site.root_path,
                        "app_label": app_label,
                        "add": False,
                        "change": True,
                        "has_add_permission": self.has_add_permission(request),
                        "has_change_permission": self.has_change_permission(request, obj),
                        "has_delete_permission": self.has_delete_permission(request, obj),
                        "has_file_field": True, # FIXME - this should check if form or formsets have a FileField,
                        "has_absolute_url": hasattr(self.model, "get_absolute_url"),
                        "ordered_objects": ordered_objects,
                        "form_url": mark_safe(request.path),
                        "opts": opts,
                        "content_type_id": ContentType.objects.get_for_model(self.model).id,
                        "save_as": self.save_as,
                        "save_on_top": self.save_on_top,
                        "root_path": self.admin_site.root_path,})
        return render_to_response(template, context, RequestContext(request))

Example 11

Project: tendenci Source File: views.py
@is_enabled('jobs')
@login_required
def add(request, form_class=JobForm, template_name="jobs/add.html",
        object_type=Job, success_redirect='job', thankyou_redirect='job.thank_you'):

    require_payment = get_setting('module', 'jobs',
                                    'jobsrequirespayment')

    can_add_active = has_perm(request.user, 'jobs.add_job')

    content_type = get_object_or_404(
        ContentType,
        app_label=object_type._meta.app_label,
        model=object_type._meta.model_name
    )

    if request.user.profile.is_superuser:
        category_form_class = CategoryForm
    else:
        category_form_class = CategoryForm2

    form = form_class(request.POST or None, request.FILES or None, user=request.user)
    # adjust the fields depending on user type
    if not require_payment:
        del form.fields['payment_method']
        del form.fields['list_type']

    if request.method == "POST":
        if require_payment:
            is_free = is_free_listing(request.user,
                               request.POST.get('pricing', 0),
                               request.POST.get('list_type'))
            if is_free:
                del form.fields['payment_method']

        categoryform = category_form_class(
                        content_type,
                        request.POST,)

        if form.is_valid() and categoryform.is_valid():
            job = form.save(commit=False)
            pricing = form.cleaned_data['pricing']

            if require_payment and is_free:
                job.payment_method = 'paid - cc'

            # set it to pending if the user is anonymous or not an admin
            if not can_add_active:
                #job.status = 1
                job.status_detail = 'pending'

            # list types and duration
            if not job.requested_duration:
                job.requested_duration = 30
            if not job.list_type:
                job.list_type = 'regular'

            # set up all the times
            now = datetime.now()
            job.activation_dt = now
            if not job.post_dt:
                job.post_dt = now

            # set the expiration date
            job.expiration_dt = job.activation_dt + timedelta(
                                        days=job.requested_duration)

            # semi-anon job posts don't get a slug field on the form
            # see __init__ method in JobForm
            if not job.slug:
                #job.slug = get_job_unique_slug(slugify(job.title))
                job.slug = '%s-%s' % (slugify(job.title),
                                        object_type.objects.count())

            job = update_perms_and_save(request, form, job)

            # create invoice
            job_set_inv_payment(request.user, job, pricing)

            #setup categories
            category = Category.objects.get_for_object(job, 'category')
            sub_category = Category.objects.get_for_object(
                                                job, 'sub_category')

            ## update the category of the job
            category_removed = False
            category = categoryform.cleaned_data['category']
            if category != '0':
                Category.objects.update(job, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(job, 'category')
                Category.objects.remove(job, 'sub_category')

            if not category_removed:
                # update the sub category of the job
                sub_category = categoryform.cleaned_data['sub_category']
                if sub_category != '0':
                    Category.objects.update(job, sub_category,
                                                'sub_category')
                else:  # remove
                    Category.objects.remove(job,'sub_category')

            #save relationships
            job.save()
            msg_string = 'Successfully added %s' % job
            messages.add_message(request, messages.SUCCESS,_(msg_string))

            # send notification to administrators
            recipients = get_notice_recipients(
                            'module', 'jobs', 'jobrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': job,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'job_added',
                                                extra_context)

            # send user to the payment page if payment is required
            if require_payment:
                if job.payment_method.lower() in ['credit card', 'cc']:
                    if job.invoice and job.invoice.balance > 0:
                        return HttpResponseRedirect(reverse(
                            'payment.pay_online',
                            args=[job.invoice.id, job.invoice.guid])
                        )

            # send user to thank you or view page
            if request.user.profile.is_superuser:
                return HttpResponseRedirect(
                        reverse(success_redirect, args=[job.slug]))
            else:
                return HttpResponseRedirect(reverse(thankyou_redirect))
    else:
        # Redirect user w/perms to create pricing if none exist
        pricings = JobPricing.objects.all()
        if not pricings and has_perm(request.user, 'jobs.add_jobpricing'):
            msg_string = 'You need to add a %s Pricing before you can add a %s.' % (get_setting('module', 'jobs', 'label_plural'),get_setting('module', 'jobs', 'label'))
            messages.add_message(request, messages.WARNING, _(msg_string))
            return HttpResponseRedirect(reverse('job_pricing.add'))

        initial_category_form_data = {
            'app_label': 'jobs',
            'model': 'job',
            'pk': 0, #not used for this view but is required for the form
        }
        categoryform = category_form_class(
                        content_type,
                        initial=initial_category_form_data,)

    return render_to_response(template_name,
            {'form': form,
             'require_payment': require_payment,
             'categoryform': categoryform},
            context_instance=RequestContext(request))

Example 12

Project: tendenci Source File: views.py
@ssl_required
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             event_id=None,
             extra_context=None):
    """
    Allow a new user to register an account.

    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.

    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).

    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.

    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.

    **Required arguments**

    None.

    **Optional arguments**

    ``form_class``
        The form class to use for registration.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.

    ``success_url``
        The URL to redirect to on successful registration.

    ``template_name``
        A custom template to use.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    # check if this site allows self registration, if not, redirect to login page
    allow_self_registration = get_setting('module', 'users', 'selfregistration')
    if not allow_self_registration:
        return HttpResponseRedirect(reverse('auth_login'))

    form_params = {}
    if request.session.get('form_params', None):
        form_params = request.session.pop('form_params')

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES, **form_params)
        if form.is_valid():
            # This is for including a link in the reg email back to the event viewed
            event = None
            if event_id: # the user signed up via an event
                from tendenci.apps.events.models import Event
                event = get_object_or_404(Event, pk=event_id)

            new_user = form.save(profile_callback=profile_callback, event=event)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.

            # add to the default group(s)
            default_user_groups =[g.strip() for g in (get_setting('module', 'users', 'defaultusergroup')).split(',')]
            if default_user_groups:
                from tendenci.apps.user_groups.models import Group, GroupMembership
                from django.db.models import Q
                for group_name in default_user_groups:
                    groups = Group.objects.filter(Q(name=group_name) | Q(label=group_name)).filter(allow_self_add=1, status=1, status_detail='active')
                    if groups:
                        group = groups[0]
                    else:
                        # group doesnot exist, so create the group
                        group = Group()
                        group.name  = group_name
                        group.label = group_name
                        group.type = 'distribution'
                        group.show_as_option = 1
                        group.allow_self_add = 1
                        group.allow_self_remove = 1
                        group.creator = new_user
                        group.creator_username = new_user.username
                        group.owner =  new_user
                        group.owner_username = new_user.username
                        try:
                            group.save()
                        except:
                            group = None

                    if group:
                        gm = GroupMembership()
                        gm.group = group
                        gm.member = new_user
                        gm.creator_id = new_user.id
                        gm.creator_username = new_user.username
                        gm.owner_id =  new_user.id
                        gm.owner_username = new_user.username
                        gm.save()


            EventLog.objects.log(instance=new_user)

            return HttpResponseRedirect(success_url or reverse('registration_complete'))
        elif form.similar_email_found:
            messages.add_message(
                request, messages.INFO,
                _(u"An account already exists for the email %(email)s." % {
                    'email': request.POST.get('email_0') or request.POST.get('email_1')}))

            querystring = 'registration=True'
            return HttpResponseRedirect(reverse('auth_password_reset')+ "?%s" % querystring)

    else:
        allow_same_email = request.GET.get('registration_approved', False)
        form_params = {'allow_same_email' : allow_same_email }
        request.session['form_params'] = form_params
        form = form_class(**form_params)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 13

Project: coursys Source File: view_instructors.py
@requires_role('PLAN')
def view_instructors(request, semester, plan_slug, planned_offering_slug):
    semester_plan = get_object_or_404(SemesterPlan, semester__name=semester, slug=plan_slug)
    planned_offering = get_object_or_404(PlannedOffering, slug=planned_offering_slug)

    all_instructors = Person.objects.filter(role__role__in=["FAC", "SESS", "COOP"], role__unit=semester_plan.unit)
    capable_instructors = all_instructors.filter(teachingcapability__course__plannedoffering=planned_offering)
    all_instructors = all_instructors.exclude(teachingcapability__course__plannedoffering=planned_offering)

    if request.method == 'POST':
        semester_plan = get_object_or_404(SemesterPlan, semester__name=semester, slug=plan_slug)
        course = get_object_or_404(PlannedOffering, slug=planned_offering_slug, plan=semester_plan)

        no_intention_note = "Added by planned administrator. Instructor posted no previous semester teaching intentions."

        instructor_id = request.POST['instructor']
        if instructor_id == "None":
            pre_instructor = course.instructor
            course.instructor = None
            course.save()

            offering_section = course.section[0:2]
            labs = PlannedOffering.objects.filter(plan=semester_plan, course=course.course, component__in=['LAB', 'TUT'], section__startswith=offering_section)
            for lab in labs:
                lab.instructor = None
                lab.save()

            pre_intention_count = PlannedOffering.objects.filter(plan=semester_plan, instructor=pre_instructor).count()
            pre_teaching_intention = TeachingIntention.objects.get(semester=semester_plan.semester, instructor=pre_instructor)

            if pre_teaching_intention.note == no_intention_note:
                pre_teaching_intention.delete()
            else:
                pre_teaching_intention.intentionfull = (pre_intention_count >= pre_teaching_intention.count)
                pre_teaching_intention.save()

            messages.add_message(request, messages.SUCCESS, 'Instructor removed successfully.')
            return HttpResponseRedirect(reverse(update_plan, kwargs={'semester': semester_plan.semester.name, 'plan_slug': semester_plan.slug}))

        #instructor_id is not None
        assigned_instructor = get_object_or_404(Person, userid=instructor_id)

        if course.instructor:
            pre_instructor = course.instructor
        else:
            pre_instructor = None

        course.instructor = assigned_instructor
        course.save()

        offering_section = course.section[0:2]
        labs = PlannedOffering.objects.filter(plan=semester_plan, course=course.course, component__in=['LAB', 'TUT'], section__startswith=offering_section)
        for lab in labs:
            lab.instructor = assigned_instructor
            lab.save()

        if pre_instructor != None:
            pre_intention_count = PlannedOffering.objects.filter(plan=semester_plan, instructor=pre_instructor).count()
            pre_teaching_intention = TeachingIntention.objects.get(semester=semester_plan.semester, instructor=pre_instructor)

            if pre_teaching_intention.note == no_intention_note:
                pre_teaching_intention.delete()
            else:
                pre_teaching_intention.intentionfull = (pre_intention_count >= pre_teaching_intention.count)
                pre_teaching_intention.save()

        intention_count = PlannedOffering.objects.filter(plan=semester_plan, instructor=assigned_instructor).count()
        if TeachingIntention.objects.filter(semester=semester_plan.semester, instructor=assigned_instructor):
            teaching_intentions = TeachingIntention.objects.filter(semester=semester_plan.semester, instructor=assigned_instructor)
            teaching_intention = teaching_intentions[0]

            teaching_intention.intentionfull = (intention_count >= teaching_intentions.count)
            teaching_intention.save()

            messages.add_message(request, messages.SUCCESS, 'Instructor assinged successfully.')
            return HttpResponseRedirect(reverse(update_plan, kwargs={'semester': semester_plan.semester.name, 'plan_slug': semester_plan.slug}))

        else:
            add_intention = TeachingIntention(instructor=assigned_instructor, semester=semester_plan.semester, count=1, intentionfull=True, note=no_intention_note)
            add_intention.save()
            messages.add_message(request, messages.WARNING, 'There is no intention for this instructor.')
            return HttpResponseRedirect(reverse(update_plan, kwargs={'semester': semester_plan.semester.name, 'plan_slug': semester_plan.slug}))

    capable_instructors_list = []
    for i in capable_instructors:
        capable_instructors_list.append({
            'instructor': i,
            'intention': TeachingIntention.objects.filter(instructor=i).order_by('semester'),
            'teachable': TeachingCapability.objects.filter(instructor=i).order_by('course'),
            'current_courses': PlannedOffering.objects.filter(plan=semester_plan, instructor=i, component="LEC")
        })

    all_instructors_list = []
    for i in all_instructors:
        all_instructors_list.append({
            'instructor': i,
            'intention': TeachingIntention.objects.filter(instructor=i).order_by('semester'),
            'teachable': TeachingCapability.objects.filter(instructor=i).order_by('course'),
            'current_courses': PlannedOffering.objects.filter(plan=semester_plan, instructor=i, component="LEC")
        })

    return render_to_response("planning/view_instructors.html", {'semester_plan': semester_plan, 'capable_instructors_list': capable_instructors_list, 'all_instructors_list': all_instructors_list, 'planned_offering': planned_offering}, context_instance=RequestContext(request))

Example 14

Project: hubplus Source File: views.py
@secure_resource(TgGroup)
def group(request, group, template_name="plus_groups/group.html", current_app='plus_groups', **kwargs):

    if not group :
        raise Http404(_('There is no group with this id'))

    user = request.user

    can_join = False
    apply = False
    leave = False
    invite = False
    can_comment = False
    message = False
    add_link = False
    can_tag = False
    can_change_avatar = False
    has_accept = False
    can_delete = False

    is_following = Following.objects.is_following(request.user, group.get_inner())

    editable_group_type = group.group_type != settings.GROUP_HUB_TYPE

    if user.is_authenticated():
        if user.is_direct_member_of(group.get_inner()):
            # can now leave group if you aren't the last one out
            if group.get_no_members() > 1 :
                leave = True
            try :
                group.invite_member
                invite = True
            except Exception, e :# user doesn't have invite permission
                pass

        else :
            try :
                group.join 
                can_join = True
            except Exception, e: # user doesn't have join permission
                pass
            try :
                if not can_join :
                    group.apply
                    apply = True
            except Exception, e : # user doesn't have apply permission
                pass

        try : 
            group.comment
            can_comment = True
            can_tag = True # XXX commentor interface governs who can tag. Do we need a special tag interface?
        except :
            pass


        try :
            group.message_members
            message = True
        except :
            pass
        
        try :
            group.create_Link
            add_link = True
        except Exception, e :
            print e
            pass

        try :
            group.change_avatar
            can_change_avatar  = True
        except Exception, e:
            pass

        try :
            dummy = group.delete
            can_delete = True
        except :
            pass

        if has_access(request.user, None, 'Application.Accept', group._inner.get_security_context()):
            has_accept = True
        else:
            has_accept = False
    
    tweets = FeedItem.feed_manager.get_from_permissioned(group, request.user)

    try:
        group.get_all_sliders
        perms_bool = True
    except PlusPermissionsNoAccessException:
        perms_bool = False

    if kwargs['type'] == 'hub':
        type_name = hub_name()
    else:
        type_name = "Group"

    search_types = narrow_search_types(type_name)
    side_search = side_search_args(current_app + ':groups', search_types[0][1][2])

    search = request.GET.get('search', '')
    order = request.GET.get('order', '')
    resource_search = resources(group=group, search=search, order=order)
    resource_listing_args = listing_args(current_app + ':group_resources', current_app + ':group_resources_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='resources')
    resource_listing_args['group_id'] = group.id

    ##############Here we should use the "plus_search" function from plus_explore as above########

    member_search = a_member_search(group=group, search=search, order=order, 
                                    member_profile_ids=[x.get_profile().get_ref().id for x in group.users.all()])
    host_search = a_member_search(group=group.get_admin_group(), search=search, order=order, 
                                  member_profile_ids=[x.get_profile().get_ref().id for x in group.get_admin_group().users.all()])
    member_listing_args = listing_args(current_app+':group_members', current_app+':group_members_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='members', group_id=group.id)

    host_listing_args = listing_args(current_app+':group_hosts', current_app+':group_hosts_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='hosts', group_id=group.id)
    member_count = group.users.all().count()
    host_count = group.get_admin_group().users.all().count()


    ##############################################################################################

    return render_to_response(template_name, {
            "head_title" : "%s" % group.get_display_name(),
            "status_type" : 'group',
            #"status_since" : status_since,
            "group" : TemplateSecureWrapper(group),
            "target_class" : ContentType.objects.get_for_model(group.get_inner()).id,
            "target_id" : group.get_inner().id,
            #"members" : members,
            "member_count" : member_count,
            "leave": leave,
            "can_join" : can_join, 
            "apply" : apply, 
            "invite" : invite, 
            "can_comment" : can_comment, 
            "message" : message,
            "add_link" : add_link,
            "can_tag" : can_tag,
            "can_change_avatar" : can_change_avatar,
            "can_delete" : can_delete, 

            "is_following" : is_following,
            #"hosts": hosts,
            "host_group_id":group.get_admin_group().id,
            "host_group_app_label":group.get_admin_group().group_app_label() + ':group',
            "is_host":user.is_admin_of(group.get_inner()),
            "host_count": host_count,
            "tweets" : tweets,
            "permissions": perms_bool,
            'side_search_args':side_search,
            'resource_search':resource_search,
            'resource_listing_args':resource_listing_args,
            'member_search':member_search,
            'member_listing_args':member_listing_args,
            'host_search':host_search,
            'host_listing_args':host_listing_args,
            'group_id':group.id,
            'search_types':search_types,
            'tagged_url':current_app + ':groups_tag',
            'has_accept':has_accept,
            'editable_group_type':editable_group_type,
            }, context_instance=RequestContext(request, current_app=current_app)
    )

Example 15

Project: classic.rhizome.org Source File: admin.py
    def url_inventory(self, request):
        '''
        creates a csv file compiling the http status of artbase artworks and their urls and locations
        
        '''
        context_instance = RequestContext(request)
        opts = self.model._meta
        admin_site = self.admin_site
        completed_message = None

        writer = csv.writer(open(os.path.join(settings.MEDIA_ROOT, "artbase/data/artbase_broken_urls_inventory_%s.csv" \
            % datetime.date.today(), "wb")))
                
        writer.writerow(['ARTWORK ID', 'ARTWORK TITLE', 'ARTWORK URL', 'URL STATUS', 'LOCATION', 'LOCATION STATUS','UPDATE NOTICE']) 
        all_works = ArtworkStub.objects.filter(status="approved")

        handler = urllib2.UnknownHandler()
        opener = urllib2.build_opener(handler)
        urllib2.install_opener(opener)    
        
        # timeout in seconds
        timeout = 15
        socket.setdefaulttimeout(timeout)
        
        if request.method == "POST":
            if request.POST.get("run_inventory"):
                for work in all_works:   
                    url_response = None
                    url_error_msg = None
                    url_status = None
                    location_response = None
                    location_status = None
                    location_error_msg = None
                    updating_notice = None
            
                    #a few hacks to make sure the url is formatted correctly
                    if "/artbase/" in work.url:
                        if "http://archive.rhizome.org" not in work.url:
                            if "http://" not in work.url:
                                work.url = "http://archive.rhizome.org%s" % work.url
                                updating_notice = "Make sure has full rhizome archives url (http://archive.rhizome.org/....)"
        
                    if "/artbase/" in work.location:
                        if "http://archive.rhizome.org" not in work.location:
                            if "http://" not in work.location:
                                work.location = "http://archive.rhizome.org%s" % work.location
                                updating_notice = "Make sure has full rhizome archives url (http://archive.rhizome.org/....)"
                    if "http://" not in work.url:
                        work.url = "http://%s" % work.url
                        updating_notice = "Make sure has url including 'http://'"
        
                    if "http://" not in work.location:
                        work.location = "http://%s" % work.location
                        updating_notice = "Make sure has url including 'http://'"
                             
                    try:
                        url_response = urllib2.urlopen(work.url, timeout = 15)
                    except (urllib2.URLError, httplib.BadStatusLine, httplib.InvalidURL, httplib.HTTPException,httplib.UnknownProtocol), e:
                        if hasattr(e, 'reason'):
                                if isinstance(e.reason, socket.timeout):
                                    url_error_msg = 'Failed to reach server. TIMED OUT '
                                else:
                                    url_error_msg = 'Failed to reach server. Reason: %s ' % e.reason
                        elif hasattr(e, 'code'):
                            url_error_msg = "The server couldn't fulfill the request. Error code: %s" % e.code
                        else:
                            url_error_msg = "Failed to reach server!"                    
                    except:
                        url_error_msg = "Failed to reach server!"
                          
                    if url_response:
                        url_status = "SUCCESS"
                    else:
                        url_status = url_error_msg
                    
                    
                    if work.location:
                        try:
                            location_response = urllib2.urlopen(work.location, timeout = 15)
                        except (urllib2.URLError, httplib.BadStatusLine, httplib.InvalidURL, \
                                httplib.HTTPException,httplib.UnknownProtocol), e:
                            if hasattr(e, 'reason'):
                                if isinstance(e.reason, socket.timeout):
                                    url_error_msg = 'Failed to reach server. TIMED OUT '
                                else:
                                    location_error_msg = 'Failed to reach a server. Reason: %s ' % e.reason
                            elif hasattr(e, 'code'):
                                location_error_msg = "The server couldn't fulfill the request. Error code: %s" % e.code
                            else:
                                location_error_msg = "Failed to reach server!"
                    
                    if location_response:
                        location_status = "SUCCESS"
                    else:
                        location_status = location_error_msg
                 
                    if location_error_msg or url_error_msg and not updating_notice:
                        updating_notice = "This work has broken links"                 
                    
                    if updating_notice:
                        writer.writerow([    
                            "%s" % work.id,
                            "%s" % work.title,
                            "%s" % work.url,
                            "%s" % url_status,
                            "%s" % work.location,
                            "%s" % location_status,
                            "%s" % updating_notice,
                        ])
                        
                report_email = EmailMessage('ArtBase Broken URLs Inventory Report', 'Report Attached.', settings.ARTBASE_GROUP_EMAIL,
                                            [settings.ARTBASE_GROUP_EMAIL], headers = {'Reply-To': settings.ARTBASE_GROUP_EMAIL})  
                    
                report_email.attach('artbase_broken_urls_inventory_%s.csv' % datetime.date.today(), writer, 'text/csv')
                report_email.send()
                
                completed_message = True
            
        d = {'admin_site': admin_site.name, 
             'title': "Inventory Broken Artwork URLS", 
             'opts': "Artworks", 
             'app_label': opts.app_label,
             "completed_message":completed_message
             }
             
        return render_to_response('admin/artbase/url_inventory.html', d, context_instance)                

Example 16

Project: treeio Source File: reports.py
@contextfunction
def display_chart(context, chart, skip_group=False):
    "Return HTML for chart"

    request = context['request']

    response_format = 'html'
    if 'response_format' in context:
        response_format = context['response_format']

    options = loads(chart.options)

    content = _get_report_content(chart.report, request)

    objs = content['set']

    chart_dict = {}

    field_name = options['grouping']

    model = loads(chart.report.model)

    chart_dict['yAxis'] = {'allowDecimals': False,
                           'title': {
                               'text': model.name.split('.')[-1] + " Count vs. " + field_name.replace('_', ' ').title()}
                           }
    chart_dict['xAxis'] = {}
    try:
        xfield = objs[0]._meta.get_field_by_name(field_name)[0]
    except:
        chart.delete()
        return

    def get_date(g, mindate):
        if g and g != datetime.min.date():
            return g
        else:
            return mindate

    if xfield.get_internal_type() == 'ManyToManyField':
        l = []
        for obj in objs:
            for mi in getattr(obj, field_name).all():
                l.append(unicode(mi))
    elif xfield.get_internal_type() == 'DateTimeField' or xfield.get_internal_type() == 'DateField':
        chart_dict['xAxis']['labels'] = {  # 'rotation':90,
                                           'align': 'left',
                                           'x': 3,
                                           'y': 15}
        l, m, datelist = [], [], []
        maxdate = None
        mindate = None
        for obj in objs:
            if getattr(obj, field_name):
                x = getattr(obj, field_name)
                if xfield.get_internal_type() == 'DateTimeField':
                    x = x.date()
                if not maxdate or x > maxdate:
                    maxdate = x
                if not mindate or x < mindate:
                    mindate = x
                datelist.append(x)
                if unicode(x) not in m:
                    m.append(unicode(x))
            else:
                datelist.append(datetime.min.date())
        while datetime.min.date() in datelist:
            datelist.append(mindate)
            datelist.remove(datetime.min.date())
        datelist = sorted(datelist, key=lambda g: get_date(g, mindate))
        l = [unicode(g) for g in datelist]

        # chart_dict['xAxis']['categories']=m

        chart_dict['xAxis']['type'] = 'datetime'
        td = maxdate - mindate
        # print (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
        chart_dict['zoomType'] = 'x'
        chart_dict['xAxis']['tickInterval'] = (
                                                  td.microseconds + (
                                                      td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 4
        # chart_dict['xAxis']['tickWidth']= 0,
        chart_dict['maxZoom'] = 14 * 24 * 3600000  # 2wks
        # chart_dict['xAxis']['gridLineWidth']= 1,
        chart_dict['series'] = [{'name': model.name.split('.')[-1], 'data': []}]
        for x in set(l):
            chart_dict['series'][0]['data'].append(('%s UTC' % x, l.count(x)))

    else:
        l = [unicode(obj.get_field_value(field_name)) for obj in objs]

    if 'series' not in chart_dict:
        chart_dict['series'] = []
        # chart_dict['series'].append({'name':field_name, 'data': [{'name': x, 'y':l.count(x)} for x in set(l)]})
        chart_dict['series'].append({'name': field_name.replace(
            '_', ' ').title(), 'data': [[x, l.count(x)] for x in set(l)]})
        # for x in set(l):
        # chart_dict['series'].append({'name':x, 'data': l.count(x)})
        # chart_dict['series'].append({'data':[{'name':x, 'y': [l.count(x)]} for x in set(l)]})
        if 'xAxis' not in chart_dict:
            chart_dict['xAxis']['categories'] = [x for x in set(l)]
        # Chart type specific options

        if 'legend' in options and options['legend'] == 'on':
            chart_dict['legend'] = {
                'layout': 'vertical',
                'align': 'right',
                'verticalAlign': 'top',
                'x': -10,
                'y': 100,
                'borderWidth': 0
            }
    if 'title' in options:
        chart_dict['title'] = {'text': options['title']}

    # Create a hash and use it as a unqiue div id and var name for the chart.
    hasher = hashlib.md5()
    hasher.update(str(random()))
    id = 'chartcontainer' + str(hasher.hexdigest())
    # Disable animation for when saving as PDF
    chart_dict['chart'] = {'renderTo': id,
                           'defaultSeriesType': options['type']}
    # chart_dict['plotOptions'] = {'series': {'animation': False}}

    chart_dict['plotOptions'] = {'pie': {
        'allowPointSelect': True,
        'cursor': 'pointer',
        'dataLabels': {
            'enabled': False
        },
        'showInLegend': True
    }}

    chart_dict['credits'] = {'enabled': False}

    rendered_options = json.dumps(chart_dict)

    rendered_options = rendered_options[
                       :-1] + ", tooltip: {formatter: function() {return '<b>'+ this.point.name +'</b>: '+ this.y;}}}"

    if 'type' in chart_dict['xAxis'] and chart_dict['xAxis']['type'] == 'datetime':
        rendered_options += """
        datedata = [];
        jQuery.each(options.series[0].data, function(i,item){
        date = Date.parse(item[0]);
        count = item[1];
        datedata.push([date, count]);
        });
      options.series[0].data = datedata;

      function merge_options(obj1,obj2){
        var obj3 = {};
        for (attrname in obj1) { obj3[attrname] = obj1[attrname]; }
        for (attrname in obj2) { obj3[attrname] = obj2[attrname]; }
        return obj3;
      }
      var dateoptions =  {


      tooltip: {
         shared: true,
         crosshairs: true

      },

      };


    options = merge_options(options, dateoptions);

              """

    return Markup(render_to_string('reports/tags/chart',
                                   {'rendered_options': rendered_options,
                                    'id': id,
                                    'chart_id': chart.id,
                                    'chart': chart,
                                    'name': options['title']},
                                   context_instance=RequestContext(request),
                                   response_format=response_format))

Example 17

Project: splunk-webframework Source File: comments.py
@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    return next_redirect(request, fallback=next or 'comments-comment-done',
        c=comment._get_pk_val())

Example 18

Project: syndication-view Source File: views.py
    def get_feed(self, obj, request):
        """
        Returns a feedgenerator.DefaultFeed object, fully populated, for
        this feed. Raises FeedDoesNotExist for invalid parameters.
        """
        if Site._meta.installed:
            current_site = Site.objects.get_current()
        else:
            current_site = RequestSite(request)

        link = self.__get_dynamic_attr('link', obj)
        link = add_domain(current_site.domain, link)

        feed = self.feed_type(
            title = self.__get_dynamic_attr('title', obj),
            subtitle = self.__get_dynamic_attr('subtitle', obj),
            link = link,
            description = self.__get_dynamic_attr('description', obj),
            language = settings.LANGUAGE_CODE.decode(),
            feed_url = add_domain(current_site.domain,
                    self.__get_dynamic_attr('feed_url', obj) or request.path),
            author_name = self.__get_dynamic_attr('author_name', obj),
            author_link = self.__get_dynamic_attr('author_link', obj),
            author_email = self.__get_dynamic_attr('author_email', obj),
            categories = self.__get_dynamic_attr('categories', obj),
            feed_copyright = self.__get_dynamic_attr('feed_copyright', obj),
            feed_guid = self.__get_dynamic_attr('feed_guid', obj),
            ttl = self.__get_dynamic_attr('ttl', obj),
            **self.feed_extra_kwargs(obj)
        )

        title_tmp = None
        if self.title_template is not None:
            try:
                title_tmp = loader.get_template(self.title_template)
            except TemplateDoesNotExist:
                pass

        description_tmp = None
        if self.description_template is not None:
            try:
                description_tmp = loader.get_template(self.description_template)
            except TemplateDoesNotExist:
                pass

        for item in self.__get_dynamic_attr('items', obj):
            if title_tmp is not None:
                title = title_tmp.render(RequestContext(request, {'obj': item, 'site': current_site}))
            else:
                title = self.__get_dynamic_attr('item_title', item)
            if description_tmp is not None:
                description = description_tmp.render(RequestContext(request, {'obj': item, 'site': current_site}))
            else:
                description = self.__get_dynamic_attr('item_description', item)
            link = add_domain(current_site.domain, self.__get_dynamic_attr('item_link', item))
            enc = None
            enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
            if enc_url:
                enc = feedgenerator.Enclosure(
                    url = smart_unicode(enc_url),
                    length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)),
                    mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item))
                )
            author_name = self.__get_dynamic_attr('item_author_name', item)
            if author_name is not None:
                author_email = self.__get_dynamic_attr('item_author_email', item)
                author_link = self.__get_dynamic_attr('item_author_link', item)
            else:
                author_email = author_link = None

            pubdate = self.__get_dynamic_attr('item_pubdate', item)
            if pubdate and not pubdate.tzinfo:
                ltz = tzinfo.LocalTimezone(pubdate)
                pubdate = pubdate.replace(tzinfo=ltz)

            feed.add_item(
                title = title,
                link = link,
                description = description,
                unique_id = self.__get_dynamic_attr('item_guid', item, link),
                enclosure = enc,
                pubdate = pubdate,
                author_name = author_name,
                author_email = author_email,
                author_link = author_link,
                categories = self.__get_dynamic_attr('item_categories', item),
                item_copyright = self.__get_dynamic_attr('item_copyright', item),
                **self.item_extra_kwargs(item)
            )
        return feed

Example 19

Project: dirigible-spreadsheet Source File: views.py
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.
    
    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.
    
    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).
    
    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.
    
    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.
    
    **Required arguments**
    
    None.
    
    **Optional arguments**
    
    ``form_class``
        The form class to use for registration.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.
    
    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.
    
    ``success_url``
        The URL to redirect to on successful registration.
    
    ``template_name``
        A custom template to use.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = form.save(profile_callback=profile_callback)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.
            return HttpResponseRedirect(success_url or reverse('registration_complete'))
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 20

Project: foodnetwork Source File: views.py
@login_required
def planning_table(request, member_id, list_type, from_date, to_date):
    try:
        member = Party.objects.get(pk=member_id)
    except Party.DoesNotExist:
        raise Http404
    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":
        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:
                            if not qty == plan.quantity:
                                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,
                            )
                            new_plan.save()
                            if role == "producer":
                                listed_product, created = ProducerProduct.objects.get_or_create(
                                    product=product, producer=member)
                            #elif role == "consumer":
                            #    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:
                                plan.delete()
                            else:
                                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/'
                    % ('producer/producerplans', 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': "producer/producer_tabnav.html",
        }, context_instance=RequestContext(request))

Example 21

Project: syndicate Source File: views.py
@verifyownership_private
@authenticate
def deletevolume(request, volume_id):
    '''
    View for deleting volumes. Since so many other entites have properties related
    to volume ID's, numerous db updates need to be checked. CQ, they are all grouped
    together into the transactional helper method multi_update().
    '''

    # Clear out volume_id in properties for users, UG's, AG's, and RG's.
    @transactional(xg=True)
    def multi_update(vol, users, usergateways, acquisitiongateways, replicagateways):
        v_id = vol.volume_id
        db.delete_volume(v_id)
        logging.info(users)

        for user in users:
            fields = {}

            if v_id in user.volumes_o:
                new_volumes_o = user.volumes_o
                new_volumes_o.remove(v_id)
                fields['volumes_o'] = new_volumes_o

            if v_id in user.volumes_rw:
                new_volumes_rw = user.volumes_rw
                new_volumes_rw.remove(v_id)
                fields['volumes_rw'] = new_volumes_rw

            if v_id in user.volumes_r:
                new_volumes_r = user.volumes_r
                new_volumes_r.remove(v_id)
                fields['volumes_r'] = new_volumes_r

            if fields:
                db.update_user(user.email, **fields)


        for ug in usergateways:
            fields = {}
            fields['volume_id'] = 0
            db.update_user_gateway(ug.g_id, **fields)

        for ag in acquisitiongateways:
            logging.info(ag)
            fields = {}
            new_ids = ag.volume_ids.remove(v_id)
            if not new_ids:
                fields['volume_ids'] = []
            else:
                fields['volume_ids'] = new_ids
            db.update_acquisition_gateway(ag.g_id, **fields)

        for rg in replicagateways:
            fields = {}
            new_ids = rg.volume_ids.remove(v_id)
            if not new_ids:
                fields['volume_ids'] = []
            else:
                fields['volume_ids'] = new_ids
            db.update_replica_gateway(rg.g_id, **fields)

        # Clear initial data session variable to prevent stale tables in ag.views.viewgateway and rg.views.viewgateway
        session.pop("rg_initial_data" + str(v_id), None)
        session.pop("ag_initial_data" + str(v_id), None)
        # Clear initial data session variable to prevent stale data in volume settings, change rgs, and change ags.
        session.pop("volume_initial_ags" + str(v_id), None)
        session.pop("volume_initial_rgs" + str(v_id), None)

    session = request.session
    message = session.pop('message', "")
    username = session['login_email']
    vol = db.read_volume( volume_id )
    if not vol:
        return redirect('django_volume.views.viewvolume', volume_id)

    if request.method == "POST":
        form = forms.DeleteVolume(request.POST)
        if form.is_valid():
            # Check password hash
            hash_check = Volume.generate_password_hash(form.cleaned_data['password'], vol.volume_secret_salt)
            if hash_check == vol.volume_secret_salted_hash:
                # Ok to delete
                attrs = {}
                users = db.list_users({'SyndicateUser.volumes_rw ==':vol.volume_id})
                users.extend(db.list_users({'SyndicateUser.volumes_r ==':vol.volume_id}))
                ags = db.list_acquisition_gateways_by_volume(vol.volume_id)
                rgs = db.list_replica_gateways_by_volume(vol.volume_id)
                ugs = db.list_user_gateways_by_volume(vol.volume_id)
                try:
                    multi_update(vol, users, ugs, ags, rgs)
                except Exception as e:
                     logging.error("Unable to delete volume %s" % e)
                     session['message'] = "Unable to delete volume."
                     return redirect('django_volume.views.deletevolume', volume_id=vol.volume_id)
                session['new_change'] = "We've deleted your volume."
                session['next_url'] = '/syn/volume/myvolumes/'
                session['next_message'] = "Click here to go back to your volumes."
                return redirect('/syn/thanks')
            else:
                session['message'] = "Invalid password"
                return redirect('django_volume.views.deletevolume', volume_id=vol.volume_id)
        else:
            session['message'] = "Please fill out all entries"
            return redirect('django_volume.views.deletevolume', vol.volume_id)
    else:
        form = forms.DeleteVolume()
        t = loader.get_template('deletevolume.html')
        c = RequestContext(request, {'username':username, 'form':form, 'message':message,'volume':vol} )
        return HttpResponse(t.render(c))    

Example 22

Project: jaikuenginepatch Source File: views.py
@alternate_nick
def actor_history(request, nick=None, format='html'):
  nick = clean.nick(nick)
  view = api.actor_lookup_nick(request.user, nick)

  if not view:
    raise exception.UserDoesNotExistError(nick, request.user)

  called_subscribe, sub_ref = common_views.call_api_from_request(
      request, 'subscription_request')
  if called_subscribe:
    if sub_ref.state == 'subscribed':
      message = 'Subscribed.'
    else:
      message = 'Subscription requested.'
    return util.RedirectFlash(view.url(), message)

  handled = common_views.handle_view_action(
      request,
      { 'entry_remove': request.path,
        'entry_remove_comment': request.path,
        'entry_mark_as_spam': request.path,
        'subscription_remove': view.url(),
        'actor_add_contact': request.path,
        'actor_remove_contact': request.path,
        'post': request.path,
        'presence_set': request.path,
      }
  )
  if handled:
    return handled

  privacy = 'public'
  if request.user and request.user.is_authenticated():
    if view.nick == request.user.nick:
      privacy = 'private'
    # ROOT because we care whether or not request.user is a contact of
    # the view user's, not whether the request.user can see the contacts
    elif api.actor_has_contact(api.ROOT, view.nick, request.user.nick):
      privacy = 'contacts'

  # we're going to hide a bunch of stuff if this user is private and we
  # aren't allowed to see
  user_is_private = False
  if view.privacy < models.PRIVACY_PUBLIC and privacy == 'public':
    user_is_private = True

  per_page = ENTRIES_PER_PAGE
  offset, prev = util.page_offset(request)

  if privacy == 'public':
    if user_is_private:
      inbox = []
    else:
      inbox = api.inbox_get_actor_public(request.user, view.nick,
                                         limit=(per_page + 1), offset=offset)
  elif privacy == 'contacts':
    inbox = api.inbox_get_actor_contacts(request.user, view.nick,
                                         limit=(per_page + 1), offset=offset)
  elif privacy == 'private':
    inbox = api.inbox_get_actor_private(request.user, view.nick,
                                        limit=(per_page + 1), offset=offset)

  actor_streams = api.stream_get_actor_safe(request.user, view.nick)

  entries, more = _get_inbox_entries(request, inbox)
  contacts, channels, streams, entries = _assemble_inbox_data(request,
                                                              entries,
                                                              actor_streams,
                                                              view)

  # If not logged in, cannot write
  is_owner = request.user and request.user.is_authenticated() and view.nick == request.user.nick

  try:
    presence = api.presence_get(request.user, view.nick)
    presence_stream = api.stream_get_presence(request.user, view.nick)
    last_entry = api.entry_get_last(request.user, presence_stream.keyname())
    view.last_entry = last_entry
  except exception.ApiException:
    pass


  # for add/remove contact
  if request.user and request.user.is_authenticated():
    user_is_contact = api.actor_has_contact(request.user,
                                            request.user.nick,
                                            view.nick)
    view.my_contact = user_is_contact
  else:
    user_is_contact = False

  # for sidebar streams
  view_streams = _get_sidebar_streams(actor_streams, streams, request.user)

  # for sidebar_contacts
  contacts_count = view.extra.get('contact_count', 0)
  contacts_more = contacts_count > CONTACTS_PER_PAGE

  # for sidebar channels
  channels_count = view.extra.get('channel_count', 0)
  channels_more = channels_count > CHANNELS_PER_PAGE

  # Config for the template
  green_top = True
  sidebar_green_top = True
  selectable_icons = display.SELECTABLE_ICONS
  area = 'user'

  c = template.RequestContext(request, locals())

  if format == 'html':
    t = loader.get_template('history.html')
    return http.HttpResponse(t.render(c))
  elif format == 'json':
    t = loader.get_template('history.json')
    r = util.HttpJsonResponse(t.render(c), request)
    return r
  elif format == 'atom':
    t = loader.get_template('history.atom')
    r = util.HttpAtomResponse(t.render(c), request)
    return r
  elif format == 'rss':
    t = loader.get_template('history.rss')
    r = util.HttpRssResponse(t.render(c), request)
    return r

Example 23

Project: Observatory Source File: projects.py
@login_required
def add(request):
  feed_repo_form = FeedRepositoryForm()
  cloned_repo_form = ClonedRepositoryForm()
  project_form = ProjectForm()
  blog_form = BlogForm()
  
  form_keys = {
    1: ('title', 'description', 'website', 'wiki'),
    2: ('web_url', 'clone_url', 'vcs', 'repo_rss', 'cmd'),
    3: ('url', 'rss')
  }
  
  if 'current' in request.POST:
    current = int(request.POST['current'])
  else:
    current = 0
  
  if current == 1:
    project_form = ProjectForm(request.POST)
    if not project_form.is_valid():
      current -= 1
  
  elif current == 2:
    if 'clone_url' in request.POST:
      cloned_repo_form = ClonedRepositoryForm(request.POST)
      if not cloned_repo_form.is_valid():
        current -= 1
    elif 'repo_rss' in request.POST:
      feed_repo_form = FeedRepositoryForm(request.POST)
      if not feed_repo_form.is_valid():
        current -= 1
  
  elif current == 3:
    blog_form = BlogForm(request.POST)
    if not ('url' not in request.POST or blog_form.is_valid()):
      current -= 1
  
  # go to the next form
  current += 1
  
  # if there are more parts to the form
  if current < 4:
    # remove the csrf token and current from a copy of the POST data
    post = request.POST.copy()
    if 'csrfmiddlewaretoken' in post:
      post.pop('csrfmiddlewaretoken')
      post.pop('current')

      # remove any of the keys that should be set on this form page
      for key in form_keys[current]:
        try:
          post.pop(key)
        except:
          pass
    
    return render_to_response('projects/add.html', {
        'parts': [1, 2, 3],
        'current': current,
        'previous_data': post,
        'cloned_repo_form': cloned_repo_form,
        'feed_repo_form': feed_repo_form,
        'project_form': project_form,
        'blog_form': blog_form,
        'js_page_id': 'add_project'
      }, context_instance = RequestContext(request))
  
  # otherwise, if the form is complete, create the project
  else:
    # validate and clean all forms
    project_form = ProjectForm(request.POST)
    cloned_repo_form = ClonedRepositoryForm(request.POST)
    feed_repo_form = FeedRepositoryForm(request.POST)
    blog_form = BlogForm(request.POST)
    
    for form in [project_form, cloned_repo_form, feed_repo_form, blog_form]:
      form.is_valid()
    
    # create the blog object
    if 'rss' in request.POST:
      blog = Blog(url = blog_form.cleaned_data['url'],
                  rss = blog_form.cleaned_data['rss'],
                  from_feed = True)
    else:
      blog = Blog(from_feed = False)
    blog.save()

    # create the repository object
    # if using google code removes read only addition
    # if git@ is mistakenly typed, git:// is placed in
    if 'clone_url' in request.POST:
      url = cloned_repo_form.cleaned_data['clone_url']
      gitfix = url.replace('git@', 'git://')
      url = gitfix
      if "google.com" in url:
        split = url.split(' ')
        url = split[0]

      repo = Repository(web_url = cloned_repo_form.cleaned_data['web_url'],
                        clone_url = url,
                        from_feed = False)
    else:
      repo = Repository(web_url = feed_repo_form.cleaned_data['web_url'],
                        repo_rss = feed_repo_form.cleaned_data['repo_rss'],
                        from_feed = True)
    repo.save()

    # create the project object
    project = Project(title = project_form.cleaned_data['title'],
                      website = project_form.cleaned_data['website'],
                      wiki = project_form.cleaned_data['wiki'],
                      description = project_form.cleaned_data['description'],
                      active = True,
                      repository_id = repo.id,
                      blog_id = blog.id,
					  pending = True)

    # get the project a primary key
    project.save()

    # associate the current user with the project as an author
    project.authors.add(request.user)

    # save the project again
    project.save()

    # Set the active flag as true
    project.active = True

    # Save the project again
    project.save()

    # redirect to the show page for the new project
    return HttpResponseRedirect(reverse(show, args = (project.url_path,)))

Example 24

Project: jaikuenginepatch Source File: views.py
@alternate_nick
def actor_settings(request, nick, page='index'):
  """ just a static page that links to the rest"""
  nick = clean.nick(nick)

  view = api.actor_lookup_nick(api.ROOT, nick)
  if not api.actor_owns_actor(request.user, view):
    raise exception.ApiException(exception.PRIVACY_ERROR,
                                 'Operation not allowed')

  handled = common_views.handle_view_action(
      request,
      {
        'activation_activate_mobile': view.url('/settings/mobile'),
        'activation_request_email': view.url('/settings/email'),
        'activation_request_mobile': view.url('/settings/mobile'),
        'settings_change_notify': view.url('/settings/notifications'),
        'settings_change_privacy': request.path,
        'settings_update_account': view.url('/settings/profile'),
        'actor_remove': '/logout',
        #'oauth_remove_consumer': request.path,
        #'oauth_remove_access_token': request.path
      }
  )
  if handled:
    return handled



  # TODO(tyler/termie):  This conflicts with the global settings import.
  # Also, this seems fishy.  Do none of the settings.* items work in templates?
  import settings

  # TODO(tyler): Merge this into handle_view_action, if possible
  if 'password' in request.POST:
    try:
      validate.nonce(request, 'change_password')

      password = request.POST.get('password', '')
      confirm = request.POST.get('confirm', '')

      validate.password_and_confirm(password, confirm, field = 'password')

      api.settings_change_password(request.user, view.nick, password)
      response = util.RedirectFlash(view.url() + '/settings/password',
                                    'Password updated')
      request.user.password = util.hash_password(request.user.nick, password)
      # TODO(mikie): change when cookie-auth is changed
      user.set_user_cookie(response, request, request.user)
      return response
    except:
      exception.handle_exception(request)

  if page == 'feeds':
    try:
      if not settings.FEEDS_ENABLED:
        raise exception.DisabledFeatureError('Feeds are currently disabled')
    except:
      exception.handle_exception(request)

  if page == 'photo':
    redirect_to = view.url() + '/settings/photo'
    handled = common_views.common_photo_upload(request, redirect_to)
    if handled:
      return handled


  area = 'settings'
  full_page = page.capitalize()

  if page == 'mobile':
    full_page = 'Mobile Number'

    mobile = api.mobile_get_actor(request.user, view.nick)
    sms_notify = view.extra.get('sms_notify', False)
    
  elif page == 'im':
    full_page = 'IM Address'
    im_address = api.im_get_actor(request.user, view.nick)
    im_notify = view.extra.get('im_notify', False)
  elif page == 'index':
    email = api.email_get_actor(request.user, view.nick)
    email_notify = view.extra.get('email_notify', False)
    im_address = api.im_get_actor(request.user, view.nick)
    im_notify = view.extra.get('im_notify', False)
  elif page == 'feeds':
    full_page = 'Web Feeds'
  elif page == 'email':
    full_page = 'Email Address'
    email_notify = view.extra.get('email_notify', False)

    # check if we already have an email
    email = api.email_get_actor(request.user, view.nick) 

    # otherwise look for an unconfirmed one
    if not email:
      unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
      if unconfirmeds:
        unconfirmed_email = unconfirmeds[0].content

  elif page == 'design':
    handled = common_views.common_design_update(request, view.nick)
    if handled:
      return handled
    full_page = 'Look and Feel'

  elif page == 'notifications':
    email = api.email_get_actor(request.user, view.nick)
    email_notify = view.extra.get('email_notify', False)
    im_address = api.im_get_actor(request.user, view.nick)
    im_notify = view.extra.get('im_notify', False)
    mobile = api.mobile_get_actor(request.user, request.user.nick)
    sms_notify = view.extra.get('sms_notify', False)

    sms_confirm = sms_notify and not view.extra.get('sms_confirmed', False)
    # TODO(termie): remove this once we can actually receive sms
    sms_confirm = False
  elif page == 'profile':
    # check if we already have an email
    email = api.email_get_actor(request.user, view.nick) 

    # otherwise look for an unconfirmed one
    if not email:
      unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
      if unconfirmeds:
        unconfirmed_email = unconfirmeds[0].content

  elif page == 'photo':
    avatars = display.DEFAULT_AVATARS
    small_photos = api.image_get_all_keys(request.user, view.nick, size='f')

    # TODO(tyler): Fix this avatar nonsense!
    own_photos = [{
        'path' : small_photo.key().name(),
        'name' : small_photo.key().name()[len('image/'):-len('_f.jpg')],
      } for small_photo in small_photos
    ]

  elif page == 'privacy':
    PRIVACY_PUBLIC = api.PRIVACY_PUBLIC
    PRIVACY_CONTACTS = api.PRIVACY_CONTACTS
  elif page == 'jsbadge':
    full_page = 'Javascript Badges'
  elif page == 'badge':
    badges = [{'id': 'badge-stream',
               'width': '200',
               'height': '300',
               'src': '%sglobal/themes/%s/badge.swf' % (settings.MEDIA_URL, settings.DEFAULT_THEME),
               'title': 'Stream',
               },
              {'id': 'badge-map',
               'width': '200',
               'height': '255',
               'src': '%sglobal/themes/%s/badge-map.swf' % (settings.MEDIA_URL, settings.DEFAULT_THEME),
               'title': 'Map',
               },
              {'id': 'badge-simple',
               'width': '200',
               'height': '200',
               'src': '%sglobal/themes/%s/badge-simple.swf' % (settings.MEDIA_URL, settings.DEFAULT_THEME),
               'title': 'Simple',
               },
              ]

  elif page in ['password', 'delete']:
    # Catch for remaining pages before we generate a 404.
    pass

  else:
    return common_views.common_404(request)

  # rendering
  c = template.RequestContext(request, locals())
  t = loader.get_template('settings_%s.html' % page)
  return http.HttpResponse(t.render(c))

Example 25

Project: django-adminactions Source File: merge.py
def merge(modeladmin, request, queryset):  # noqa
    """
    Merge two model instances. Move all foreign keys.

    """

    opts = modeladmin.model._meta
    perm = "{0}.{1}".format(opts.app_label, get_permission_codename('adminactions_merge', opts))
    if not request.user.has_perm(perm):
        messages.error(request, _('Sorry you do not have rights to execute this action'))
        return

    def raw_widget(field, **kwargs):
        """ force all fields as not required"""
        kwargs['widget'] = TextInput({'class': 'raw-value'})
        return field.formfield(**kwargs)

    merge_form = getattr(modeladmin, 'merge_form', MergeForm)
    MForm = modelform_factory(modeladmin.model,
                              form=merge_form,
                              exclude=('pk', ),
                              formfield_callback=raw_widget)
    OForm = modelform_factory(modeladmin.model,
                              exclude=('pk', ),
                              formfield_callback=raw_widget)

    tpl = 'adminactions/merge.html'
    # transaction_supported = model_supports_transactions(modeladmin.model)
    ctx = {
        '_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
        'transaction_supported': 'Un',
        'select_across': request.POST.get('select_across') == '1',
        'action': request.POST.get('action'),
        'fields': [f for f in queryset.model._meta.fields if not f.primary_key and f.editable],
        'app_label': queryset.model._meta.app_label,
        'result': '',
        'opts': queryset.model._meta}

    if 'preview' in request.POST:
        master = queryset.get(pk=request.POST.get('master_pk'))
        original = clone_instance(master)
        other = queryset.get(pk=request.POST.get('other_pk'))
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        with transaction.nocommit():
            form = MForm(request.POST, instance=master)
            other.delete()
            form_is_valid = form.is_valid()
        if form_is_valid:
            ctx.update({'original': original})
            tpl = 'adminactions/merge_preview.html'
        else:
            master = queryset.get(pk=request.POST.get('master_pk'))
            other = queryset.get(pk=request.POST.get('other_pk'))

    elif 'apply' in request.POST:
        master = queryset.get(pk=request.POST.get('master_pk'))
        other = queryset.get(pk=request.POST.get('other_pk'))
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        with transaction.nocommit():
            form = MForm(request.POST, instance=master)
            stored_pk = other.pk
            other.delete()
            ok = form.is_valid()
            other.pk = stored_pk
        if ok:
            if form.cleaned_data['dependencies'] == MergeForm.DEP_MOVE:
                related = api.ALL_FIELDS
            else:
                related = None
            fields = form.cleaned_data['field_names']
            api.merge(master, other, fields=fields, commit=True, related=related)
            return HttpResponseRedirect(request.path)
        else:
            messages.error(request, form.errors)
    else:
        try:
            master, other = queryset.all()
            # django 1.4 need to remove the trailing milliseconds
            for field in master._meta.fields:
                if isinstance(field, models.DateTimeField):
                    for target in (master, other):
                        raw_value = getattr(target, field.name)
                        if raw_value:
                            fixed_value = datetime(
                                raw_value.year,
                                raw_value.month,
                                raw_value.day,
                                raw_value.hour,
                                raw_value.minute,
                                raw_value.second)
                            setattr(target, field.name, fixed_value)
        except ValueError:
            messages.error(request, _('Please select exactly 2 records'))
            return

        initial = {'_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
                   'select_across': 0,
                   'generic': MergeForm.GEN_IGNORE,
                   'dependencies': MergeForm.DEP_MOVE,
                   'action': 'merge',
                   'master_pk': master.pk,
                   'other_pk': other.pk}
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        form = MForm(initial=initial, instance=master)

    adminForm = helpers.AdminForm(form, modeladmin.get_fieldsets(request), {}, [], model_admin=modeladmin)
    media = modeladmin.media + adminForm.media
    ctx.update({'adminform': adminForm,
                'formset': formset,
                'media': mark_safe(media),
                'action_short_description': merge.short_description,
                'title': u"%s (%s)" % (
                    merge.short_description.capitalize(),
                    smart_text(modeladmin.opts.verbose_name_plural),
                ),
                'master': master,
                'other': other})
    if django.VERSION[:2] > (1, 7):
        ctx.update(modeladmin.admin_site.each_context(request))
    else:
        ctx.update(modeladmin.admin_site.each_context())
    if django.VERSION[:2] > (1, 8):
        return render(request, tpl, context=ctx)
    else:
        return render_to_response(tpl, RequestContext(request, ctx))

Example 26

Project: tendenci Source File: views.py
@is_enabled('forms')
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user,'forms.view_form',form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING,
                    'Please edit the form to include an email field ' + \
                    'as it is required for setting up a recurring ' + \
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or None)
    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid():
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase + string.ascii_uppercase)

                    user_list = User.objects.filter(email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30], email=emailfield,
                                                 first_name=firstnamefield, last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                    creator=anonymous_creator, phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To':form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(email_to)
                EventLog.objects.log(instance=form, description=description)
                
                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)
                
            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To':email_from})
            email_copies = [e.strip() for e in form.email_copies.split(',') if e.strip()]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append((f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get('custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                             user=rp_user,
                             description=form.title,
                             billing_period=entry.pricing.billing_period,
                             billing_start_dt=billing_start_dt,
                             num_days=entry.pricing.num_days,
                             due_sore=entry.pricing.due_sore,
                             payment_amount=price,
                             taxable=entry.pricing.taxable,
                             tax_rate=entry.pricing.tax_rate,
                             has_trial_period=entry.pricing.has_trial_period,
                             trial_period_start_dt=trial_period_start_dt,
                             trial_period_end_dt=trial_period_end_dt,
                             trial_amount=entry.pricing.trial_amount,
                             creator=rp_user,
                             creator_username=rp_user.username,
                             owner=rp_user,
                             owner_username=rp_user.username,
                         )
                    rp.save()
                    rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id, rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    # NOTE: Temporarily use forms/base.html for the meantime
    form.template = "forms/base.html"

    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))

Example 27

Project: tendenci Source File: views.py
def index(request, form_class=SubmitContactForm, template_name="form.html"):

    if request.method == "GET":
        # event-log view
        EventLog.objects.log(instance=Contact(), action='viewed')

    if request.method == "POST":
        event_log_dict = {}
        form = form_class(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')

            if listed_in_email_block(email):
                # listed in the email blocks - it's a spam email we want to block
                # log the spam
                EventLog.objects.log()

                # redirect normally so they don't suspect
                return HttpResponseRedirect(reverse('form.confirmation'))

            address = form.cleaned_data.get('address')
            city = form.cleaned_data.get('city')
            state = form.cleaned_data.get('state')
            zipcode = form.cleaned_data.get('zipcode')
            country = form.cleaned_data.get('country')
            phone = form.cleaned_data.get('phone')
            url = form.cleaned_data.get('url')
            message = form.cleaned_data.get('message')

            exists = User.objects.filter(
                first_name__iexact=first_name,
                last_name__iexact=last_name,
                email__iexact=email,
            ).exists()

            if request.user.is_anonymous():
                username = first_name.replace(' ', '')
                if last_name:
                    username = username + '_' + last_name.replace(' ', '')
                username = username.lower()
                try:
                    User.objects.get(username=username)
                    x = User.objects.filter(first_name=first_name).count()
                    username = username + '_' + unicode(x)
                except User.DoesNotExist:
                    pass

                contact_user = User(
                    username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                )

                contact_user.is_active = False
                contact_user.save()
                profile = Profile(user=contact_user, owner=contact_user, creator=User.objects.get(pk=1),
                                  address=address, country=country, city=city, state=state,
                                  url=url, phone=phone, zipcode=zipcode)
                profile.save()
                sf_id = create_salesforce_contact(profile)

                # if exists:
                #     event_log_dict['description'] = 'logged-out submission as existing user'
                # else:
                event_log_dict['description'] = 'logged-out submission as new user'

            else:  # logged in user
                self_submit = all([
                    request.user.first_name.lower().strip() == first_name.lower().strip(),
                    request.user.last_name.lower().strip() == last_name.lower().strip(),
                    request.user.email.lower().strip() == email.lower().strip(),
                ])

                contact_user = request.user

                if exists:
                    if self_submit:
                        event_log_dict['description'] = 'logged-in submission as self'
                    else:
                        event_log_dict['description'] = 'logged-in submission as existing user'
                else:
                    event_log_dict['description'] = 'logged-in submission as non-existing user'

            contact_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'message': message,
                'user': contact_user,
            }

            contact = Contact(**contact_kwargs)
            contact.allow_anonymous_view = False
            contact.save()

            if address or city or state or zipcode or country:
                address_kwargs = {
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                }
                obj_address = Address(**address_kwargs)
                obj_address.save()  # saves object
                contact.addresses.add(obj_address)  # saves relationship

            if phone:
                obj_phone = Phone(number=phone)
                obj_phone.save()  # saves object
                contact.phones.add(obj_phone)  # saves relationship

            if email:
                obj_email = Email(email=email)
                obj_email.save()  # saves object
                contact.emails.add(obj_email)  # saves relationship

            if url:
                obj_url = URL(url=url)
                obj_url.save()  # saves object
                contact.urls.add(obj_url)  # saves relationship

            site_name = get_setting('site', 'global', 'sitedisplayname')
            message_link = get_setting('site', 'global', 'siteurl')

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'contacts', 'contactrecipients')
            if recipients:
                if notification:
                    extra_context = {
                    'reply_to': email,
                    'contact': contact,
                    'first_name': first_name,
                    'last_name': last_name,
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                    'phone': phone,
                    'email': email,
                    'url': url,
                    'message': message,
                    'message_link': message_link,
                    'site_name': site_name,
                    }
                    notification.send_emails(recipients, 'contact_submitted', extra_context)

            # event-log (logged in)
            event_log = EventLog.objects.log(
                instance=contact,
                user=contact_user,
                action='submitted',
                **event_log_dict
            )

            event_log.url = contact.get_absolute_url()
            event_log.save()

            return HttpResponseRedirect(reverse('form.confirmation'))
        else:
            return render_to_response(template_name, {'form': form},
                context_instance=RequestContext(request))

    form = form_class()
    return render_to_response(template_name, {'form': form},
        context_instance=RequestContext(request))

Example 28

Project: coursys Source File: views.py
@requires_discipline_user
def edit_case_info(request, course_slug, case_slug, field):
    """
    View function for all of the "edit this aspect of the case" steps.  Uses the STEP_* dictionaries to get relevant strings/classes.
    """
    course = get_object_or_404(CourseOffering, slug=course_slug)
    case = get_object_or_404(DisciplineCaseBase, slug=case_slug, offering__slug=course_slug)
    case = case.subclass()

    # permisson checks
    roles = request.session['discipline-'+course_slug]
    if not case.can_edit(field):
        # once instructor finished, don't allow editing those fields
        return ForbiddenResponse(request, "letter has been sent: cannot edit this field")
    elif isinstance(case, DisciplineCaseInstr) and "INSTR" not in roles:
        # only instructor can edit those fields
        return ForbiddenResponse(request, "only the instructor can edit this field")
    elif isinstance(case, DisciplineCaseChair) and "DEPT" not in roles:
        # only discipline admins can edit chair fields
        return ForbiddenResponse(request, "only the Chair (or delegate) can edit this field")

    FormClass = STEP_FORM[field]
    if request.method == 'POST':
        form = FormClass(request.POST, instance=case)
        if form.is_valid():
            c = form.save()
            if field in PRE_LETTER_STEPS:
                # letter hasn't been reviewed if anything changes
                c.letter_review = False
                c.letter_sent = 'WAIT'
                c.penalty_implemented = False
                c.save()

            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("edit discipline case %s in %s: changed %s") % (c.slug, c.offering, STEP_DESC[field]),
                  related_object=c)
            l.save()
            messages.add_message(request, messages.SUCCESS, "Updated " + STEP_DESC[field] + '.')
            
            # set identical value for group members as requested
            also_contact = []
            for postfield in request.POST:
                match = also_set_re.match(postfield)
                if not match or request.POST[postfield] != "on":
                    continue
                
                field = match.group('field')
                caseid = match.group('caseid')
                cases = DisciplineCaseBase.objects.filter(id=caseid)
                if len(cases) != 1 or cases[0].group != case.group:
                    continue
                c0 = cases[0].subclass()
                if not c0.can_edit(field):
                    messages.add_message(request, messages.ERROR,
                        "Case for %s is finished: cannot update %s." % (c0.student.name(), STEP_DESC[field]))
                    continue

                if field=="contacted" and form.cleaned_data[field]=='MAIL':
                    # special case handled below
                    also_contact.append(c0)
                else:
                    setattr(c0, field, form.cleaned_data[field])
                    if field in PRE_LETTER_STEPS:
                        c0.letter_review = False
                    c0.save()
                    messages.add_message(request, messages.SUCCESS,
                        "Also updated %s for %s." % (STEP_DESC[field], c0.student.name()))
                    
            if hasattr(c, 'send_letter_now'):
                # send instructor's letter
                assert case.public_attachments_size() <= MAX_ATTACHMENTS # should be ensured by "review letter" step
                c.send_letter(_currentuser(request))
                messages.add_message(request, messages.INFO, "Letter sent to student summarizing case.")

            if hasattr(c, 'send_contact_mail'):
                # send initial contact email
                c.send_contact_email()
                messages.add_message(request, messages.INFO, "Email sent to student notifying of case.")
                for c0 in also_contact:
                    textkey = 'also-contact_email_text-' + str(c0.id)
                    if textkey in request.POST and request.POST[textkey]=="on":
                        # only send the email if text was updated too
                        c0.contacted = form.cleaned_data['contacted']
                        c0.contact_email_text = form.cleaned_data['contact_email_text']
                        c0.save()
                        messages.add_message(request, messages.SUCCESS,
                            "Also updated %s for %s." % (STEP_DESC['contacted'], c0.student.name()))
                        c0.send_contact_email()
                        messages.add_message(request, messages.INFO, "Also emailed %s." % (c0.student.name()))
                    else:
                        # if not, give an error message.
                        messages.add_message(request, messages.ERROR,
                            mark_safe('Email not sent to %s since their "Contact Email Text" was not updated. You can <a href="%s">edit their contact info</a> if you wish.'
                            % (c0.student.name(),
                                reverse('discipline.views.edit_case_info',
                                    kwargs={'field': 'contacted', 'course_slug': course_slug, 'case_slug': c0.slug}))))
            
            if isinstance(case, DisciplineCaseChair):
                return HttpResponseRedirect(reverse('discipline.views.show_chair', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))
            else:
                return HttpResponseRedirect(reverse('discipline.views.show', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))
    else:
        form = FormClass(instance=case)
    
    templates = DisciplineTemplate.objects.filter(field__in=form.fields.keys())
    tempaltesJSON = json.dumps([t.JSON_data() for t in templates])
    groupmembersJSON = case.groupmembersJSON()
    hasRelAct = len(case.related_activities())>0
    
    context = {'course': course, 'case': case, 'form': form,
        'templatesJSON': mark_safe(tempaltesJSON), 'groupmembersJSON': mark_safe(groupmembersJSON), 'hasRelAct': hasRelAct}
    if field == 'letter_review':
        context['currentuser'] = _currentuser(request)
    return render_to_response("discipline/edit_"+field+".html", context, context_instance=RequestContext(request))

Example 29

Project: tendenci Source File: models.py
def send_emails(emails, label, extra_context=None, on_site=True):
    """
    This method accepts a list of email addresses
    as opposed to a list of users. This is a custom method
    as opposed to send(), send_now(), and queue()

    Just send the notice to a list of emails immediately.
    No new notice created here
    notification.send_emails(email_list, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    """
    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except:
        # Stop here because we need a notice_type
        return None

    headers = {}
    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = Site.objects.get_current()

    notices_url = u"%s://%s%s" % (
        protocol,
        unicode(current_site),
        reverse("notification_notices"),
    )

    formats = (
        'full.html',
        'short.txt',
        'notice.html',
    )  # TODO make formats configurable

    # test for request in the extra_context
    if 'request' in extra_context.keys():
        context = RequestContext(extra_context['request'])
        extra_context.update({
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)
    else:
        # update context with user specific translations
        context = Context({
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)

    # get prerendered format messages
    messages = get_formatted_messages(formats, label, context)

    if 'admin' in label:
        subject = messages['short']
        body = messages['full']

    else:
        subject = render_to_string(
            'notification/email_subject.txt',
            {'message': mark_safe(messages['short'])},
            context)

        body = render_to_string(
            'notification/email_body.txt',
            {'message': mark_safe(messages['full'])},
            context)

    if 'reply_to' in extra_context.keys():
        reply_to = extra_context['reply_to']
        headers['Reply-To'] = reply_to
    else:
        reply_to = ''

    sender = extra_context.get('sender', '')
    if not sender:
        sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if not sender:
            sender = settings.DEFAULT_FROM_EMAIL

    sender_display = extra_context.get('sender_display', '')
    # Add quotes around display name to prevent errors on sending
    # when display name contains comma or other control characters, - jennyq
    from_display = '"%s"<%s>' % (sender_display, sender)

    if sender_display:
        headers['From'] = from_display

    recipient_bcc = extra_context.get('recipient_bcc') or []
    content_type = 'html'

    # removing newlines
    subject = ''.join(subject.splitlines())

    for email_addr in emails:
        recipients = [email_addr]

        if recipient_bcc:
            email = EmailMessage(subject, body, sender,
                                 recipients, recipient_bcc, headers=headers)
        else:
            email = EmailMessage(subject, body, sender,
                                 recipients, headers=headers)
        email.content_subtype = content_type

        try:
            email.send(fail_silently=True)  # should we raise exception or not?
        except UnicodeError:
            pass

    to = ','.join(emails)
    bcc = ','.join(recipient_bcc)
    reply_to = reply_to or unicode()

    NoticeEmail.objects.create(
        emails=to,
        sender=sender,
        bcc=bcc,
        title=subject,
        content=body,
        reply_to=reply_to,
        from_display=from_display,
        notice_type=notice_type
    )

Example 30

Project: Observatory Source File: views.py
@login_required
def view_list(request,list_id=0,list_slug=None,view_completed=0):
    
    """
    Display and manage items in a task list
    """
    
    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.

    if list_slug == "mine"  or list_slug == "recent-add" or list_slug == "recent-complete" :
        auth_ok =1
    else: 
        list = get_object_or_404(List, slug=list_slug)
        listid = list.id    
        
        # Check whether current user is a member of the group this list belongs to.
        if list.group in request.user.groups.all() or request.user.mentor or list_slug == "mine" :
            auth_ok = 1   # User is authorized for this view
        else: # User does not belong to the group this list is attached to
            messages.error(request, "You do not have permission to view/edit this list.")                                    

        
    # First check for items in the mark_done POST array. If present, change
    # their status to complete.
    if request.POST.getlist('mark_done'):
        done_items = request.POST.getlist('mark_done')
        # Iterate through array of done items and update its representation in the model
        for thisitem in done_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 1
            p.completed_date = datetime.datetime.now()
            p.save()
            messages.success(request, "Item \"%s\" marked complete." % p.title)                                             


    # Undo: Set completed items back to incomplete
    if request.POST.getlist('undo_completed_task'):
        undone_items = request.POST.getlist('undo_completed_task')
        for thisitem in undone_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 0
            p.save()
            messages.success(request, "Previously completed task \"%s\" marked incomplete." % p.title)


    # And delete any requested items
    if request.POST.getlist('del_task'):
        deleted_items = request.POST.getlist('del_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            p.delete()
            messages.success(request, "Item \"%s\" deleted." % p.title)         

    # And delete any *already completed* items
    if request.POST.getlist('del_completed_task'):
        deleted_items = request.POST.getlist('del_completed_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            p.delete()
            messages.success(request, "Deleted previously completed item \"%s\"."  % p.title)                       


    thedate = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)


    # Get list of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user, completed=0)
        completed_list = Item.objects.filter(assigned_to=request.user, completed=1)
        
    elif list_slug == "recent-add":
        # We'll assume this only includes uncompleted items to avoid confusion.
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=(request.user.groups.all()),completed=0).order_by('-created_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)   
        
    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=request.user.groups.all(),completed=1).order_by('-completed_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)             


    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)


    if request.POST.getlist('add_task') :
        form = AddItemForm(list, request.POST,initial={
        'assigned_to':request.user.id,
        'priority':999,
        })
        
        if form.is_valid():
            # Save task first so we have a db object to play with
            new_task = form.save()

            # Send email alert only if the Notify checkbox is checked AND the assignee is not the same as the submittor
            # Email subect and body format are handled by templates
            if "notify" in request.POST :
                if new_task.assigned_to != request.user :
                                        
                    # Send email
                    email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': new_task })                    
                    email_body = render_to_string("todo/email/assigned_body.txt", { 'task': new_task, 'site': current_site, })
                    try:
                        send_mail(email_subject, email_body, new_task.created_by.email, [new_task.assigned_to.email], fail_silently=False)
                    except:
                        messages.error(request, "Task saved but mail not sent. Contact your administrator.")
                        

            messages.success(request, "New task \"%s\" has been added." % new_task.title)                       
            
            return HttpResponseRedirect(request.path)

    else:
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete" : # We don't allow adding a task on the "mine" view
            form = AddItemForm(list, initial={
                'assigned_to':request.user.id,
                'priority':999,
                } )

    if request.user.mentor :
        can_del = 1

    return render_to_response('todo/view_list.html', locals(), context_instance=RequestContext(request))

Example 31

Project: hubplus Source File: views.py
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """
    photo = get_object_or_404(Image, id=id)
    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404
    photo_url = photo.get_display_url()
    
    tribes = []
    projects = []
    
    # Build a list of tribes and the photos from the pool
    for tribe in Tribe.objects.filter(members=request.user):
        phototribe = Tribe.objects.get(pk=tribe.id)
        if phototribe.photos.filter(photo=photo).count():
            tribes.append({
                "name": tribe.name,
                "slug": tribe.slug,
                "id": tribe.id,
                "has_photo": True,
            })
        else:
            tribes.append({
                "name": tribe.name,
                "slug": tribe.slug,
                "id": tribe.id,
                "has_photo": False,
            })

    # Build a list of projects and the photos from the pool
    for project in Project.objects.filter(members__user=request.user):
        photoproject = Project.objects.get(pk=project.id)
        if photoproject.photos.filter(photo=photo).count():
            projects.append({
                "name": project.name,
                "slug": project.slug,
                "id": project.id,
                "has_photo": True,
            })
        else:
            projects.append({
                "name": project.name,
                "slug": project.slug,
                "id": project.id,
                "has_photo": False,
            })

    title = photo.title
    host = "http://%s" % get_host(request)
    if photo.member == request.user:
        is_me = True
    else:
        is_me = False
    # TODO: check for authorized user and catch errors
    if is_me:
        if request.method == "POST" and request.POST["action"] == "add_to_project":
            projectid = request.POST["project"]
            myproject = Project.objects.get(pk=projectid)
            if not myproject.photos.filter(photo=photo).count():
                myproject.photos.create(photo=photo)
                request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
            else:
                # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

            return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))
        
        if request.method == "POST":
            if request.POST["action"] == "addtotribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if not mytribe.photos.filter(photo=photo).count():
                    mytribe.photos.create(photo=photo)
                    request.user.message_set.create(message=_("Successfully add photo '%s' to tribe") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to tribe because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "removefromtribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if mytribe.photos.filter(photo=photo).count():
                    mytribe.photos.filter(photo=photo).delete()
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from tribe") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from tribe.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "addtoproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if not myproject.photos.filter(photo=photo).count():
                    myproject.photos.create(photo=photo)
                    request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "removefromproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if myproject.photos.filter(photo=photo).count():
                    myproject.photos.filter(photo=photo).delete()
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from project") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from project.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

    return render_to_response(template_name, {
        "host": host, 
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
        "projects": projects,
        "tribes": tribes,
    }, context_instance=RequestContext(request))

Example 32

Project: django-templatesadmin Source File: views.py
@never_cache
@user_passes_test(lambda u: user_in_templatesadmin_group(u))
@login_required
def modify(request,
           path,
           template_name='templatesadmin/edit.html',
           base_form=TemplateForm,
           available_template_dirs=TEMPLATESADMIN_TEMPLATE_DIRS):

    template_path = _fixpath(path)

    # Check if file is within template-dirs
    if not any([template_path.startswith(templatedir) for templatedir in available_template_dirs]):
        request.user.message_set.create(message=_('Sorry, that file is not available for editing.'))
        return HttpResponseRedirect(reverse('templatesadmin-overview'))

    if request.method == 'POST':
        formclass = base_form
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(hook.contribute_to_form(template_path))

        form = formclass(request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    pre_save_notice = hook.pre_save(request, form, template_path)
                    if pre_save_notice:
                        request.user.message_set.create(message=pre_save_notice)
            except TemplatesAdminException, e:
                request.user.message_set.create(message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            # Save the template
            try:
                f = open(template_path, 'r')
                file_content = f.read()
                f.close()

                # browser tend to strip newlines from <textarea/>s before
                # HTTP-POSTing: re-insert them if neccessary

                # content is in dos-style lineending, will be converted in next step
                if (file_content[-1] == '\n' or file_content[:-2] == '\r\n') \
                   and content[:-2] != '\r\n':
                    content = u"%s\r\n" % content

                # Template is saved in unix-style, save in unix style.
                if None == search("\r\n", file_content):
                    content = content.replace("\r\n", "\n")

                f = codecs.open(template_path, 'w', 'utf-8')
                f.write(content)
                f.close()
            except IOError, e:
                request.user.message_set.create(
                    message=_('Template "%(path)s" has not been saved! Reason: %(errormsg)s' % {
                        'path': path,
                        'errormsg': e
                    })
                )
                return HttpResponseRedirect(request.build_absolute_uri())

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    post_save_notice = hook.post_save(request, form, template_path)
                    if post_save_notice:
                        request.user.message_set.create(message=post_save_notice)
            except TemplatesAdminException, e:
                request.user.message_set.create(message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            request.user.message_set.create(
                message=_('Template "%s" was saved successfully.' % path)
            )
            return HttpResponseRedirect(reverse('templatesadmin-overview'))
    else:
        template_file = codecs.open(template_path, 'r', 'utf-8').read()

        formclass = TemplateForm
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(hook.contribute_to_form(template_path))

        form = formclass(
            initial={'content': template_file}
        )

    template_context = {
        'messages': request.user.get_and_delete_messages(),
        'form': form,
        'short_path': path,
        'template_path': path,
        'template_writeable': os.access(template_path, os.W_OK),
        'ADMIN_MEDIA_PREFIX': settings.ADMIN_MEDIA_PREFIX,
    }

    return render_to_response(template_name, template_context,
                              RequestContext(request))

Example 33

Project: hubplus Source File: views.py
def profile(request, username, template_name="profiles/profile.html"):
    #trellis.callInEventLoop(hello, "Tom")

    is_me = False
    user = request.user


    if request.user.is_authenticated() :
        if user.username == username :
            is_me = True
    else :
        user = get_anon_user()

    other_user = secure_wrap(get_object_or_404(User, username=username),user)

    is_following = Following.objects.is_following(request.user, other_user.get_inner())

    p = other_user.get_inner().get_profile()
    profile = secure_wrap(p,user)
    profile.user # trigger permission exception if no access
 
    can_change_avatar = False
    
    try :
        profile.change_avatar
        can_change_avatar = True
    except PlusPermissionsNoAccessException :
        pass

    interests = get_tags(tagged=other_user.get_inner().get_profile(), 
                         tagged_for=other_user.get_inner(), tag_type='interest')
    skills = get_tags(tagged = other_user.get_inner().get_profile(), 
                      tagged_for=other_user.get_inner(), tag_type='skill')
    needs = get_tags(tagged = other_user.get_inner().get_profile(), 
                     tagged_for=other_user.get_inner(), tag_type='need')

    user_type = ContentType.objects.get_for_model(other_user)

    # new style statuses
    tweets = FeedItem.feed_manager.get_from(other_user.get_inner()).order_by("-sent")
    if tweets :
        latest_status = tweets[0]
        status_since = defaultfilters.timesince(latest_status.sent)
    else:
        status_since = ''
    status_type = 'profile'

    try:
        profile.get_all_sliders
        perms_bool = True
    except PlusPermissionsNoAccessException:
        perms_bool = False

    profile = TemplateSecureWrapper(profile)

    search_type = 'profile_list' 
    search_types = narrow_search_types()
    search_types_len = len(search_types)
    search_type_label = search_types[0][1][2]


    host_info = p.get_host_info()
    host_info = secure_wrap(host_info, user, interface_names=['Viewer', 'Editor'])

    see_host_info = False
    try :
        host_info.user 
        see_host_info = True
    except :
        pass # can't see host_info
    host_info = TemplateSecureWrapper(host_info)
    
    hubs = other_user.get_inner().hubs()
    non_hub_groups = [(g.group_app_label() + ':group', g) for g in 
                      other_user.get_inner().groups.filter(level='member').exclude(id__in=hubs)]
    hubs = [(g.group_app_label() + ':group', g) for g in hubs]

    see_about = is_me or show_section(profile, ('about',))
    see_contacts = is_me or show_section(profile,('mobile','home','work','fax','website','address','email_address'))
    
    see_links = is_me
    links = get_links_for(other_user,RequestContext(request))
    if links :
        see_links = True

    can_tag = profile.has_interface('Profile.Editor')


    template_args = {
            "is_me": is_me,
            "is_following": is_following,
            "other_user": other_user.get_inner(), # XXX - should fix this get_inner
            "profile":profile,
            "can_change_avatar":can_change_avatar,

            "head_title" : "%s" % profile.get_display_name(),
            "status_type" : status_type,
            "status_since" : status_since,
            "host_info" : host_info,
            "skills" : skills,
            "needs" : needs,
            "interests" : interests,
            "other_user_tweets" : tweets,
            "permissions":perms_bool,
            "non_hub_groups":non_hub_groups,
            "hubs":hubs,
            "search_type":search_type,
            "search_types":search_types,
            "search_type_label":search_type_label,
            "search_types_len":search_types_len,
            "host_info":host_info, 
            "see_host_info":see_host_info,
            "see_about":see_about,
            "see_contacts":see_contacts,
            "see_links":see_links,
            "other_user_class":user_type.id,
            "other_user_id":other_user.id,
            "can_tag":can_tag,
            }
    labels = {'MAIN_HUB_LABEL':_('Main %s')%settings.HUB_NAME,
              'MAIN_HUB_DEFAULT':_("No %s selected")%settings.HUB_NAME}
    template_args.update(labels)

    return render_to_response(template_name, template_args, context_instance=RequestContext(request))

Example 34

Project: PyClassLessons Source File: views.py
    def get_feed(self, obj, request):
        """
        Returns a feedgenerator.DefaultFeed object, fully populated, for
        this feed. Raises FeedDoesNotExist for invalid parameters.
        """
        current_site = get_current_site(request)

        link = self.__get_dynamic_attr('link', obj)
        link = add_domain(current_site.domain, link, request.is_secure())

        feed = self.feed_type(
            title=self.__get_dynamic_attr('title', obj),
            subtitle=self.__get_dynamic_attr('subtitle', obj),
            link=link,
            description=self.__get_dynamic_attr('description', obj),
            language=settings.LANGUAGE_CODE,
            feed_url=add_domain(
                current_site.domain,
                self.__get_dynamic_attr('feed_url', obj) or request.path,
                request.is_secure(),
            ),
            author_name=self.__get_dynamic_attr('author_name', obj),
            author_link=self.__get_dynamic_attr('author_link', obj),
            author_email=self.__get_dynamic_attr('author_email', obj),
            categories=self.__get_dynamic_attr('categories', obj),
            feed_copyright=self.__get_dynamic_attr('feed_copyright', obj),
            feed_guid=self.__get_dynamic_attr('feed_guid', obj),
            ttl=self.__get_dynamic_attr('ttl', obj),
            **self.feed_extra_kwargs(obj)
        )

        title_tmp = None
        if self.title_template is not None:
            try:
                title_tmp = loader.get_template(self.title_template)
            except TemplateDoesNotExist:
                pass

        description_tmp = None
        if self.description_template is not None:
            try:
                description_tmp = loader.get_template(self.description_template)
            except TemplateDoesNotExist:
                pass

        for item in self.__get_dynamic_attr('items', obj):
            context = self.get_context_data(item=item, site=current_site,
                                            obj=obj, request=request)
            if title_tmp is not None:
                title = title_tmp.render(RequestContext(request, context))
            else:
                title = self.__get_dynamic_attr('item_title', item)
            if description_tmp is not None:
                description = description_tmp.render(RequestContext(request, context))
            else:
                description = self.__get_dynamic_attr('item_description', item)
            link = add_domain(
                current_site.domain,
                self.__get_dynamic_attr('item_link', item),
                request.is_secure(),
            )
            enc = None
            enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
            if enc_url:
                enc = feedgenerator.Enclosure(
                    url=smart_text(enc_url),
                    length=smart_text(self.__get_dynamic_attr('item_enclosure_length', item)),
                    mime_type=smart_text(self.__get_dynamic_attr('item_enclosure_mime_type', item))
                )
            author_name = self.__get_dynamic_attr('item_author_name', item)
            if author_name is not None:
                author_email = self.__get_dynamic_attr('item_author_email', item)
                author_link = self.__get_dynamic_attr('item_author_link', item)
            else:
                author_email = author_link = None

            tz = get_default_timezone()

            pubdate = self.__get_dynamic_attr('item_pubdate', item)
            if pubdate and is_naive(pubdate):
                pubdate = make_aware(pubdate, tz)

            updateddate = self.__get_dynamic_attr('item_updateddate', item)
            if updateddate and is_naive(updateddate):
                updateddate = make_aware(updateddate, tz)

            feed.add_item(
                title=title,
                link=link,
                description=description,
                unique_id=self.__get_dynamic_attr('item_guid', item, link),
                unique_id_is_permalink=self.__get_dynamic_attr(
                    'item_guid_is_permalink', item),
                enclosure=enc,
                pubdate=pubdate,
                updateddate=updateddate,
                author_name=author_name,
                author_email=author_email,
                author_link=author_link,
                categories=self.__get_dynamic_attr('item_categories', item),
                item_copyright=self.__get_dynamic_attr('item_copyright', item),
                **self.item_extra_kwargs(item)
            )
        return feed

Example 35

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 36

Project: splunk-webframework Source File: views.py
@staff_member_required
def model_detail(request, app_label, model_name):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    # Get the model class.
    try:
        app_mod = models.get_app(app_label)
    except ImproperlyConfigured:
        raise Http404(_("App %r not found") % app_label)
    model = None
    for m in models.get_models(app_mod):
        if m._meta.object_name.lower() == model_name:
            model = m
            break
    if model is None:
        raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})

    opts = model._meta

    # Gather fields/field descriptions.
    fields = []
    for field in opts.fields:
        # ForeignKey is a special case since the field will actually be a
        # descriptor that returns the other object
        if isinstance(field, models.ForeignKey):
            data_type = field.rel.to.__name__
            app_label = field.rel.to._meta.app_label
            verbose = utils.parse_rst((_("the related `%(app_label)s.%(data_type)s` object")  % {'app_label': app_label, 'data_type': data_type}), 'model', _('model:') + data_type)
        else:
            data_type = get_readable_field_data_type(field)
            verbose = field.verbose_name
        fields.append({
            'name': field.name,
            'data_type': data_type,
            'verbose': verbose,
            'help_text': field.help_text,
        })

    # Gather many-to-many fields.
    for field in opts.many_to_many:
        data_type = field.rel.to.__name__
        app_label = field.rel.to._meta.app_label
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
        fields.append({
            'name': "%s.all" % field.name,
            "data_type": 'List',
            'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % field.name,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })

    # Gather model methods.
    for func_name, func in model.__dict__.items():
        if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
            try:
                for exclude in MODEL_METHODS_EXCLUDE:
                    if func_name.startswith(exclude):
                        raise StopIteration
            except StopIteration:
                continue
            verbose = func.__doc__
            if verbose:
                verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
            fields.append({
                'name': func_name,
                'data_type': get_return_data_type(func_name),
                'verbose': verbose,
            })

    # Gather related objects
    for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
        verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
        accessor = rel.get_accessor_name()
        fields.append({
            'name'      : "%s.all" % accessor,
            'data_type' : 'List',
            'verbose'   : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
        })
        fields.append({
            'name'      : "%s.count" % accessor,
            'data_type' : 'Integer',
            'verbose'   : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
        })
    return render_to_response('admin_doc/model_detail.html', {
        'root_path': urlresolvers.reverse('admin:index'),
        'name': '%s.%s' % (opts.app_label, opts.object_name),
        'summary': _("Fields on %s objects") % opts.object_name,
        'description': model.__doc__,
        'fields': fields,
    }, context_instance=RequestContext(request))

Example 37

Project: tri.table Source File: __init__.py
def table_context(request,
                  table,
                  links=None,
                  paginate_by=None,
                  page=None,
                  extra_context=None,
                  context_processors=None,
                  paginator=None,
                  show_hits=False,
                  hit_label='Items'):
    """
    :type table: Table
    """
    if extra_context is None:  # pragma: no cover
        extra_context = {}

    assert table.data is not None

    grouped_links = {}
    if links is not None:
        links = evaluate_recursive(links, table=table)
        links = [link for link in links if link.show and link.url]

        grouped_links = groupby((link for link in links if link.group is not None), key=lambda l: l.group)
        grouped_links = [(g, slugify(g), list(lg)) for g, lg in grouped_links]  # because django templates are crap!

        links = [link for link in links if link.group is None]

    base_context = {
        'links': links,
        'grouped_links': grouped_links,
        'table': table,
    }

    if paginate_by:
        try:
            paginate_by = int(request.GET.get('page_size', paginate_by))
        except ValueError:  # pragma: no cover
            pass
        if paginator is None:
            paginator = Paginator(table.data, paginate_by)
            object_list = None
        else:  # pragma: no cover
            object_list = table.data
        if not page:
            page = request.GET.get('page', 1)
        try:
            page = int(page)
            if page < 1:  # pragma: no cover
                page = 1
            if page > paginator.num_pages:  # pragma: no cover
                page = paginator.num_pages
            if object_list is None:
                table.data = paginator.page(page).object_list
        except (InvalidPage, ValueError):  # pragma: no cover
            if page == 1:
                table.data = []
            else:
                raise Http404

        base_context.update({
            'request': request,
            'is_paginated': paginator.num_pages > 1,
            'results_per_page': paginate_by,
            'has_next': paginator.num_pages > page,
            'has_previous': page > 1,
            'page_size': paginate_by,
            'page': page,
            'next': page + 1,
            'previous': page - 1,
            'pages': paginator.num_pages,
            'hits': paginator.count,
            'show_hits': show_hits,
            'hit_label': hit_label})
    else:  # pragma: no cover
        base_context.update({
            'is_paginated': False})

    base_context.update(extra_context)
    return RequestContext(request, base_context, context_processors)

Example 38

Project: rpc4django Source File: views.py
@csrf_exempt
def serve_rpc_request(request):
    '''
    Handles rpc calls based on the content type of the request or
    returns the method docuementation page if the request
    was a GET.

    **Parameters**

    ``request``
        the Django HttpRequest object

    '''

    if request.method == "POST" and int(request.META.get('CONTENT_LENGTH', 0)) > 0:
        # Handle POST request with RPC payload

        if LOG_REQUESTS_RESPONSES:
            logger.debug('Incoming request: %s' % str(get_request_body(request)))

        if is_xmlrpc_request(request):
            if RESTRICT_XML:
                raise Http404

            if not check_request_permission(request, 'xml'):
                return HttpResponseForbidden()

            resp = dispatcher.xmldispatch(get_request_body(request),
                                          request=request)
            response_type = 'text/xml'
        else:
            if RESTRICT_JSON:
                raise Http404

            if not check_request_permission(request, 'json'):
                return HttpResponseForbidden()

            resp = dispatcher.jsondispatch(get_request_body(request),
                                           request=request)
            response_type = 'application/json'

        if LOG_REQUESTS_RESPONSES:
            logger.debug('Outgoing %s response: %s' % (response_type, resp))

        return HttpResponse(resp, response_type)
    elif request.method == 'OPTIONS':
        # Handle OPTIONS request for "preflighted" requests
        # see https://developer.mozilla.org/en/HTTP_access_control

        response = HttpResponse('', 'text/plain')

        origin = request.META.get('HTTP_ORIGIN', 'unknown origin')
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        response['Access-Control-Max-Age'] = 0
        response['Access-Control-Allow-Credentials'] = \
            str(HTTP_ACCESS_CREDENTIALS).lower()
        response['Access-Control-Allow-Origin'] = HTTP_ACCESS_ALLOW_ORIGIN

        response['Access-Control-Allow-Headers'] = \
            request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', '')

        if LOG_REQUESTS_RESPONSES:
            logger.debug('Outgoing HTTP access response to: %s' % (origin))

        return response
    else:
        # Handle GET request

        if RESTRICT_METHOD_SUMMARY:
            # hide the docuementation by raising 404
            raise Http404

        # show docuementation
        methods = dispatcher.list_methods()
        template_data = {
            'methods': methods,
            'url': URL,

            # rpc4django version
            'version': version(),

            # restricts the ability to test the rpc server from the docs
            'restrict_rpctest': RESTRICT_RPCTEST,
        }
        from django.template import RequestContext
        return render_to_response('rpc4django/rpcmethod_summary.html',
                                  template_data,
                                  context_instance=RequestContext(request))

Example 39

Project: daywatch Source File: views.py
@login_required
@catch_error
@permission_required
@log_activity
def history_comparison_div(request):
    context = get_status(request)
    form = HistoryComparisonForm(user=request.user, data=request.GET)

    if form.is_valid():
        request.session['form_session'] = form.cleaned_data
        style = get_style()

        period = form.cleaned_data['period']
        concept = form.cleaned_data['concept']

        today = date.today()

        if period == 'last_3_m':
            months = 3
        elif period == 'last_4_m':
            months = 4
        elif period == 'last_6_m':
            months = 6

        player_ids = form.cleaned_data['players']
        player_ids = [int(p_id) for p_id in player_ids]

        country = form.cleaned_data['country']
        context['local_currency'] = CURRENCY_DICT[country]
        context['use_local_currency'] = country in LOCAL_CURRENCY_COUNTRIES

        if form.cleaned_data['all_categories']:
            categories = Category.objects.all()
            category_ids = []
            for category in categories:
                if category.name != 'root':
                    category_ids.append(int(category.id))
        else:
            category_ids = form.cleaned_data['categories']
            category_ids = [int(c_id) for c_id in category_ids]

        histo = defaultdict()
        player_list = []
        total_sales_player = defaultdict()
        company_names = defaultdict()

        total_sales_period = {}

        for p_id in player_ids:
            company_name = DayWatchSite.objects.get(id=int(p_id)).name
            company_names[int(p_id)] = company_name
            player_list.append((int(p_id), company_name))
            total_sales_player[company_name] = 0
            histo[company_name] = defaultdict()

        category_choices = []
        category_legends = []
        for c_id, name in CATEGORY_CHOICES:
            if c_id in category_ids:
                category_choices.append((c_id, name))
                category_legends.append(name)

        company_choices = []
        for c_id, name in COMPANY_CHOICES:
            if c_id in player_ids:
                company_choices.append((c_id, name))

        if concept == 'sales':
            if context['use_local_currency']:
                context['total_title'] = _('Total Sales')
                context['trend_y_legend'] = context['local_currency'] + ' %.0f'
            else:
                context['total_title'] = _('Total Sales U$S')
                context['trend_y_legend'] = 'U$S %.0f'
        elif concept == 'deals':
            context['total_title'] = _('Total # Deals Offered')
            context['trend_y_legend'] = '%d'
        elif concept == 'coupons_sold':
            context['trend_title'] = _('# Coupons Sold')
            context['total_title'] = _('Total # Coupons Sold')
            context['trend_y_legend'] = '%d'

        for company_id, company_name in player_list:
            total_sales_period[company_name] = []
            category_values = {}

            for category_id, category_name in category_choices:
                category_values[category_name] = []

            for i in range(months - 1, -1, -1):
                start_month = today.month - i
                if start_month <= 0:
                    start_month += 12
                    start_year = today.year - 1
                else:
                    start_year = today.year
                start_date_range = datetime(start_year, start_month, 1)
                (_, last) = calendar.monthrange(start_year, start_month)
                end_date_range = datetime(start_year, start_month, last)

                items = DayWatchItem.objects.filter(country=country)
                if concept == 'sales':
                    context['trend_title'] = _('Sales U$S')
                    context['trend_y_legend'] = _('U$S %.0f')

                    items = items.filter(
                        company__id=company_id,
                        category__id__in=category_ids,
                        start_date_time__gte=start_date_range,
                        start_date_time__lte=end_date_range,
                        total_sales_usd__gt=0
                    )
                    items = items.values('category__name').annotate(
                        subtotal=Sum('total_sales_usd')
                    )

                elif concept == 'deals':
                    context['trend_title'] = _('# Deals Offered')
                    context['trend_y_legend'] = '%d'

                    items = items.filter(
                        company__id=company_id,
                        category__id__in=category_ids,
                        start_date_time__gte=start_date_range,
                        start_date_time__lte=end_date_range
                    )
                    items = items.values('category__name').annotate(
                        subtotal=Count('offer_id')
                    )

                elif concept == 'coupons_sold':
                    context['trend_title'] = _('# Coupons Sold')
                    context['trend_y_legend'] = '%d'

                    items = items.filter(
                        company__id=company_id,
                        category__id__in=category_ids,
                        start_date_time__gte=start_date_range,
                        start_date_time__lte=end_date_range,
                        sold_count__gt=0
                    )
                    items = items.values('category__name').annotate(
                        subtotal=Sum('sold_count')
                    )

                total_category = {}
                for _, category_name in category_choices:
                    total_category[category_name] = 0

                for item in items:
                    total_category[deal['category__name']] += deal['subtotal']
                for items in items:
                    total_category[deal['category__name']] += deal['subtotal']

                for _, category_name in category_choices:
                    category_values[category_name].append(
                        total_category[category_name]
                    )

            for _, category_name in category_choices:
                total_sales_period[company_name].append(
                    category_values[category_name]
                )

        interval_values = []
        graphs = []
        for company_name in total_sales_period:
            max_val = 0
            for array in total_sales_period[company_name]:
                for value in array:
                    if value > max_val:
                        max_val = value
            graphs.append({
                'company_name': company_name,
                'interval_value': get_interval(max_val),
                'arrays': total_sales_period[company_name]
            })

        month_legends = []
        for i in range(months - 1, -1, -1):
            start_month = today.month - i
            if start_month <= 0:
                start_month += 12
            month_legends.append(calendar.month_name[start_month])

        legends = [style[category]['label'] for category in category_legends]

        context['graphs'] = graphs
        context['concept'] = concept
        context['category_legends'] = legends
        context['month_legends'] = month_legends
        context['interval_values'] = interval_values

        html = render_to_string(
            'history_comparison_div.html',
            context,
            context_instance=RequestContext(request)
            )
        return JsonResponse(result(Status.OK, data={'html': html}))
    else:
        return JsonResponse(result(Status.ERROR, 'Invalid form.'))

Example 40

Project: django-vcs-watch Source File: views.py
Function: object_list
def object_list(request,
                cls,
                query = {},
                paginate_by = None,
                page = None,
                allow_empty = True,
                template_name = None,
                template_loader = loader,
                extra_context = {},
                context_processors = None,
                template_object_name = 'object_list',
                mimetype = None,
                map_func = lambda x: x,
                **kwargs):
    """
    Generic list of objects.

    Templates: ``<collection_name>_list.html``
    Context:
        object_list
            list of objects
        is_paginated
            are the results paginated?
        results_per_page
            number of objects per page (if paginated)
        has_next
            is there a next page?
        has_previous
            is there a prev page?
        page
            the current page
        next
            the next page
        previous
            the previous page
        pages
            number of pages, total
        hits
            number of objects, total
        last_on_page
            the result number of the last of object in the
            object_list (1-indexed)
        first_on_page
            the result number of the first object in the
            object_list (1-indexed)
        page_range:
            A list of the page numbers (1-indexed).
    """
    if callable(extra_context):
        extra_context = extra_context(request, **kwargs)

    if callable(query):
        query = query(request, **kwargs)

    cursor = cls.objects.find(query)

    if paginate_by:
        paginator = Paginator(cursor, paginate_by, allow_empty_first_page=allow_empty)
        if not page:
            page = request.GET.get('page', 1)
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                # Page is not 'last', nor can it be converted to an int.
                raise Http404
        try:
            page_obj = paginator.page(page_number)
        except InvalidPage:
            raise Http404
        c = RequestContext(request, {
            template_object_name: map(map_func, page_obj.object_list),
            'paginator': paginator,
            'page_obj': page_obj,

            # Legacy template context stuff. New templates should use page_obj
            # to access this instead.
            'is_paginated': page_obj.has_other_pages(),
            'results_per_page': paginator.per_page,
            'has_next': page_obj.has_next(),
            'has_previous': page_obj.has_previous(),
            'page': page_obj.number,
            'next': page_obj.next_page_number(),
            'previous': page_obj.previous_page_number(),
            'first_on_page': page_obj.start_index(),
            'last_on_page': page_obj.end_index(),
            'pages': paginator.num_pages,
            'hits': paginator.count,
            'page_range': paginator.page_range,
        }, context_processors)
    else:
        c = RequestContext(request, {
            template_object_name: map(map_func, cursor),
            'paginator': None,
            'page_obj': None,
            'is_paginated': False,
        }, context_processors)
        if not allow_empty and len(cursor) == 0:
            raise Http404
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    if not template_name:
        template_name = "%s_list.html" % cls.objects.collection_name
    t = template_loader.get_template(template_name)
    return HttpResponse(t.render(c), mimetype=mimetype)

Example 41

Project: timebank Source File: compressor.py
def gzip_compressor(request):
    plugins = split_commas(request.GET.get("plugins", ""))
    languages = split_commas(request.GET.get("languages", ""))
    themes = split_commas(request.GET.get("themes", ""))
    isJS = request.GET.get("js", "") == "true"
    compress = request.GET.get("compress", "true") == "true"
    suffix = request.GET.get("suffix", "") == "_src" and "_src" or ""
    content = []

    response = HttpResponse()
    response["Content-Type"] = "text/javascript"

    if not isJS:
        response.write(render_to_string('tinymce/tiny_mce_gzip.js', {
            'base_url': tinymce.settings.JS_BASE_URL,
        }, context_instance=RequestContext(request)))
        return response

    patch_vary_headers(response, ['Accept-Encoding'])

    now = datetime.utcnow()
    response['Date'] = now.strftime('%a, %d %b %Y %H:%M:%S GMT')

    cacheKey = '|'.join(plugins + languages + themes)
    cacheData = cache.get(cacheKey)

    if not cacheData is None:
        if cacheData.has_key('ETag'):
            if_none_match = request.META.get('HTTP_IF_NONE_MATCH', None)
            if if_none_match == cacheData['ETag']:
                response.status_code = 304
                response.content = ''
                response['Content-Length'] = '0'
                return response

        if cacheData.has_key('Last-Modified'):
            if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE', None)
            if if_modified_since == cacheData['Last-Modified']:
                response.status_code = 304
                response.content = ''
                response['Content-Length'] = '0'
                return response

    # Add core, with baseURL added
    content.append(get_file_contents("tiny_mce%s.js" % suffix).replace(
            "tinymce._init();", "tinymce.baseURL='%s';tinymce._init();"
            % tinymce.settings.JS_BASE_URL))

    # Patch loading functions
    content.append("tinyMCE_GZ.start();")

    # Add core languages
    for lang in languages:
        content.append(get_file_contents("langs/%s.js" % lang))

    # Add themes
    for theme in themes:
        content.append(get_file_contents("themes/%s/editor_template%s.js"
                % (theme, suffix)))

        for lang in languages:
            content.append(get_file_contents("themes/%s/langs/%s.js"
                    % (theme, lang)))

    # Add plugins
    for plugin in plugins:
        content.append(get_file_contents("plugins/%s/editor_plugin%s.js"
                % (plugin, suffix)))

        for lang in languages:
            content.append(get_file_contents("plugins/%s/langs/%s.js"
                    % (plugin, lang)))

    # Add filebrowser
    if tinymce.settings.USE_FILEBROWSER:
        content.append(render_to_string('tinymce/filebrowser.js', {},
            context_instance=RequestContext(request)).encode("utf-8"))

    # Restore loading functions
    content.append("tinyMCE_GZ.end();")

    # Compress
    if compress:
        content = compress_string(''.join(content))
        response['Content-Encoding'] = 'gzip'
        response['Content-Length'] = str(len(content))

    response.write(content)
    timeout = 3600 * 24 * 10
    patch_response_headers(response, timeout)
    cache.set(cacheKey, {
        'Last-Modified': response['Last-Modified'],
        'ETag': response['ETag'],
    })
    return response

Example 42

Project: talk.org Source File: comments.py
def post_comment(request, extra_context=None, context_processors=None):
    """
    Post a comment

    Redirects to the `comments.comments.comment_was_posted` view upon success.

    Templates: `comment_preview`
    Context:
        comment
            the comment being posted
        comment_form
            the comment form
        options
            comment options
        target
            comment target
        hash
            security hash (must be included in a posted form to succesfully
            post a comment).
        rating_options
            comment ratings options
        ratings_optional
            are ratings optional?
        ratings_required
            are ratings required?
        rating_range
            range of ratings
        rating_choices
            choice of ratings
    """
    if extra_context is None: extra_context = {}
    if not request.POST:
        raise Http404, _("Only POSTs are allowed")
    try:
        options, target, security_hash = request.POST['options'], request.POST['target'], request.POST['gonzo']
    except KeyError:
        raise Http404, _("One or more of the required fields wasn't submitted")
    photo_options = request.POST.get('photo_options', '')
    rating_options = normalize_newlines(request.POST.get('rating_options', ''))
    if Comment.objects.get_security_hash(options, photo_options, rating_options, target) != security_hash:
        raise Http404, _("Somebody tampered with the comment form (security violation)")
    # Now we can be assured the data is valid.
    if rating_options:
        rating_range, rating_choices = Comment.objects.get_rating_options(base64.decodestring(rating_options))
    else:
        rating_range, rating_choices = [], []
    content_type_id, object_id = target.split(':') # target is something like '52:5157'
    try:
        obj = ContentType.objects.get(pk=content_type_id).get_object_for_this_type(pk=object_id)
    except ObjectDoesNotExist:
        raise Http404, _("The comment form had an invalid 'target' parameter -- the object ID was invalid")
    option_list = options.split(',') # options is something like 'pa,ra'
    new_data = request.POST.copy()
    new_data['content_type_id'] = content_type_id
    new_data['object_id'] = object_id
    new_data['ip_address'] = request.META.get('REMOTE_ADDR')
    new_data['is_public'] = IS_PUBLIC in option_list
    manipulator = PublicCommentManipulator(request.user,
        ratings_required=RATINGS_REQUIRED in option_list,
        ratings_range=rating_range,
        num_rating_choices=len(rating_choices))
    errors = manipulator.get_validation_errors(new_data)
    # If user gave correct username/password and wasn't already logged in, log them in
    # so they don't have to enter a username/password again.
    if manipulator.get_user() and not manipulator.get_user().is_authenticated() and 'password' in new_data and manipulator.get_user().check_password(new_data['password']):
        from django.contrib.auth import login
        login(request, manipulator.get_user())
    if errors or 'preview' in request.POST:
        class CommentFormWrapper(oldforms.FormWrapper):
            def __init__(self, manipulator, new_data, errors, rating_choices):
                oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
                self.rating_choices = rating_choices
            def ratings(self):
                field_list = [self['rating%d' % (i+1)] for i in range(len(rating_choices))]
                for i, f in enumerate(field_list):
                    f.choice = rating_choices[i]
                return field_list
        comment = errors and '' or manipulator.get_comment(new_data)
        comment_form = CommentFormWrapper(manipulator, new_data, errors, rating_choices)
        return render_to_response('comments/preview.html', {
            'comment': comment,
            'comment_form': comment_form,
            'options': options,
            'target': target,
            'hash': security_hash,
            'rating_options': rating_options,
            'ratings_optional': RATINGS_OPTIONAL in option_list,
            'ratings_required': RATINGS_REQUIRED in option_list,
            'rating_range': rating_range,
            'rating_choices': rating_choices,
        }, context_instance=RequestContext(request, extra_context, context_processors))
    elif 'post' in request.POST:
        # If the IP is banned, mail the admins, do NOT save the comment, and
        # serve up the "Thanks for posting" page as if the comment WAS posted.
        if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
            mail_admins("Banned IP attempted to post comment", smart_unicode(request.POST) + "\n\n" + str(request.META))
        else:
            manipulator.do_html2python(new_data)
            comment = manipulator.save(new_data)
        return HttpResponseRedirect("../posted/?c=%s:%s" % (content_type_id, object_id))
    else:
        raise Http404, _("The comment form didn't provide either 'preview' or 'post'")

Example 43

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 44

Project: syndicate Source File: views.py
@authenticate
def create(request):
    '''
    View for creating UG's
    '''
    session = request.session
    username = session['login_email']
    user = db.read_user(username)

    # Helper method that simplifies returning forms after user error.
    def give_create_form(username, session):
        message = session.pop('message', "")
        form = gatewayforms.CreateUG()
        t = loader.get_template('gateway_templates/create_user_gateway.html')
        c = RequestContext(request, {'username':username,'form':form, 'message':message})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.CreateUG(request.POST)
        if form.is_valid():
            if not form.cleaned_data['volume_name']:
                logging.info("DLFKJSDF")
                vol = None
            else:
                attrs = {"Volume.name ==":form.cleaned_data['volume_name'].strip().replace(" ", "_")}
                vols = db.list_volumes(attrs, limit=1)
                if vols:
                    vol = vols[0]
                else:
                    session['message'] = "No volume %s exists." % form.cleaned_data['volume_name']
                    return give_create_form(username, session)
                if (vol.volume_id not in user.volumes_r) and (vol.volume_id not in user.volumes_rw):
                    session['message'] = "Must have read rights to volume %s to create UG for it." % form.cleaned_data['volume_name']
                    return give_create_form(username, session)
                # Force update of UG version
                attrs = {"UG_version":1}

                try:
                   transaction( lambda: db.update_volume(vol.volume_id, **attrs) )
                except Exception as E:
                   session['message'] = "UG creation error: %s" % E
                   return give_create_form( username, session )

            try:
                # Prep kwargs
                kwargs = {}
                kwargs['read_write'] = form.cleaned_data['read_write']
                kwargs['ms_username'] = form.cleaned_data['g_name']
                kwargs['port'] = form.cleaned_data['port']
                kwargs['host'] = form.cleaned_data['host']
                kwargs['ms_password'] = form.cleaned_data['g_password']

                # Create
                new_ug = db.create_user_gateway(user, vol, **kwargs)
            except Exception as E:
                session['message'] = "UG creation error: %s" % E
                return give_create_form(username, session)

            session['new_change'] = "Your new gateway is ready."
            session['next_url'] = '/syn/UG/mygateways'
            session['next_message'] = "Click here to see your gateways."
            return HttpResponseRedirect('/syn/thanks/')
        else:
            # Prep returned form values (so they don't have to re-enter stuff)

            if 'g_name' in form.errors:
                oldname = ""
            else:
                oldname = request.POST['g_name']
            if 'volume_name' in form.errors:
                oldvolume_name = ""
            else:
                oldvolume_name = request.POST['volume_name']
            if 'host' in form.errors:
                oldhost = ""
            else:
                oldhost = request.POST['host']
            if 'port' in form.errors:
                oldport = ""
            else:
                oldport = request.POST['port']

            # Prep error message
            message = "Invalid form entry: "

            for k, v in form.errors.items():
                message = message + "\"" + k + "\"" + " -> " 
                for m in v:
                    message = message + m + " "

            # Give then the form again
            form = gatewayforms.CreateUG(initial={'g_name': oldname,
                                       'volume_name': oldvolume_name,
                                       'host': oldhost,
                                       'port': oldport,
                                       })
            t = loader.get_template('gateway_templates/create_user_gateway.html')
            c = RequestContext(request, {'username':username,'form':form, 'message':message})
            return HttpResponse(t.render(c))

    else:
        # Not a POST, give them blank form
        return give_create_form(username, session)

Example 45

Project: django-facebookconnect Source File: views.py
def setup(request,redirect_url=None,
          registration_form_class=FacebookUserCreationForm,
          template_name='facebook/setup.html',
          extra_context=None):
    """
    setup
    ===============================
    
    Handles a new facebook user. There are three ways to setup a new facebook user.
     1. Link the facebook account with an existing django account.
     2. Create a dummy django account to attach to facebook. The user must always use
        facebook to login.
     3. Ask the user to create a new django account
     
    The built in template presents the user with all three options. Once setup is 
    complete the user will get redirected. The url used in the following order of 
    presidence:

      1. whatever url is in the 'next' get parameter passed to the setup url
      2. whatever url is passed to the setup view when the url is defined
      3. whatever url is defined in the LOGIN_REDIRECT_URL setting directive
    
    If you define a url to use this view, you can pass the following parameters:
     * redirect_url: Defines where to send the user after they are setup. This
                     can get overridden by the url in the 'next' get param passed on 
                     the url.
     * registration_form_class: Django form class to use for new user way #3 explained
                                above. The form should create a new user.
     * template_name: Template to use. Uses 'facebook/setup.html' by default.
     * extra_context: A context object whose contents will be passed to the template.
    """
    log.debug('in setup view')
    #you need to be logged into facebook.
    if not request.facebook.uid:
        log.debug('Need to be logged into facebook')
        url = reverse(facebook_login)
        if request.REQUEST.get(REDIRECT_FIELD_NAME,False):
            url += "?%s=%s" % (REDIRECT_FIELD_NAME, request.REQUEST[REDIRECT_FIELD_NAME])
        return HttpResponseRedirect(url)

    #setup forms
    login_form = AuthenticationForm()
    registration_form = registration_form_class()

    #figure out where to go after setup
    if request.REQUEST.get(REDIRECT_FIELD_NAME,False):
        redirect_url = request.REQUEST[REDIRECT_FIELD_NAME]
    elif redirect_url is None:
        redirect_url = getattr(settings, "LOGIN_REDIRECT_URL", "/")

    #check that this fb user is not already in the system
    try:
        FacebookProfile.objects.get(facebook_id=request.facebook.uid)
        # already setup, move along please
        return HttpResponseRedirect(redirect_url)
    except FacebookProfile.DoesNotExist, e:
        # not in the db, ok to continue
        pass

    #user submitted a form - which one?
    if request.method == "POST":
        log.debug('Submitted form')
        #lets setup a facebook only account. The user will have to use
        #facebook to login.
        if request.POST.get('facebook_only',False):
            log.debug('Facebook Only')
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            user = User(username=request.facebook.uid,
                        email=profile.email)
            user.set_unusable_password()
            user.save()
            profile.user = user
            profile.save()
            log.info("Added user and profile for %s!" % request.facebook.uid)
            user = authenticate(request=request)
            login(request, user)
            return HttpResponseRedirect(redirect_url)
        
        # user setup his/her own local account in addition to their facebook
        # account. The user will have to login with facebook unless they 
        # reset their password.
        elif request.POST.get('register',False):
            log.debug('Register a new account')
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            if profile.first_name != "(Private)":
                fname = profile.first_name
            if profile.last_name != "(Private)":
                lname = profile.last_name
            user = User(first_name=fname, last_name=lname)
            registration_form = registration_form_class(
                                        data=request.POST, instance=user)
            if registration_form.is_valid():
                user = registration_form.save()
                profile.user = user
                profile.save()
                log.info("Added user and profile for %s!" % request.facebook.uid)
                login(request, authenticate(request=request))
                return HttpResponseRedirect(redirect_url)
            else:
                request.user = User()
                request.user.facebook_profile = FacebookProfile(facebook_id=request.facebook.uid)
    
        #user logs in in with an existing account, and the two are linked.
        elif request.POST.get('login',False):
            login_form = AuthenticationForm(data=request.POST)

            if login_form.is_valid():
                user = login_form.get_user()
                log.debug("Trying to setup FB: %s, %s" % (user,request.facebook.uid))
                if user and user.is_active:
                    FacebookProfile.objects.get_or_create(user=user, facebook_id=request.facebook.uid)
                    log.info("Attached facebook profile %s to user %s!" % (request.facebook.uid, user))
                    login(request, user)
                    return HttpResponseRedirect(redirect_url)
            else:
                request.user = User()
                request.user.facebook_profile = FacebookProfile(facebook_id=request.facebook.uid)
    
    #user didn't submit a form, but is logged in already. We'll just link up their facebook
    #account automatically.
    elif request.user.is_authenticated():
        log.debug('Already logged in')
        try:
            request.user.facebook_profile
        except FacebookProfile.DoesNotExist:
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            profile.user = request.user
            profile.save()
            log.info("Attached facebook profile %s to user %s!" % (profile.facebook_id,profile.user))

        return HttpResponseRedirect(redirect_url)
    
    # user just showed up
    else:
        log.debug('Setting up form...')
        request.user.facebook_profile = profile = FacebookProfile(facebook_id=request.facebook.uid)
        login_form = AuthenticationForm(request)
        log.debug('creating a dummy user')
        fname = lname = ''
        if profile.first_name != "(Private)":
            fname = profile.first_name
        if profile.last_name != "(Private)":
            lname = profile.last_name
        user = User(first_name=fname, last_name=lname)
        registration_form = registration_form_class(instance=user)
    
    log.debug('going all the way...')
    
    # add the extra_context to this one
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    template_dict = {
        "login_form":login_form,
        "registration_form":registration_form
    }
    
    # we only need to set next if its been passed in the querystring or post vars
    if request.REQUEST.get(REDIRECT_FIELD_NAME, False):
        template_dict.update( {REDIRECT_FIELD_NAME: request.REQUEST[REDIRECT_FIELD_NAME]})
        
    return render_to_response(
        template_name,
        template_dict,
        context_instance=context)

Example 46

Project: talk.org Source File: main.py
Function: change_stage
def change_stage(request, app_label, model_name, object_id):
    model = models.get_model(app_label, model_name)
    object_id = unquote(object_id)
    if model is None:
        raise Http404("App %r, model %r, not found" % (app_label, model_name))
    opts = model._meta

    if not request.user.has_perm(app_label + '.' + opts.get_change_permission()):
        raise PermissionDenied

    if request.POST and "_saveasnew" in request.POST:
        return add_stage(request, app_label, model_name, form_url='../../add/')

    try:
        manipulator = model.ChangeManipulator(object_id)
    except model.DoesNotExist:
        raise Http404('%s object with primary key %r does not exist' % (model_name, escape(object_id)))

    if request.POST:
        new_data = request.POST.copy()

        if opts.has_field_type(models.FileField):
            new_data.update(request.FILES)

        errors = manipulator.get_validation_errors(new_data)
        manipulator.do_html2python(new_data)

        if not errors:
            new_object = manipulator.save(new_data)
            pk_value = new_object._get_pk_val()

            # Construct the change message.
            change_message = []
            if manipulator.fields_added:
                change_message.append(_('Added %s.') % get_text_list(manipulator.fields_added, _('and')))
            if manipulator.fields_changed:
                change_message.append(_('Changed %s.') % get_text_list(manipulator.fields_changed, _('and')))
            if manipulator.fields_deleted:
                change_message.append(_('Deleted %s.') % get_text_list(manipulator.fields_deleted, _('and')))
            change_message = ' '.join(change_message)
            if not change_message:
                change_message = _('No fields changed.')
            LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), CHANGE, change_message)

            msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)}
            if "_continue" in request.POST:
                request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
                if '_popup' in request.REQUEST:
                    return HttpResponseRedirect(request.path + "?_popup=1")
                else:
                    return HttpResponseRedirect(request.path)
            elif "_saveasnew" in request.POST:
                request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)})
                return HttpResponseRedirect("../%s/" % pk_value)
            elif "_addanother" in request.POST:
                request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
                return HttpResponseRedirect("../add/")
            else:
                request.user.message_set.create(message=msg)
                return HttpResponseRedirect("../")
    else:
        # Populate new_data with a "flattened" version of the current data.
        new_data = manipulator.flatten_data()

        # TODO: do this in flatten_data...
        # If the object has ordered objects on its admin page, get the existing
        # order and flatten it into a comma-separated list of IDs.

        id_order_list = []
        for rel_obj in opts.get_ordered_objects():
            id_order_list.extend(getattr(manipulator.original_object, 'get_%s_order' % rel_obj.object_name.lower())())
        if id_order_list:
            new_data['order_'] = ','.join(map(str, id_order_list))
        errors = {}

    # Populate the FormWrapper.
    form = oldforms.FormWrapper(manipulator, new_data, errors)
    form.original = manipulator.original_object
    form.order_objects = []

    #TODO Should be done in flatten_data  / FormWrapper construction
    for related in opts.get_followed_related_objects():
        wrt = related.opts.order_with_respect_to
        if wrt and wrt.rel and wrt.rel.to == opts:
            func = getattr(manipulator.original_object, 'get_%s_list' %
                    related.get_accessor_name())
            orig_list = func()
            form.order_objects.extend(orig_list)

    c = template.RequestContext(request, {
        'title': _('Change %s') % force_unicode(opts.verbose_name),
        'form': form,
        'object_id': object_id,
        'original': manipulator.original_object,
        'is_popup': '_popup' in request.REQUEST,
    })
    return render_change_form(model, manipulator, c, change=True)

Example 47

Project: PyClassLessons Source File: comments.py
@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = apps.get_model(ctype)
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except LookupError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.model_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.model_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    return next_redirect(request, fallback=next or 'comments-comment-done',
        c=comment._get_pk_val())

Example 48

Project: Observatory Source File: projects.py
@login_required
def modify(request, project_url_path, tab_id = 1):
  # redirect if the url path is not in the correct format
  resp = force_url_paths(modify, project_url_path)
  if resp: return resp
  
  project = get_object_or_404(Project, url_path = project_url_path)
  screenshots = Screenshot.objects.filter(project = project)
  
  # if someone tries to edit a project they shouldn't be able to
  if not (request.user in project.authors.all() or request.user.info.mentor):
    return HttpResponseRedirect(reverse(show, args = (project.url_path,)))
  
  # default forms
  project_form = ProjectForm(instance = project)
  cloned_repo_form = ClonedRepositoryForm(instance = project.repository)
  feed_repo_form = FeedRepositoryForm(instance = project.repository)
  blog_form = BlogForm(instance = project.blog)
  screenshot_form = UploadScreenshotForm()
  
  # if changes should be saved or rejected
  if request.POST:
    # uploading a screenshot
    if 'screenshot_upload' in request.POST:
      form = UploadScreenshotForm(request.POST, request.FILES)
      if form.is_valid():
        Screenshot.create(form, request.FILES["file"], project)
      else:
        screenshot_form = form

    # wrote a post with the js overlay
    if 'title' in request.POST and 'markdown' in request.POST:
      from dashboard.views.blogs import create_post_real
      return create_post_real(request.POST)

    # editing the project's information
    elif 'title' in request.POST:
      form = ProjectForm(request.POST)
      
      # if the form is valid, save
      if form.is_valid():
        project.title = form.cleaned_data['title']
        project.website = form.cleaned_data['website']
        project.wiki = form.cleaned_data['wiki']
        project.description = form.cleaned_data['description']
        project.active = form.cleaned_data['active']
        project.save()
        project_form = ProjectForm(instance = project)
      
      # otherwise, display the errors
      else:
        project_form = form
    
    # editing a cloned repository
    elif 'clone_url' in request.POST:
      form = ClonedRepositoryForm(request.POST)
      
      if form.is_valid():
        project.repository.web_url = form.cleaned_data['web_url']
        project.repository.clone_url = form.cleaned_data['clone_url']
        project.repository.vcs = form.cleaned_data['vcs']
        project.repository.from_feed = False
        project.repository.save()
        cloned_repo_form = ClonedRepositoryForm(instance = project.repository)
      else:
        cloned_repo_form = form
    
    # editing a feed repository
    elif 'repo_rss' in request.POST:
      form = FeedRepositoryForm(request.POST)
      
      if form.is_valid():
        project.repository.repo_rss = form.cleaned_data['repo_rss']
        project.repository.cmd = form.cleaned_data['cmd']
        project.repository.web_url = form.cleaned_data['web_url']
        project.repository.from_feed = True
        project.repository.save()
        feed_repo_form = FeedRepositoryForm(instance = project.repository)
      else:
        feed_repo_form = form
    
    # editing a feed-based blog
    elif 'url' in request.POST:
      form = BlogForm(request.POST)
      
      if form.is_valid():
        project.blog.url = form.cleaned_data['url']
        project.blog.rss = form.cleaned_data['rss']
        project.blog.from_feed = True
        project.blog.save()
        blog_form = BlogForm(instance = project.blog)
      else:
        blog_form = form
    
    # switching to hosted blog
    elif 'switch-to-hosted' in request.POST:
      project.blog.from_feed = False
      project.blog.save()
      
  return render_to_response('projects/modify.html', {
    'project': project,
    'screenshots': screenshots,
    'project_form': project_form,
    'cloned_repo_form': cloned_repo_form,
    'feed_repo_form': feed_repo_form,
    'blog_form': blog_form,
    'screenshot_form': screenshot_form,
    'post_form': BlogPostForm(),
    'repo': project.repository,
    'tab': int(tab_id)
  }, context_instance = RequestContext(request))

Example 49

Project: django-admin-timeline Source File: views.py
@csrf_exempt
@never_cache
@staff_member_required
def log(request, template_name=TEMPLATE_NAME, \
        template_name_ajax=TEMPLATE_NAME_AJAX):
    """
    Get number of log entires. Serves both non-AJAX and AJAX driven requests.

    Since we have a breakdown of entries per day per entry and we have an AJAX
    driven infinite scroll and we want to avoid having duplicated date headers,
    we always pass a variable named "last_date" when making another request
    to our main AJAX-driven view. So... this is our case scenario:

    Initial timeline rendered as a normal HTML (non AJAX request) (from a list
    of log entries). We send date of last element as "last_date" to the context
    too, which will be used an an initial value for a global JavaScript
    variable. Later on that date will be used to send it to the AJAX driven
    view and used in rendering ("render_to_string" method). After we have
    rendered the HTML to send back, we get the last date of the last element
    and send it along with the HTML rendered to our view in JSON response.
    When receiving the JSON response, we update the above mentioned global
    JavaScript variable with the value given.

    :param request: django.http.HttpRequest
    :param template_name: str
    :param template_name_ajax: str
    :return: django.http.HttpResponse

    This view accepts the following POST variables (all optional).
    :param page: int - Page number to get.
    :param user_id: int - If set, used to filter the user by.
    :param last_date: str - Example value "2012-05-24".
    :param start_date: str - If set, used as a start date to filter the actions
        with. Example value "2012-05-24".
    :param end_date: str - If set, used as an end date to filter the actions
        with. Example value "2012-05-24".

    NOTE: If it gets too complicatd with filtering, we need to have forms to
    validate and process the POST data.
    """
    def _get_date_from_string(s):
        """
        Gets date from a string given.

        :param s: str - date in string format
        :return: datetime.datetime
        """
        try:
            return datetime.date(*map(lambda x: int(x), s.split("-")))
        except Exception as e:
            return ""

    try:
        page = int(request.POST.get('page', 1))
        if page < 1:
            page = 1
    except Exception as e:
        page = 1

    users = []
    content_types = []
    filter_form = None

    if 'POST' == request.method:
        post = dict(request.POST)
        if 'users[]' in post:
            post['users'] = post.pop('users[]')
        if 'content_types[]' in post:
            post['content_types'] = post.pop('content_types[]')

        filter_form = FilterForm(post)
        if filter_form.is_valid():
            users = filter_form.cleaned_data['users']
            content_types = filter_form.cleaned_data['content_types']
        else:
            pass # Anything to do here?
    else:
        filter_form = FilterForm()

    # Some kind of a pagination
    start = (page - 1) * NUMBER_OF_ENTRIES_PER_PAGE
    end = page * NUMBER_OF_ENTRIES_PER_PAGE

    # Getting admin log entires taking page number into consideration.
    log_entries = LogEntry.objects.all().select_related('content_type', 'user')

    start_date = _get_date_from_string(request.POST.get('start_date'))
    end_date = _get_date_from_string(request.POST.get('end_date'))

    if start_date:
        log_entries = log_entries.filter(action_time__gte=start_date) # TODO

    if end_date:
        log_entries = log_entries.filter(action_time__lte=end_date) # TODO

    # If users given, filtering by users
    if users:
        log_entries = log_entries.filter(user__id__in=users)

    # If content types given, filtering by content types
    if content_types:
        log_entries = log_entries.filter(content_type__id__in=content_types)

    # Applying limits / freezing the queryset
    log_entries = log_entries[start:end]

    if log_entries:
        last_date = date_format(
            log_entries[len(log_entries) - 1].action_time, "Y-m-d"
            )
    else:
        last_date = request.POST.get('last_date', None)

    # Using different template for AJAX driven requests
    if request.is_ajax():
        # Context to render the AJAX driven HTML with
        context = {
            'admin_log': log_entries,
            'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE,
            'page': page,
            'last_date': request.POST.get('last_date', None),
            'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT,
            'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': \
                LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT
        }

        # Rendering HTML for an AJAX driven request
        html = render_to_string(
            template_name_ajax,
            context,
            context_instance=RequestContext(request)
        )

        # Context to send back to user in a JSON response
        context = {
            'html': html,
            'last_date': last_date,
            'success': 1 if len(log_entries) else 0
        }
        return HttpResponse(json.dumps(context))

    # Context for a non-AJAX request
    context = {
        'admin_log': log_entries,
        'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE,
        'page': page,
        'last_date': last_date,
        'start_date': date_format(start_date, "Y-m-d") if start_date else "",
        'end_date': date_format(end_date, "Y-m-d") if end_date else "",
        'users': [int(u) for u in users],
        'content_types': [int(ct) for ct in content_types],
        'filter_form': filter_form,
        'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT,
        'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': \
            LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT,
        'title': _("Timeline") # For template breadcrumbs, etc.
    }

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )

Example 50

Project: tendenci Source File: views.py
def multi_register(request, event_id, template_name="events/registration/multi_register.html"):
    """
    This view is where a user defines the specifics of his/her registrations.
    A registration set is a set of registrants (one or many) that comply with a specific pricing.
    A pricing defines the maximum number of registrants in a registration set.
    A user can avail multiple registration sets.

    If the site setting anonymousmemberpricing is enabled,
    anonymous users can select non public pricings in their registration sets,
    provided that the first registrant of every registration set's email is validated to be an existing user.

    If the site setting anonymousmemberpricing is disabled,
    anonymous users will not be able to see non public prices.
    """

    # redirect to default registration if anonymousmemberpricing not enabled
    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        return redirect('event.multi_register', event_id)

    # clear user list session
    request.session['user_list'] = []

    event = get_object_or_404(Event, pk=event_id)

    # check if event allows registration
    if (event.registration_configuration is None or not event.registration_configuration.enabled):
        raise Http404

    # check if it is still open, always open for admin users
    if not request.user.profile.is_superuser:
        status = reg_status(event, request.user)
        if status == REG_FULL:
            messages.add_message(request, messages.ERROR, _('Registration is full.'))
            return redirect('event', event.pk)
        elif status == REG_CLOSED:
            messages.add_message(request, messages.ERROR, _('Registration is closed.'))
            return redirect('event', event.pk)

    user = AnonymousUser()
    # get available pricings
    active_pricings = get_active_pricings(event)
    event_pricings = event.registration_configuration.regconfpricing_set.all()

    # get available addons
    active_addons = get_active_addons(event)

    # check if use a custom reg form
    custom_reg_form = None
    reg_conf = event.registration_configuration
    if reg_conf.use_custom_reg_form:
        if reg_conf.bind_reg_form_to_conf_only:
            custom_reg_form = reg_conf.reg_form

    #custom_reg_form = None

    if custom_reg_form:
        RF = FormForCustomRegForm
    else:
        RF = RegistrantForm

    # start the form set factory
    RegistrantFormSet = formset_factory(
        RF,
        formset=RegistrantBaseFormSet,
        can_delete=True,
        extra=0,
    )

    RegAddonFormSet = formset_factory(
        RegAddonForm,
        formset=RegAddonBaseFormSet,
        extra=0,
    )

    if request.method == "POST":
        # process the submitted forms
        params = {'prefix': 'registrant',
                 'event': event,
                 'extra_params': {
                                  'pricings':event_pricings,
                                  }
                  }
        if custom_reg_form:
            params['extra_params'].update({"custom_reg_form": custom_reg_form,
                                           'event': event})
        reg_formset = RegistrantFormSet(request.POST,
                            **params)

        reg_form = RegistrationForm(event, request.user, request.POST,
                    reg_count = len(reg_formset.forms))

        # This form is just here to preserve the data in case of invalid registrants
        # The real validation of addons is after validation of registrants
        addon_formset = RegAddonFormSet(request.POST,
                            prefix='addon',
                            event=event,
                            extra_params={
                                'addons':active_addons,
                                'valid_addons':active_addons,
                            })
        addon_formset.is_valid()

        # validate the form and formset
        if False not in (reg_form.is_valid(), reg_formset.is_valid()):
            valid_addons = get_addons_for_list(event, reg_formset.get_user_list())
            # validate the addons
            addon_formset = RegAddonFormSet(request.POST,
                            prefix='addon',
                            event=event,
                            extra_params={
                                'addons':active_addons,
                                'valid_addons':valid_addons,
                            })
            if addon_formset.is_valid():
                # process the registration
                # this will create the registrants and apply the discount
                reg8n = process_registration(reg_form, reg_formset,  addon_formset, custom_reg_form=custom_reg_form)

                self_reg8n = get_setting('module', 'users', 'selfregistration')
                is_credit_card_payment = (reg8n.payment_method and
                    (reg8n.payment_method.machine_name).lower() == 'credit-card'
                    and reg8n.amount_paid > 0)
                registrants = reg8n.registrant_set.all().order_by('id')
                for registrant in registrants:
                    #registrant.assign_mapped_fields()
                    if registrant.custom_reg_form_entry:
                        registrant.name = registrant.custom_reg_form_entry.__unicode__()
                    else:
                        registrant.name = ' '.join([registrant.first_name, registrant.last_name])

                if is_credit_card_payment: # online payment
                    # email the admins as well
                    email_admins(event, reg8n.amount_paid, self_reg8n, reg8n, registrants)
                    # get invoice; redirect to online pay
                    return redirect('payment.pay_online',
                        reg8n.invoice.id, reg8n.invoice.guid)
                else:
                    # offline payment
                    # email the registrant
                    send_registrant_email(reg8n, self_reg8n)
                    # email the admins as well
                    email_admins(event, reg8n.amount_paid, self_reg8n, reg8n, registrants)

                EventLog.objects.log(instance=event)

                # redirect to confirmation
                return redirect('event.registration_confirmation', event_id, reg8n.registrant.hash)
    else:
        params = {'prefix': 'registrant',
                    'event': event,
                    'extra_params': {
                        'pricings':event_pricings,
                    }
                  }
        if custom_reg_form:
            params['extra_params'].update({"custom_reg_form": custom_reg_form,
                                           'event': event})
        # intialize empty forms
        reg_formset = RegistrantFormSet(**params)
        reg_form = RegistrationForm(event, request.user)
        addon_formset = RegAddonFormSet(
                            prefix='addon',
                            event=event,
                            extra_params={
                                'addons':active_addons,
                            })

    sets = reg_formset.get_sets()

    # build our hidden form dynamically
    hidden_form = None
    if custom_reg_form:
        params = {'prefix': 'registrant',
                  'event': event,
                  'extra_params': {
                        'pricings':event_pricings,
                        'custom_reg_form': custom_reg_form,
                        'event': event
                    }
                  }
        FormSet = formset_factory(
            FormForCustomRegForm,
            formset=RegistrantBaseFormSet,
            can_delete=True,
            extra=1,
        )
        formset = FormSet(**params)
        hidden_form = formset.forms[0]


    return render_to_response(template_name, {
            'event':event,
            'reg_form':reg_form,
            'custom_reg_form': custom_reg_form,
            'hidden_form': hidden_form,
            'registrant': reg_formset,
            'addon_formset': addon_formset,
            'sets': sets,
            'addons':active_addons,
            'pricings':active_pricings,
            'anon_pricing':True,
            'total_price':reg_formset.get_total_price()+addon_formset.get_total_price(),
            'allow_memberid_pricing':get_setting('module', 'events', 'memberidpricing'),
            'shared_pricing':get_setting('module', 'events', 'sharedpricing'),
            }, context_instance=RequestContext(request))
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4