Esempio n. 1
0
def signup(request):
    status = 0
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    else:
        if request.method == 'POST':
            form = SignupForm(request.POST)
            if form.is_valid():
                if form.cleaned_data.get('username') and form.cleaned_data.get('password') and form.cleaned_data.get('email'):
                    username = form.cleaned_data.get('username')
                    password = form.cleaned_data.get('password')
                    email = form.cleaned_data.get('email')
                    User.objects.create_user(username=username, password=password, email=email,
                                             first_name='No', last_name='Name')
                    MyUser.objects.create(user=User.objects.get(username=username))
                    status = 1
        else:
            form = SignupForm()

        context = RequestContext(request, {
            'form': form,
            'status': status,
        })
        context.update(csrf(request))

        return render_to_response("signup.html", context)
Esempio n. 2
0
def render_admin_menu_item(request, page, template=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/menu_item.html"

    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE) # Not found - tree will remove item
        
    # languages
    languages = []
    if page.site_id in settings.CMS_SITE_LANGUAGES:
        languages = settings.CMS_SITE_LANGUAGES[page.site_id]
    else:
        languages = [x[0] for x in settings.CMS_LANGUAGES]
    
    context = RequestContext(request, {
        'has_add_permission': permissions.has_page_add_permission(request),
        'site_languages': languages,
    })
    
    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered))
    # add mimetype to help out IE
    return render_to_response(template, context, mimetype="text/html; charset=utf-8")
Esempio n. 3
0
def lightbox_login(request):
    t = loader.get_template('lightbox/login.html')
    c = RequestContext(request, {
        'subscribe_form': ExpressRegistrationForm(),
    })
    c.update(csrf(request))
    return HttpResponse(t.render(c))
def add_occurrence(request):

    t = loader.get_template('add-occurrence.html')
    c = RequestContext(request)
    c.update(csrf(request))

    return HttpResponse(t.render(c))
Esempio n. 5
0
def user_manage(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if not request.user.is_authenticated():
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    context["device"] = device_check(request)
    return HttpResponse(get_template("manage.html").render(context))
Esempio n. 6
0
def confirm(request):
    context = RequestContext(request)
    context.update(csrf(request))

    if not request.user.is_authenticated():
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")

    if not request.method == "POST":
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    value = []
    for key in request.POST:
        if key[:4] == "dish" and request.POST[key] == u"on":
            try:
                value.append(int(key[4:]))
            except:
                return HttpResponse("Error {0}: {1}".format(str(exc_info()[0]), exc_info()[1]))

    tDishes = Dish.objects.filter(numbro__in=value)
    summ = 0
    for item in tDishes:
        summ += item.price
    context["tDishes"] = tDishes
    context["summ"] = summ
    context["device"] = device_check(request)
    return HttpResponse(get_template("omnomnom/confirm.html").render(context))
Esempio n. 7
0
def add(request):
    """
    @attention: 发表评论
    """
    content = request.POST.get('content', '').strip()
    nick = request.POST.get('nick', '').strip()
    email = request.POST.get('email', '').strip()
    user_href = request.POST.get('user_href', '').strip()

    outerobj_type = request.POST.get('outerobj_type', 'default')
    outerobj_id = request.POST.get('outerobj_id')
    comment_show_type = request.POST.get('comment_show_type', 0)

    cob = interface.CommentOperateBase()
    flag, result = cob.add(nick, email, user_href, content, outerobj_type, outerobj_id, ip=utils.get_clientip(request))
    if flag:
        lst_comment = format_outerobj_comment([result, ], request.user)
        # 两种类型,一种给用于单条外部对象,一条用于可能有多条的
        tem = template.loader.get_template('comment/_comment_single_list%s.html' % comment_show_type)
        context_instance = RequestContext(request)
        context_instance.update(dict(c=lst_comment[0], outerobj_type=outerobj_type, outerobj_id=outerobj_id))

        # 设置留言用户session
        request.session['comment_user'] = dict(nick=nick, email=email, user_href=user_href)
        return HttpResponse(tem.render(template.Context(context_instance, autoescape=False)))
    else:
        return HttpResponse('$%s' % result)
Esempio n. 8
0
def multipartite_view_sbol(request, multi_type=None):
    'view of the multipartite tool'

    if multi_type is None:
        return render_to_response('multipartite_initial.html', {},
                                  context_instance=RequestContext(request))
    elif multi_type not in PARTS_TO_ASSEMBLE.keys():
        return Http404
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        request_data = request.POST
    elif request.method == 'GET':
        request_data = request.GET
    else:
        request_data = None
    form_class = get_multipartite_form(multi_type, request.user)
    if request_data:
        form = form_class(request_data)

        if form.is_valid():
            multi_form_data = form.cleaned_data
            part_types = [p[0] for p in PARTS_TO_ASSEMBLE[multi_type]]
            assembled_seq = assemble_parts(multi_form_data, part_types)
            filename = assembled_seq.name + '.xml'
            response = HttpResponse(convert_to_sbol(assembled_seq),
                                    content_type='xml/plain')
            response['Content-Disposition'] = 'attachment; '
            response['Content-Disposition'] += 'filename="{0}"'.format(filename)
            return response
    return HttpResponseBadRequest()
Esempio n. 9
0
def get_placeholders(request, template=None):
    """
    Return a list of PlaceholderNode found in the given template
    """
    if not template:
        template = get_template_from_request(request)
    try:
        temp = loader.get_template(template)
    except TemplateDoesNotExist:
        return []
    user = request.user
    request.user = AnonymousUser()
    context = RequestContext(request)#details(request, no404=True, only_context=True)
    template = get_template_from_request(request)
    old_page = request.current_page
    request.current_page = "dummy"
    
    context.update({'template':template,
                    'request':request,
                    'display_placeholder_names_only': True,
                    'current_page': "dummy",
                    })
    output = temp.render(context)
    request.user = user
    placeholders = re.findall("<!-- PlaceholderNode: (.+?) -->", output)
    request.current_page = old_page
    return placeholders
Esempio n. 10
0
def render_single_to_response(request, comic, template='comics/single.html', contextDict=None):
    t = loader.get_template(template)
    c = RequestContext(request)
    thisId = comic.id
    # The out-commented alternatives should not be necessary because a webcomic should follow a strict id sequence
    firstId = 1
#    firstId = Comic.objects.order_by('dateTime')[0].id
    if firstId == thisId:
        firstId = 0
    latestId = get_published_comics().order_by('-dateTime')[0].id
    if latestId == thisId:
        latestId = 0
    prevId = 0
    if firstId:
        prevId = thisId - 1
#        prevId = Comic.objects.filter(dateTime__lt=comic.dateTime).order_by('-dateTime')[0].id
    nextId = 0
    if latestId:
        nextId = thisId + 1
#        nextId = Comic.objects.filter(datetime__gt=comic.dateTime).order_by('dateTime')[0].id
    c.update({
        'baseUrl': request.build_absolute_uri('/')[:-1],
        'comic': comic,
        'comicTemplate': 'comics/types/{0}.html'.format( comic.type.lower() ),
        'title': comic.title,
        'subtitle': comic.get_comic_obj().pageSubtitle,
        'firstId': firstId,
        'latestId': latestId,
        'prevId': prevId,
        'nextId': nextId
    })
    if contextDict:
        c.update(contextDict)
    return HttpResponse( t.render(c) )
Esempio n. 11
0
def connect(request):
    '''
    Exception and validation functionality around the _connect view
    Separated this out from _connect to preserve readability
    Don't bother reading this code, skip to _connect for the bit you're interested in :)
    '''
    facebook_login = to_bool(request.REQUEST.get('facebook_login'))
    context = RequestContext(request)

    #validation to ensure the context processor is enabled
    if not context.get('FACEBOOK_APP_ID'):
        message = 'Please specify a Facebook app id and ensure the context processor is enabled'
        raise ValueError(message)

    #hide the connect page, convenient for testing with new users in production though
    if not facebook_login and not settings.DEBUG and facebook_settings.FACEBOOK_HIDE_CONNECT_TEST:
        raise Http404('not showing the connect page')

    try:
        response = _connect(request, facebook_login)
    except open_facebook_exceptions.FacebookUnreachable, e:
        #often triggered when Facebook is slow
        warning_format = u'%s, often caused by Facebook slowdown, error %s'
        warn_message = warning_format % (type(e), e.message)
        send_warning(warn_message, e=e)
        response = error_next_redirect(request,
                                       additional_params=dict(
                                           fb_error_or_cancel=1)
                                       )
Esempio n. 12
0
def draw_chart(request):
    
    def validate_and_get_date(request):
        date_from = request.GET.get('date_from')
        date_to = request.GET.get('date_to')
        date_from = datetime.datetime.strptime(date_from, '%Y-%m-%d').date()
        date_to = datetime.datetime.strptime(date_to, '%Y-%m-%d').date()
        if date_to < date_from:
            messages.error(request, _('Invalid period entered'))
            return HttpResponseRedirect(request.META['HTTP_REFERER']), date_to, date_from
        return None, date_to, date_from
    
    group = None
    if request.GET.get('group'):
        group = request.GET.get('group')
    response, date_to, date_from = validate_and_get_date(request)
    if response:
        return response
    quality = Orderfailure.calculate_service_level(date_from, date_to, group)
    tooltip_date = "%d %b %Y %H:%M:%S %p"
    extra_series = {"tooltip": {"y_start": "", "y_end": " calls"},
                    "date_format": tooltip_date}
    chartdata = {
        'x': quality.keys(),
        'name1': _('Quality cofficient'), 'y1': quality.values(), 'extra1': extra_series
    }
    charttype = "cumulativeLineChart"
    data = {
        'charttype': charttype,
        'chartdata': chartdata,
    }
    rc = RequestContext(request, {})
    rc.autoescape = False
    res = render_to_response('graph.html', data, rc)
    return res
Esempio n. 13
0
def connect(request, graph):
    '''
    Exception and validation functionality around the _connect view
    Separated this out from _connect to preserve readability
    Don't bother reading this code, skip to _connect for the bit you're interested in :)
    '''
    backend = get_registration_backend()
    context = RequestContext(request)

    # validation to ensure the context processor is enabled
    if not context.get('FACEBOOK_APP_ID'):
        message = 'Please specify a Facebook app id and ensure the context processor is enabled'
        logger.info('CO01 Please specify a Facebook app id and ensure the context processor is enabled')
        raise ValueError(message)

    try:
        response = _connect(request, graph)
    except open_facebook_exceptions.FacebookUnreachable, e:
        logger.info('CO02 Probably slow FB')
        # often triggered when Facebook is slow
        warning_format = u'%s, often caused by Facebook slowdown, error %s'
        warn_message = warning_format % (type(e), e.message)
        send_warning(warn_message, e=e)
        additional_params = dict(fb_error_or_cancel=1)
        response = backend.post_error(request, additional_params)
Esempio n. 14
0
def multipartite_view_free_sbol(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        request_data = request.POST
    else:
        msg = "To get the sequence you need first to assemble parts"
        return HttpResponseBadRequest(msg)

    feats = [request_data['vector']]
    for k in sorted(request_data.keys()):
        if 'part_' in k:
            feats.append(request_data[k])

    form_class = get_multipartite_free_form(feats)
    form = form_class(request_data)
    if form.is_valid():
        last_feat = Feature.objects.get(uniquename=feats[-1])
        last_suffix = last_feat.suffix
        if last_suffix == 'CGCT':
            protocol_data, part_order = _get_fragments_from_request(request)
            assembled_seq = assemble_parts(protocol_data, part_order)
            response = HttpResponse(convert_to_sbol(assembled_seq),
                                    content_type='xml/plain')
            filename = assembled_seq.name + '.xml'
            response['Content-Disposition'] = 'attachment; '
            response['Content-Disposition'] += 'filename="{0}"'.format(filename)
            return response

    return HttpResponseBadRequest('There was an error in the assembly')
Esempio n. 15
0
def get_outerobj_comment(request):
    outerobj_type = request.POST.get('outerobj_type')
    outerobj_id = request.POST.get('outerobj_id')
    comment_show_type = request.POST.get('comment_show_type', 0)
    page_num = int(request.REQUEST.get('page', 1))
    # 能否发表评论权限判断
    can_create_comment_permission = request.POST.get('can_create_comment_permission', 'True')
    can_create_comment_permission = True if can_create_comment_permission == 'True' else False
    cob = interface.CommentOperateBase()
    objs = cob.get_outerobj_comment(outerobj_type, outerobj_id)

    # 分页
    page_objs = page.Cpt(objs, count=10, page=page_num).info
    objs = page_objs[0]
    page_params = (page_objs[1], page_objs[4])
    lst_comment = format_outerobj_comment(objs, request.user)

    from www.custom_tags.templatetags.custom_filters import paging
    from www.comment.interface import get_comment_page_onclick
    paging_html = paging(page_params, request, get_page_onclick=get_comment_page_onclick,
                         page_onclick_params=dict(outerobj_type=outerobj_type, outerobj_id=outerobj_id,
                                                  comment_show_type=comment_show_type,
                                                  can_create_comment_permission=can_create_comment_permission))

    # 两种类型,一种给用于单条外部对象,一条用于可能有多条的
    tem = template.loader.get_template('comment/_comment_sub%s.html' % comment_show_type)
    context_instance = RequestContext(request)
    context_instance.update(dict(lst_comment=lst_comment, outerobj_type=outerobj_type, outerobj_id=outerobj_id,
                                 request=request, paging_html=paging_html,
                                 can_create_comment_permission=can_create_comment_permission,
                                 comment_user=request.session.get('comment_user')))

    return HttpResponse(tem.render(template.Context(context_instance, autoescape=False)))
Esempio n. 16
0
def multipartite_view(request, multi_type=None):
    if multi_type is None:
        return render_to_response('multipartite_initial.html', {},
                                  context_instance=RequestContext(request))
    elif multi_type not in PARTS_TO_ASSEMBLE.keys():
        return Http404
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        request_data = request.POST
    elif request.method == 'GET':
        request_data = request.GET
    else:
        request_data = None
    form_class = get_multipartite_form(multi_type, request.user)
    if request_data:
        form = form_class(request_data)
        if form.is_valid():
            used_parts = OrderedDict()
            multi_form_data = form.cleaned_data
            for part_type in [p[0] for p in PARTS_TO_ASSEMBLE[multi_type]]:
                used_parts[part_type] = multi_form_data[part_type]
                used_parts[VECTOR_TYPE_NAME] = multi_form_data[VECTOR_TYPE_NAME]
            return render_to_response('multipartite_result.html',
                                      {'used_parts': used_parts,
                                       'multi_type': multi_type},
                                context_instance=RequestContext(request))
    else:
        form = form_class()

    context['form'] = form

    template = 'multipartite_template.html'
    content_type = None
    return render_to_response(template, context, content_type=content_type)
Esempio n. 17
0
def render_admin_menu_item(request, page, template=None, language=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/tree/menu_fragment.html"

    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE) # Not found - tree will remove item

    # languages
    from cms.utils import permissions
    languages = get_language_list(page.site_id)
    context = RequestContext(request, {
        'has_add_permission': permissions.has_page_add_permission(request),
        'site_languages': languages,
    })

    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered, language))
    # add mimetype to help out IE
    if DJANGO_1_4:
        return render_to_response(template, context, mimetype="text/html; charset=utf-8")
    else:
        return render_to_response(template, context, content_type="text/html; charset=utf-8")
Esempio n. 18
0
def home(request):
    context = RequestContext(request)
    context.update({ 'msg_body' : "List of all machines", })
    
    products = Product.objects.all()
    context.update({ 'products' : products, })
    return render_to_response("home.html", context_instance=context)
Esempio n. 19
0
def cfp(request):
    if request.method == "POST":
        context = {}
        context.update(csrf(request))
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            if 'next' in request.GET:
                next = request.GET['next']
                return HttpResponseRedirect(next)
            context['user'] = user
            return render_to_response('cfp.html', context)
        else:
            context['invalid'] = True
            context['form'] = UserLoginForm
            return render_to_response('cfp.html', context)
    else:
        form = UserLoginForm()
        context = RequestContext(request, {'request': request,
                                           'user': request.user,
                                           'form': form})
        context.update(csrf(request))
        return render_to_response('cfp.html',
                             context_instance=context)
Esempio n. 20
0
def order_delete(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if not request.user.is_authenticated:
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    if not request.method == "POST":
        return HttpResponse("(\/)~(-_-)~(\/) Вы не туда попали (\/)~(-_-)~(\/)")
    tDate = datetime.now()
    for key in request.POST:
        if key[:3] == "del" and request.POST[key] == u"on":
            try:
                value = int(key[3:])
                tOrder = Order.objects.get(id=value)
                tOrder_Log = Order_Log(
                    text="Заказ %s от %s был удалён %s в %s:%s:%s. Он содержал блюдо %s в кол-ве: %s"
                    % (
                        tOrder.customer,
                        tOrder.date.date(),
                        tDate.date(),
                        tDate.hour,
                        tDate.minute,
                        tDate.second,
                        tOrder.dish,
                        tOrder.count,
                    )
                )
                tOrder_Log.save()
                tOrder.delete()
            except:
                return HttpResponse("Error {0}: {1}".format(str(exc_info()[0]), exc_info()[1]))
    context["device"] = device_check(request)
    return HttpResponseRedirect("/order_today/")
Esempio n. 21
0
def File_form(request):
    if request.method == 'GET':
        form = FileForm()
        data_for_templete = {'form' : form}
        rc = RequestContext(request, {})
        rc.autoescape = False
        return render_to_response('stock_info/fileimport.html', data_for_templete, rc)
    else:
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            
            data = form.cleaned_data['file_name']
            try:
                results = Data_import(data)
                err_msg = []
                if results['not_found']:
                    err_msg.append(unicode(ugettext_lazy('Not found operations: %d' % results['not_found'])))
                if results['failed']:
                    err_msg.append(unicode(ugettext_lazy('Failed rows: %d' % results['failed'])))
                if len(err_msg) > 0:
                    messages.error(request, '; '.join(err_msg))
                else:
                    messages.info(request, unicode(ugettext_lazy('Success: %s rows' % results['success'])))
            except:
                messages.error(request, ugettext_lazy('Import failed'))
    return HttpResponseRedirect('/admin/stock_info/orderfailure')
Esempio n. 22
0
def experimentpage(request, exp_id,comesFromNewExp=False):
    view_url = '/experiments/'+exp_id
    #uploadFormForLiquidClasses = UploadForm()
    is_valid = False
    try:
        exp = Experiment.objects.get(pk = exp_id)
    except Exception as e:
        raise Http404
    if not request.user.is_authenticated():
         return index(request,message = 'user is not logged in')
    if request.method=='POST':
        f = ExperimentForm (request.POST,request.FILES,instance=exp)
        if f.is_valid() :
            is_valid = True
            exp = f.save()
    else:
        f= ExperimentForm(instance=exp)
        f.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
    _man = exp.manualFile.file.file
    _rob = exp.robotFile.file.file
    dilsList,pipetorsCV ,dilsListForLineChart= compareManualToRobotReaderForWebApp(manualExcelFile= _man,robotExcelFile=_rob, experiment=exp)
    upload_url, upload_data = prepare_upload(request, view_url)
    distance = abs(exp.getMeans()-exp.volume)
    c = RequestContext(request,{'exp':exp,'exp_id':exp_id,'form':f,'messege':'New experiment submitted successfully','pipetorsCV':pipetorsCV,'dilsList':dilsList,'dilsListForLineChart':dilsListForLineChart, 'upload_url':upload_url, 'upload_data':upload_data,
                                'comesFromNewExperiment':False,'distance':distance})
    c.update(csrf(request))
    return render_to_response('experiment_page.html',c)
Esempio n. 23
0
def get_placeholders(request):
    # Walk through all the templates which have a html extension
    placeholders = []
    for template_dir in settings.TEMPLATE_DIRS:
        for root, dirs, files in os.walk(template_dir):
            for file in files:
                ext = file.split(".")[-1]
                if ext == "html":
                    placeholders.append(os.path.join(root, file))

    # Update context and get current_placeholders
    context = RequestContext(request)
    context.update({'request': request,
                    'display_banner_names': True })
    current_placeholders = [(p.title) for p in Placeholder.objects.all()]

    # For every template retrieve the placeholders and add to the DB
    all_positions = set()
    for template in placeholders:
        file = open(template, 'r')
        temp_string = file.read()
        banner_re = r'{% banner (?P<title>[-\w]+).* %}'

        for match in re.finditer(banner_re, temp_string):
            title = match.group('title')
            all_positions.add(title)

            placeholder, created = Placeholder.objects.get_or_create(title=title)

    # Delete any non-existing placeholder
    removable = list(set(current_placeholders).difference(set(all_positions)))

    for placeholder in removable:
        Placeholder.objects.filter(title__iexact=placeholder).delete()
Esempio n. 24
0
    def __init__(self, request, dictionary = None, current_project = None, current_story = None):
        self.request = request

        if request.user.is_authenticated():
            project_list = request.user.project_set.all()
            if project_list is None or project_list.count() == 0:
                raise UserHasNoProjectException
        else:
            raise UserHasNoProjectException

        if current_project is None:
            current_project = project_list[0]
        else:
            current_project = Project.objects.get(pk = current_project)

        if current_story is not None:
            try:
                current_story = UserStory.objects.get(id = current_story)
            except UserStory.DoesNotExist:
                current_story = None

        if dictionary is None:
            self.dictionary = { 'project_list' : project_list,
                                'current_project' : current_project,
                                'current_story': current_story,
                                'last_page': request.path,
                                }
        else:
            self.dictionary = dictionary
            self.dictionary['project_list'] = project_list
            self.dictionary['current_project'] = current_project
            self.dictionary['current_story'] = current_story
            self.dictionary['last_page'] = request.path
        
        RequestContext.__init__(self, self.request, self.dictionary)
Esempio n. 25
0
def english_info(request):
    id = 0

    try:
        id = int(request.GET.get('id', 0))
    except Exception as e:
        log_info('english_info() errors: %s ' % str(e))

    data_dict = {}
    if not id:
        data_dict.update({'msg': ErrorCodeMsgList.INVALID_PARAMETER.message})
    else:
        item = English.get_dict_by_id(id)
        if item:
            item = format_english_dict(item, wechat=True)

        if not item:
            data_dict.update({'msg': ErrorCodeMsgList.INVALID_PARAMETER.message})
        else:
            data_dict.update(item)

    context = RequestContext(request)
    context.update(get_seo_context(request))
    context.update({'data': data_dict})
    return template_response('english/info.html', context_instance=context)
Esempio n. 26
0
def get_from_context(request, what, default=None):
    context = RequestContext(request)
    if hasattr(context, 'bind_template'):
        # Django 1.8: force context processors
        with context.bind_template(Template('')):
            return context.get(what, default)
    return context.get(what, default)
 def __init__(self, request, course=None, course_instance=None, **dict):
     RequestContext.__init__(self, 
                             request, 
                             dict)
     
     # Initially the user is neither an assistant nor a teacher
     is_assistant    = False
     is_teacher      = False
     
     # If the course is not given, but an instance is, get the instance's course
     if course == None and course_instance != None:
         course = course_instance.course
     
     if request.user.is_authenticated():
         # If the user is authenticated, populate is_assistant and is_teacher fields
         profile     = request.user.get_profile()
         
         if course != None and course.is_teacher(profile):
             # Teachers are also allowed to act as assistants
             is_teacher      = True
             is_assistant    = True
         elif course_instance != None and course_instance.is_assistant(profile):
             is_assistant    = True
     
     course_info     = {"is_teacher":    is_teacher,
                        "is_assistant":  is_assistant,
                        "instance":      course_instance,
                        "course":        course,
                        }
     
     self.update(course_info)
Esempio n. 28
0
 def config(self, request, context=None):
     """配置 include 必须的参数 request_context """
     request_context = RequestContext(request, {})
     for c in self.context.dicts:
         request_context.update(c)
     if context:
         request_context.update(context)
     self.request_context = request_context
    def _render_form_error(self, err_message):
        context = RequestContext(HttpRequest())
        data = {
            'message': err_message
        }

        context.update(data)
        return self.templates['form_error'].render(context)
Esempio n. 30
0
def main(request):
    context = RequestContext(request)
    context.update(csrf(request))
    if device_check(request) == "notPC":
        context["device"] = True
    else:
        context["device"] = False
    return HttpResponse(get_template("brand.html").render(context))
Esempio n. 31
0
def private_message_wall(request,link,**kwargs):
    debug=[]
    nm=NotificationManager()
    nm.set_sender(request.user.username, 'smtp.gmail.com', 465, '*****@*****.**', '13936344120lsqshr')
    #get all the groups this person registered
    try:
        debug.append("get user\n")
        sys_user = request.user
        #get the joinin user
        user = sys_user.joinin_user
    except JoinInUser.DoesNotExist:
        raise Exception("Sorry, this user does not exist. Please contact the system administrator." \
                        + "USERID:" + str(request.user.id))
    groups = user.groups.all()
    #create the messagewall instance for this view
    msgw = MessageWall(user=user)
    debug.append("ready for the from!")
    if link == 'view':
        #check if notification is set as read
        if kwargs.has_key('notification_id'):
            notification_id=kwargs['notification_id']
            #find the notification and set it as read 
            n=Notification.objects.get(id=notification_id)
            n.is_read=True
            n.save()
        #deal with the form
        if request.method == "POST":
            debug.append("get in deal with form,")
            if 'post_msg'  in request.POST: 
                form = SendMessageForm(request.user,None,request.POST)
                if form.is_valid():
                    debug.append("form valid!")
                    cd = form.cleaned_data
                    if cd.has_key('web_url'):
                        web_url = cd['web_url']
                    priority = cd['priority']
                    if cd.has_key('send_to'):
                        send_to = cd['send_to']
                        if send_to is u'':
                            send_to = None
                    else:
                        send_to = None
                    belongs_to = cd['belongs_to_group']
                    content = cd['content']
                    #get all the entities
                    try:
                        if send_to:
                            send_to = JoinInUser.objects.get(user__username=send_to)
                    except JoinInUser.DoesNotExist:
                        raise Exception("Fail to find the user to send the message. User with email:" + send_to + " does not exist.") 
                    try:
                        belongs_to = JoinInGroup.objects.get(id=belongs_to)
                    except JoinInGroup.DoesNotExist:
                        raise Exception("Fail to find the group to send the message. Group with name " + belongs_to + " does not exist.")
                    #send this message
                    debug.append("ready to send\n")
                    msgw.send_message(web_url=web_url, send_datetime=datetime.datetime.now(), \
                                      send_to=send_to, belongs_to_group=belongs_to, written_by=user, content=content,priority=priority)#did not include priority
                    #send notification to all of the members in that group
                    nm.send_notification(to_user=None, to_group=belongs_to, text=request.user.username+\
                                         " has posted a message in group "+belongs_to.name+".\n\n"\
                                         +str(datetime.datetime.now())+content, \
                                         url="/message_wall/view/", sys=False, email=True)
            elif 'reply' in request.POST:#write reply
                content=request.POST['content']
                message_id=long(request.POST['message_id'])
                group_id=request.POST['group_id']
                #get message to reply to
                try:
                    message=Message.objects.get(id=message_id)
                except Message.DoesNotExist:
                    raise Exception("message not found") 
                try:
                    group=JoinInGroup.objects.get(id=group_id)
                except JoinInGroup.DoesNotExist:
                    raise Exception("group not found")
                Message.objects.create(reply_to=message,priority=1,\
                                       send_datetime=datetime.datetime.now(), \
                                       update_datetime=datetime.datetime.now(),\
                                       belongs_to_group=group,\
                                       written_by=request.user.joinin_user,content=content)
                #change the parent message's update_datetime for sorting
                message.update_datetime=datetime.datetime.now() 
                message.save()
                return HttpResponseRedirect('/message_wall/view/')
            elif 'apply' in request.POST:
                #deal with the form
                if request.method == 'POST':
                    form=ApplyGroupForm(request.POST)
                    errors=[]
                    if form.is_valid():
                        cd=form.cleaned_data
                        group_name=cd['group_name']
                        #find the group
                        group_to_apply=None
                        try:
                            group_to_apply=JoinInGroup.objects.get(name=group_name)
                        except JoinInGroup.DoesNotExist:
                            errors.append("Sorry, group with name<b>"+group_name+"</b> does not exist, please check the name.")
                        #add the user to the appliers of that group
                        if request.user.joinin_user not in group_to_apply.appliers.all() or \
                                request.user.joinin_user not in group_to_apply.users.all():
                            group_to_apply.appliers.add(request.user.joinin_user)
                            
                        else:#TODO:
                            raise "You have applied for this group or you have been a member of this group. Please be patient for the acceptance."
                        #send notification
                        nm.send_notification(request.user.joinin_user, None, 'You have applied to join group '+group_to_apply.name\
                                             +'.Please wait for permission. Any of the members in this group are able to allow you to join in.', None) 
                        #redirect to the private message wall
                        return HttpResponseRedirect("/message_wall/view/")
                    else:#group name is not in the right format
                        errors.append("OOps!The group name is too long...")
                    if errors:    
                        return render_to_response("accounts_modules/apply_dialog.html",{'form':form,'errors':errors},\
                                          context_instance=RequestContext(request, {}))       
                    else:
                        form=ApplyGroupForm()
                    #show the apply group dialog
                    return render_to_response("accounts_modules/apply_dialog.html",{'form':form},\
                                              context_instance=RequestContext(request, {}))
            elif 'create_group' in request.POST:
                return create_group(request)
        else:
            pass
        #get all the private messages to this user
        p_msgs = msgw.retrieve_list()
        #refresh the form to render
        form = SendMessageForm(user=request.user)
        #add groups to the choicefield of the SendMessageForm
        #debug bundle
    #    debug=[]
    #    debug.append(user)
    #    debug.append(p_msgs)
        #get notifications
        if kwargs.has_key('see') and kwargs['see'] == 'all_notifications':
            notifications=nm.get_all_notification(user)
            see_all_notifications=True
        elif kwargs.has_key('see') and kwargs['see']=='unread_notifications' \
                or not kwargs.has_key('see'):
            notifications=nm.get_unread_notification(user)
            see_all_notifications=False
        return render_to_response('private_message_wall.html', {'form':form,\
                                                                'page_name':'Hi, '+user.user.username,\
                                                                'page_tag':'private',\
                                                                'private_messages':p_msgs,\
                                                                "groups":groups,'notifications':notifications,\
                                                                'see_all_notifications':see_all_notifications,\
                                                                "debug":debug,'user':request.user.joinin_user},\
                                                                context_instance=RequestContext(request, {}))
    #elif link=='apply':
        
    elif link == 'accept':#accept one groupe's invitation 
        #get groupto accept invitation
        group_id=long(kwargs['group_id'])
        try:
            group_to_join=JoinInGroup.objects.get(id=group_id)
        except JoinInGroup.DoesNotExist:
            #TODO:
            raise Exception("Sorry, This group does not exist any more.")
        #add this user to that group
        if request.user.joinin_user in group_to_join.invitations.all() and \
                request.user.joinin_user not in group_to_join.users.all():
            group_to_join.users.add(request.user.joinin_user)
            for msg in group_to_join.messages.all():
                PrivateMessage.objects.create(message=msg, belongs_to=request.user.joinin_user, read=False, priority=msg.priority, trashed=False)
        #delete the invitation
        group_to_join.invitations.remove(request.user.joinin_user)
        #TODO:send notification to this user
        nm.send_notification(request.user.joinin_user,None, \
                             "Congratulations, you are now in group "+group_to_join.name+'.',\
                              '/message_wall/group/'+str(group_to_join.id)+'/view/')
        return HttpResponseRedirect('/message_wall/view/')
    elif link == 'deny':
        #get groupto accept invitation
        group_id=long(kwargs['group_id'])
        try:
            group_to_join=JoinInGroup.objects.get(id=group_id)
        except JoinInGroup.DoesNotExist:
            #TODO:
            raise Exception("Sorry, This group does not exist any more.")
        #simply remove the user from the invitations
        group_to_join.invitations.remove(request.user.joinin_user)
        return HttpResponseRedirect('/message_wall/view/')           
Esempio n. 32
0
def handler500(request):
    response = render_to_response('errors/500custom.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response
Esempio n. 33
0
def add_event(request,
              template='schedule/schedule_form.html',
              event_form_class=ReferralForm,
              recurrence_form_class=ScheduleOccurrenceForm,
              redirect_to=None):

    # have to contains dtstart variable in URL. URL from schedule have to
    # contains date and time informations.
    if 'dtstart' not in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    if request.method == 'POST':
        if int(request.POST.get('count')) > 40:  # limit occurrence repeat
            return render_to_response(
                '403.html', {
                    'object':
                    _('Sorry. You can not book more than 40 occurrence at the same \
time')
                })
        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if invalid_delta_time(request.POST.get('start_time_delta'),
                                  request.POST.get('end_time_delta')):
                messages.error(
                    request,
                    _('The start time should be less than the end time'))
                return http.HttpResponseRedirect(
                    request.META.get('HTTP_REFERER') or '/schedule/')

            # filter devices based on selection
            devices = DeviceDetails.objects.filter(
                id__in=request.POST.getlist('device'))
            start_occurrence_date = end_occurrence_date = datetime(
                year=int(request.POST.get('until_year')),
                month=int(request.POST.get('until_month')),
                day=int(request.POST.get('until_day')))
            # create a start delta time
            start_delta = timedelta(
                seconds=int(request.POST.get('start_time_delta')))
            # checking till one minute before next session
            end_delta = timedelta(
                seconds=(int(request.POST.get('end_time_delta')) - 1))
            # get correct start time of device schedule
            start_device_schedule = (start_occurrence_date + start_delta)

            end_device_schedule = (end_occurrence_date + end_delta)
            # try to check if there's any occurrence with the device in
            # specified time
            occurrence_start = Occurrence.objects.filter(
                start_time__range=(start_device_schedule, end_device_schedule),
                scheduleoccurrence__device__in=devices,
            )
            # check exact end time
            end_delta = timedelta(
                seconds=int(request.POST.get('end_time_delta')))
            end_device_schedule = (end_occurrence_date + end_delta)
            occurrence_end = Occurrence.objects.filter(
                end_time__range=(start_device_schedule, end_device_schedule),
                scheduleoccurrence__device__in=devices,
            )
            if len(occurrence_start) is not 0 or len(occurrence_end) is not 0:
                error = recurrence_form._errors.setdefault(
                    'device', ErrorList())
                error.append('Selected device is busy')
            if request.POST.get('tabtitle'):  # booking single client
                if verify_client(request.POST.get('referral')) is False:
                    messages.error(request, _('Check the mandatory fields'))
                    return http.HttpResponseRedirect(
                        request.META.get('HTTP_REFERER') or '/schedule/')
                referral = get_object_or_404(Referral,
                                             pk=request.POST.get('referral'),
                                             service__organization=request.
                                             user.get_profile().org_active)
                event = recurrence_form.save(referral)
            elif request.POST.get('group'):  # booking a group
                group = get_object_or_404(ServiceGroup,
                                          pk=request.POST.get('group'),
                                          service__organization=request.user.
                                          get_profile().org_active,
                                          active=True)
                # this check is already done in template. just to prevent
                # empty groups
                if group.charged_members():
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                # ignore busy check
                                event = recurrence_form.save(
                                    group_member.referral, True)
            else:
                referral = get_object_or_404(
                    Referral,
                    pk=request.POST.get('select_referral'),
                    service__organization=request.user.get_profile(
                    ).org_active)
                event = recurrence_form.save(referral, True, True)
            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html',
                    dict(event=event),
                    context_instance=RequestContext(request))
    else:

        dtstart = parser.parse(request.GET['dtstart'])
        room = get_object_or_None(
            Room,
            pk=request.GET.get('room'),
            place__organization=request.user.get_profile().org_active)
        client = get_object_or_None(
            Client,
            pk=request.GET.get('client'),
            person__organization=request.user.get_profile().org_active)
        referral = get_object_or_None(
            Referral,
            pk=request.GET.get('referral'),
            service__organization=request.user.get_profile().org_active)
        event_form = event_form_class()

        recurrence_form = recurrence_form_class(initial=dict(
            dtstart=dtstart,
            day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            room=room.id,
        ))

        recurrence_form.fields['device'].widget.choices = ([
            (i.id, i) for i in DeviceDetails.objects.active(
                request.user.get_profile().org_active).filter(
                    Q(room=room) | Q(mobility="2", lendable=True)
                    | Q(place=room.place, mobility="2", lendable=False))
        ])

    return render_to_response(
        template,
        dict(
            dtstart=dtstart,
            event_form=event_form,
            recurrence_form=recurrence_form,
            group=ServiceGroup.objects.filter(
                service__organization=request.user.get_profile().org_active,
                active=True),
            room=room,
            object=client,
            referral=referral,
            referrals=Referral.objects.all(),
            room_id=room.id,
        ),
        context_instance=RequestContext(request))
Esempio n. 34
0
def _datetime_view(request,
                   template,
                   dt,
                   place,
                   referral=None,
                   client=None,
                   timeslot_factory=None,
                   items=None,
                   params=None):
    '''
        Tiago de Souza Moraes
        place: Place.id
    '''

    try:
        referral = Referral.objects.get(
            pk=referral,
            service__organization=request.user.get_profile().org_active)
    except:
        referral = None

    try:
        object = Client.objects.get(
            pk=client,
            person__organization=request.user.get_profile().org_active)
    except:
        object = ''

    place = Place.objects.get(pk=place)
    occurrences = ScheduleOccurrence.objects.filter(start_time__year=dt.year,
                                                    start_time__month=dt.month,
                                                    start_time__day=dt.day)

    # user = request.user
    timeslot_factory = timeslot_factory or create_timeslot_table
    params = params or {}

    data = dict(
        day=dt,
        next_day=dt + timedelta(days=+1),
        prev_day=dt + timedelta(days=-1),

        # get start_time and end_time_delta from place
        # get schedule slot time from organization
        timeslots=timeslot_factory(
            dt,
            items,
            start_time=datetime_.time(place.hours_work()[0],
                                      place.hours_work()[1]),
            end_time_delta=timedelta(hours=place.hours_work()[2]),
            time_delta=timedelta(minutes=int(
                request.user.get_profile().org_active.time_slot_schedule)),
            **params),
        places_list=Place.objects.active().filter(
            organization=request.user.get_profile().org_active.id),
        place=place,
        place_id=place.id,
        occurrences=occurrences,
        services=Service.objects.active().filter(
            organization=request.user.get_profile().org_active.id),
        professionals=CareProfessional.objects.active_all(
            request.user.get_profile().org_active.id),
        referral=referral,
        object=object,
        tab_daily_class="active",  # class object, tab menu
        restrict_schedule=hide_schedule_information(request.user))

    return render_to_response(
        template,
        data,
        context_instance=RequestContext(request),
    )
Esempio n. 35
0
def resource(request, slug):
    page = get_object_or_404(models.Resource, slug=slug)
    current_item = page.title
    return render_to_response('pages/content_type.html', {},
                              context_instance=RequestContext(
                                  request, locals()))
Esempio n. 36
0
def output_detail(request, pk):
    """
    This view is the single page of diplaying a progress bar for how
    close the job is to finishing, and then it will also display the
    job results if the job is done. Finally, it will render a 'job failed'
    page if the job has failed.
    """

    try:
        url = OutputUrl.objects.get(pk=pk)
    except:
        raise Http404

    model = url.unique_inputs

    taxcalc_vers_disp = get_version(url, 'taxcalc_vers', TAXCALC_VERSION)
    webapp_vers_disp = get_version(url, 'webapp_vers', WEBAPP_VERSION)

    context_vers_disp = {
        'taxcalc_version': taxcalc_vers_disp,
        'webapp_version': webapp_vers_disp
    }
    if model.tax_result:
        context = get_result_context(model, request, url)
        context.update(context_vers_disp)
        context[
            "raw_reform_text"] = model.json_text.raw_reform_text if model.json_text else ""
        context[
            "raw_assumption_text"] = model.json_text.raw_assumption_text if model.json_text else ""
        return render(request, 'taxbrain/results.html', context)
    elif model.error_text:
        return render(request, 'taxbrain/failed.html',
                      {"error_msg": model.error_text.text})
    else:

        job_ids = model.job_ids
        jobs_to_check = model.jobs_not_ready
        if not jobs_to_check:
            jobs_to_check = normalize(job_ids)
        else:
            jobs_to_check = normalize(jobs_to_check)

        try:
            jobs_ready = dropq_compute.dropq_results_ready(jobs_to_check)
        except JobFailError as jfe:
            print(jfe)
            return render_to_response('taxbrain/failed.html')

        if any([j == 'FAIL' for j in jobs_ready]):
            failed_jobs = [
                sub_id
                for (sub_id, job_ready) in zip(jobs_to_check, jobs_ready)
                if job_ready == 'FAIL'
            ]

            #Just need the error message from one failed job
            error_msgs = dropq_compute.dropq_get_results([failed_jobs[0]],
                                                         job_failure=True)
            error_msg = error_msgs[0]
            val_err_idx = error_msg.rfind("Error")
            error = ErrorMessageTaxCalculator()
            error_contents = error_msg[val_err_idx:].replace(" ", "&nbsp;")
            error.text = error_contents
            error.save()
            model.error_text = error
            model.save()
            return render(request, 'taxbrain/failed.html',
                          {"error_msg": error_contents})

        if all([j == 'YES' for j in jobs_ready]):
            results = dropq_compute.dropq_get_results(normalize(job_ids))
            model.tax_result = results
            model.creation_date = datetime.datetime.now()
            model.save()
            context = get_result_context(model, request, url)
            context.update(context_vers_disp)
            return render(request, 'taxbrain/results.html', context)

        else:
            jobs_not_ready = [
                sub_id
                for (sub_id, job_ready) in zip(jobs_to_check, jobs_ready)
                if job_ready == 'NO'
            ]
            jobs_not_ready = denormalize(jobs_not_ready)
            model.jobs_not_ready = jobs_not_ready
            model.save()
            if request.method == 'POST':
                # if not ready yet, insert number of minutes remaining
                exp_comp_dt = url.exp_comp_datetime
                utc_now = datetime.datetime.utcnow()
                utc_now = utc_now.replace(tzinfo=pytz.utc)
                dt = exp_comp_dt - utc_now
                exp_num_minutes = dt.total_seconds() / 60.
                exp_num_minutes = round(exp_num_minutes, 2)
                exp_num_minutes = exp_num_minutes if exp_num_minutes > 0 else 0
                if exp_num_minutes > 0:
                    return JsonResponse({'eta': exp_num_minutes}, status=202)
                else:
                    return JsonResponse({'eta': exp_num_minutes}, status=200)

            else:
                context = {'eta': '100'}
                context.update(context_vers_disp)
                return render_to_response(
                    'taxbrain/not_ready.html',
                    context,
                    context_instance=RequestContext(request))
Esempio n. 37
0
def about(request):
    return render_to_response(
        'about/about.html', {
            'breadcrumb': (('About', None), ),
            'staff_members': StaffMember.objects.all().order_by('last_name'),
        }, RequestContext(request))
Esempio n. 38
0
def profile_search(request):
	errors = []
	profile = ""
	if 'q' in request.GET:
	    q=request.GET['q']
	    if q is None:
	    	errors.append('Enter a search term!')
	    else:
			try: 
				pro = User.objects.get(username__exact=q)
				return HttpResponseRedirect("/accounts/profile/%s" % q)
			except ObjectDoesNotExist:
				errors.append('The user you searched for does not exist, please enter a valid username')
	return render_to_response("profile_search.html" , {'errors':errors, 'profile':profile}, context_instance=RequestContext(request))
Esempio n. 39
0
def email_change(request):
	errors = []
	form = Email_Change_Form()
	if request.method=='POST':
		form = Email_Change_Form(request.POST)
		if form.is_valid():
				if form.cleaned_data['email1']  == form.cleaned_data['email2']:
					u = User.objects.get(username=request.user)
					# get the proper user
					u.email = form.cleaned_data['email1'] 
					#^this is where the error is thrown
					u.save()
					return HttpResponseRedirect("/accounts/profile/")
				else:
					errors.append('Please enter two identical addresses!')
	return render_to_response("email_change.html", {'form':form , 'errors' : errors}, context_instance=RequestContext(request))
Esempio n. 40
0
 def preview_get(self, request):
     "Displays the form"
     f = self.form(auto_id=AUTO_ID)
     return render_to_response(self.form_template,
         {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
         context_instance=RequestContext(request))
Esempio n. 41
0
def home(request):
    """Docstring"""
    return render_to_response('signup_confirmar.html',
                              {'user': request.user}, context_instance=RequestContext(request))
Esempio n. 42
0
def add(request, activity):
    """Creates a request for points for an activity."""

    user = request.user

    if request.method == "POST":
        form = _get_form(request, activity)

        if form.is_valid():
            try:
                action_member = ActionMember.objects.get(user=user,
                                                         action=activity)
            except ObjectDoesNotExist:
                action_member = ActionMember(
                    user=user,
                    action=activity,
                    submission_date=datetime.datetime.today())

            # Attach image if it is an image form.
            if "image_response" in form.cleaned_data:
                if activity.confirm_type == "free_image":
                    action_member.response = form.cleaned_data["response"]

                path = activity_image_file_path(
                    user=user, filename=request.FILES['image_response'].name)
                action_member.image = path

                action_member.image.storage.save(
                    path, request.FILES["image_response"])

                action_member.approval_status = "pending"
            # Attach text prompt question if one is provided
            elif "question" in form.cleaned_data:
                action_member.question = TextPromptQuestion.objects.get(
                    pk=form.cleaned_data["question"])
                action_member.response = form.cleaned_data["response"]
                action_member.approval_status = "pending"

            elif activity.confirm_type == "free":
                action_member.response = form.cleaned_data["response"]
                action_member.approval_status = "pending"

            action_member.social_email = form.cleaned_data[
                "social_email"].lower()
            try:
                action_member.save()
            except IntegrityError:
                messages.error = 'Sorry, but it appears that you have already added this activity.'
                return HttpResponseRedirect(
                    reverse("activity_task",
                            args=(
                                activity.type,
                                activity.slug,
                            )))

            response = HttpResponseRedirect(
                reverse("activity_task", args=(
                    activity.type,
                    activity.slug,
                )))

            return response

        # invalid form
        # rebuild the form
        form.form_title = "Get your points"
        if activity.confirm_type == "text":
            qid = form.data["question"]
            question = TextPromptQuestion.objects.get(pk=qid)
            form.action_question = question
        return render_to_response("task.html", {
            "action": activity,
            "form": form,
            "completed_count": 0,
            "team_members": None,
            "display_form": True,
            "reminders": None,
        },
                                  context_instance=RequestContext(request))

    return HttpResponseRedirect(
        reverse("activity_task", args=(
            activity.type,
            activity.slug,
        )))
def register(request):
    """
    A very simplistic register view
    """
    
    """ ORIGINAL CODE
    backend = get_registration_backend()
    form_class = backend.get_form_class(request)
    template_name = backend.get_registration_template()

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            response = backend.post_registration_redirect(request, new_user)
            #keep the post behaviour exactly the same as django facebook
            
            return response
    else:
        form = form_class()
    
    context = RequestContext(request)
    context['form'] = form
    response = render_to_response(template_name, context_instance=context)
    
    return response"""

    data = {}
    if request.method == 'POST':
        email = request.POST['email']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        #gender = request.POST['gender']
        password = request.POST['password']
        try:
            # user = authenticate(username=email,password=password) # This code doesn't work as intended use
            user = User.objects.get(username=email)
            if user.is_active == False: #if user has not yet activated, resend data
                try:
                    user.get_profile().delete()
                except:
                    pass
                user.delete()
                raise User.DoesNotExist
            data['title'] = "Registration Error"
            data['message'] = "That email exists already."
            form = FacebookProfileForm(request.POST)
            data['form'] = form
            return render_to_response('registration/registration_form.html',data,context_instance = RequestContext(request))
        except: #errors if email doesn't exist which is good
            pass

        new_user = User()
        new_user.username = email
        new_user.first_name = first_name
        new_user.last_name = last_name
        new_user.email = email
        new_user.set_password(password)
        new_user.is_active = False
        new_user.save()
        
        #new_user = authenticate( username= email, password=password)
        #login(request,new_user)
        
        auth_key = ""
        # create a 20 length random key
        for i in range(0,20):
            auth_key += random.choice(RANDOM_CHARS)
        
        verif = VerificationEmailID(user=new_user,auth_key=auth_key)
        verif.save()

        full_name = new_user.get_full_name()
        send_templated_mail(
            template_name='register',
            from_email='Buy Near Me <*****@*****.**>',
            recipient_list=[add_name_to_email(full_name, email)],
            context={
                'auth_key':auth_key,
                'first_name':new_user.first_name,
                'full_name':full_name,
                },
        )
        
        data['title'] = "Sign Up Verification"
        data['message'] = """Verification email has been sent.<br>Follow the instructions on the email to activate your account."""
        
        return render_to_response('message.html',data,context_instance=RequestContext(request))
        
        #return render_to_response('index.html',context_instance=RequestContext(request) )
    else:
        form = FacebookProfileForm()
    
    context = RequestContext(request)
    context['form'] = form
    response = render_to_response('registration/registration_form.html', context_instance=context)
    
    return response
Esempio n. 44
0
def category_view(request, id):
    return render_to_response(
        'sampleapp/category_view.html',
        RequestContext(request, {'category': Category.objects.get(pk=id)}))
Esempio n. 45
0
def cambiarPass(request):
    return render_to_response('principal.html',
                              context_instance=RequestContext(request, {}))
Esempio n. 46
0
def sign_up(request):
	return render_to_response("signup.html", context_instance=RequestContext(request))
Esempio n. 47
0
def policy(request):
    return render_to_response('about/policy.html', {
        'breadcrumb': (('Policy', None), ),
    }, RequestContext(request))
Esempio n. 48
0
def contato(request, cidade_slug):
    cidade = get_object_or_404(Cidade, slug=cidade_slug)
    cidades_disponiveis = Cidade.objects.all()
    #Mapa
    gmap = maps.Map(
        opts={
            'center': maps.LatLng('-34', '20'),
            'mapTypeId': maps.MapTypeId.ROADMAP,
            'zoom': 15,
            'mapTypeControlOptions': {
                'style': maps.MapTypeControlStyle.DROPDOWN_MENU
            },
        })
    marker = maps.Marker(opts={
        'map': gmap,
        'position': maps.LatLng('-34', '20'),
    })
    maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')
    maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')
    info = maps.InfoWindow({
        'content':
        '<h3>' + 'Clipper Magazine' + '</h3>' + '<p>Rua: ' + 'etc etc' +
        '</p>' + '<p>Telefone: ' + '62 888992212' + '</p>',
        'disableAutoPan':
        False
    })
    info.open(gmap, marker)

    #formulario de contato
    if request.POST:
        postdata = request.POST.copy()
        form_contato = Contato_Form(postdata)
        if form_contato.is_valid():
            cad_contato = Contato()
            cad_contato.nome = form_contato.cleaned_data['nome']
            cad_contato.empresa = form_contato.cleaned_data['empresa']
            cad_contato.email = form_contato.cleaned_data['email']
            cad_contato.telefone = cad_contato.cleaned_data['telefone']
            cad_contato.mensagem = form_contato.cleaned_data['mensagem']
            cad_contato.save()

            mensagem_site = form_contato.cleaned_data['mensagem']
            mensagem = "Ola\nO %s Mandou a seguinte mensagem:\n%s" % (
                cad_contato.nome, mensagem_site)
            email = EmailMessage(cad_contato.mensagem,
                                 mensagem,
                                 to=['*****@*****.**'])
            email.send()

            if request.is_ajax():
                return render_to_response('contato/sucesso.html')
            else:
                return redirect('contato_sucesso')
    else:
        form_contato = Contato_Form()

    if request.session.get('email_cadastrado', False):
        email_cadastrado = True
        email_form = None
    else:
        email_cadastrado = False
        email_form = EmailForm()
        email_duplicado = False

    if request.POST:
        postdata = request.POST.copy()
        email_form = EmailForm(postdata)
        if email_form.is_valid():
            cad_email = EmailInscricao()
            cad_email.email = email_form.cleaned_data['email']
            cad_email.cidade = email_form.cleaned_data['cidade']
            cad_email.save()
            email_cadastrado = True

    context = {
        'form_mapa': MapForm(initial={'map': gmap}),
        'email_form': email_form,
        'email_cadastrado': email_cadastrado,
        'form_contato': form_contato,
        'cidades_disponiveis': cidades_disponiveis,
        'cidade': cidade,
    }
    return render_to_response('contato/contato.html',
                              context,
                              context_instance=RequestContext(request))
Esempio n. 49
0
                    # Fall through. It will be reported inline and in the log.
                    logging.error('Uploading SSH key failed: %s' % e)
    else:
        form = SSHSettingsForm()

    if key:
        fingerprint = humanize_key(key)
    else:
        fingerprint = None

    return render_to_response(
        template_name,
        RequestContext(
            request, {
                'key': key,
                'fingerprint': fingerprint,
                'public_key': client.get_public_key(key),
                'form': form,
            }))


def manual_updates_required(request,
                            updates,
                            template_name="admin/manual_updates_required.html"
                            ):
    """
    Checks for required manual updates and displays informational pages on
    performing the necessary updates.
    """
    return render_to_response(
        template_name,
Esempio n. 50
0
def user_login(request):
    username = ''
    password = ''
    state = 'Please Log In'
    status_code = 0
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request,user)
                status_code = 1
                state = 'You have successfully Logged In'
            else:
                state = 'Your account has been deactivated'
        else:
            state = 'Invalid Login Details'
      
    return render_to_response('login.html',{'state':state,'status_code':status_code,'username':username},context_instance=RequestContext(request))    
Esempio n. 51
0
def faq(request, slug):
    page = get_object_or_404(models.Faq, slug=slug)
    current_item = page.title
    return render_to_response('pages/faq.html', {},
                              context_instance=RequestContext(
                                  request, locals()))
Esempio n. 52
0
def http404(request):
    return render_to_response("errors/404.html", {
        'site_location': 'Error 404',
    },
                              context_instance=RequestContext(request))
Esempio n. 53
0
def occurrence_confirmation_form(
    request,
    pk,
    template='schedule/schedule_occurrence_confirmation_form.html',
    form_class=OccurrenceConfirmationForm,
    client_id=None,
    redirect_to=None,
):

    occurrence = get_object_or_404(
        ScheduleOccurrence,
        pk=pk,
        event__referral__service__organization=request.user.get_profile(
        ).org_active)

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [
            device.pk
            for device in (occurrence.occurrenceconfirmation.device.all())
        ]

    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(
            pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None

    object = get_object_or_None(
        Client,
        pk=client_id,
        person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == 'POST':
        if denied_to_write:
            return render_to_response('403.html', {
                'object':
                _("Oops! You don't have access for this service!"),
            },
                                      context_instance=RequestContext(request))
        form = form_class(request.POST,
                          instance=occurrence_confirmation,
                          initial={
                              'device': initial_device,
                          })
        if form.is_valid():
            data = form.save(commit=False)
            data.occurrence = occurrence
            # client not arrive, dont save datetime field
            if int(data.presence) not in (1, 2, 6, 7):
                data.date_started = None
                data.date_finished = None
            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()
            messages.success(request,
                             _('Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)
        else:
            form.fields['device'].widget.choices = [(
                i.id, i
            ) for i in DeviceDetails.objects.active(request.user.get_profile(
            ).org_active).filter(
                Q(room=occurrence.room) | Q(mobility=2, lendable=True)
                | Q(place=occurrence.room.place, mobility=2, lendable=False))]
            return render_to_response(template,
                                      dict(occurrence=occurrence,
                                           form=form,
                                           object=object,
                                           referral=occurrence.event.referral),
                                      context_instance=RequestContext(request))
    else:
        # load initial data if client dont arrive
        if hasattr(occurrence_confirmation, 'presence') and int(
                occurrence_confirmation.presence) not in (1, 2, 6, 7):
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation,
                          initial={
                              'occurrence': occurrence,
                              'start_time': occurrence.start_time,
                              'end_time': occurrence.end_time,
                              'device': initial_device,
                          })

        form.fields['device'].widget.choices = [
            (i.id, i)
            for i in DeviceDetails.objects.active(request.user.get_profile(
            ).org_active).filter(
                Q(room=occurrence.room) | Q(mobility="2", lendable=True)
                | Q(place=occurrence.room.place, mobility="2", lendable=False))
        ]

        #Validating the events to be dated with input and output
        if (((occurrence_confirmation
              and int(occurrence_confirmation.presence)) > 2) and
            ((occurrence_confirmation
              and int(occurrence_confirmation.presence)) < 6)
                or ((occurrence_confirmation
                     and int(occurrence_confirmation.presence)) > 7)):
            occurrences_that_require_dates = True
        else:
            occurrences_that_require_dates = None

        #Creating dictionaries to return instance to template
        events_for_return = dict(
            occurrence=occurrence,
            form=form,
            object=object,
            referral=occurrence.event.referral,
            occurrence_confirmation=occurrence_confirmation,
            hide_date_field=occurrences_that_require_dates,
            #True if occurrence_confirmation and int(occurrence_confirmation.presence) > 7 else None,
            denied_to_write=denied_to_write)

    return render_to_response(template,
                              events_for_return,
                              context_instance=RequestContext(request))
Esempio n. 54
0
def http500(request):
    return render_to_response("errors/500.html", {
        'site_location': 'Error 500',
    },
                              context_instance=RequestContext(request))
Esempio n. 55
0
def home(request):
    organizaciones = Organizacion.objects.all()
    return render_to_response('index.html', RequestContext(request, locals()))
Esempio n. 56
0
def login(request,
          custom_message=None,
          force_form=False,
          initial_email=None,
          override_target=None):
    """
    View for logging in.
    custom_message is a string to display at the top of the login form.
    force_form is used when you want to force display of the original
    form (regardless of whether it's a POST request).
    override_target can be used to set the form's target URL;
    otherwise it's self-POSTing.
    """
    if not request.user.is_anonymous():
        # If the user is already logged in, redirect to the dashboard.
        next_url = reverse(dashboard)
        return http.HttpResponseRedirect(next_url)
    if request.method == 'POST' and not force_form:

        next_url = (request.session.pop(REDIRECT_FIELD_NAME, None)
                    or request.POST.get(REDIRECT_FIELD_NAME)
                    or reverse(dashboard))

        form = forms.LoginForm(request, request.POST)
        if form.is_valid():
            utils.login(request, form.user_cache)
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            # If the session contains a 'pending_login' variable, it will be a
            # tuple of (callback_name, data), where data is an unserialized
            # Python object and callback_name corresponds to a callback in
            # ebpub/accounts/callbacks.py.
            if 'pending_login' in request.session:
                try:
                    callback, data = request.session['pending_login']
                    message = callbacks.do_callback(callback, form.user_cache,
                                                    data)
                except (TypeError, ValueError):
                    message = None

                # We're done with the callbacks and don't want to risk them
                # happening again, so we delete the session value.
                del request.session['pending_login']

                # Save the login message in the session so we can display it
                # for the user.
                if message:
                    request.session['login_message'] = message

            return http.HttpResponseRedirect(next_url)
    else:
        form = forms.LoginForm(request, initial={'email': initial_email})

    # Rendering the form.
    request.session.set_test_cookie()
    if request.REQUEST.get(REDIRECT_FIELD_NAME):
        request.session[REDIRECT_FIELD_NAME] = request.REQUEST[
            REDIRECT_FIELD_NAME]
    custom_message = request.session.pop('login_message', custom_message)
    context = RequestContext(
        request, {
            'form': form,
            'custom_message': custom_message,
            'target': override_target or reverse(login),
        })
    return eb_render(request, 'accounts/login_form.html', context)
Esempio n. 57
0
def group_message_wall(request, group_id,link,**kwargs):
    nm=NotificationManager()
    nm.set_sender(request.user.username, 'smtp.gmail.com', 465, '*****@*****.**', '13936344120lsqshr')
    #get the group
    group_id = long(group_id)
    group = None
    try:
        group = JoinInGroup.objects.get(id=group_id)
    except:
        raise Exception("Sorry, this group does not exist..." )
    #see if this user has permission to view the group content
    try:
        group.users.get(user__username=request.user.username)
    except JoinInUser.DoesNotExist:
        return HttpResponse("sorry, you do not have the permission to view this group. Group Name:"\
                            +str(group.name)+"Your user id:"+str(request.user.id))
    if link == 'view':#deal with when the url is like /group_id/view/
        #
        #get all the messages to render
        messages=group.messages.all()
        #get all the members
        users=group.users.all()
        msgw=MessageWall(user=request.user.joinin_user,group=group)
        #TODO: get all the files
        ####################deal with form#########################################
        if request.method == "POST":
            if "post_msg" in request.POST:
                    form = SendMessageForm(request.user,group, request.POST)
                    if form.is_valid():
                        cd = form.cleaned_data
                        if cd.has_key('web_url'):
                            web_url = cd['web_url']
                        priority = cd['priority']
                        if cd.has_key('send_to'):
                            send_to = cd['send_to']
                            if send_to is u'':
                                send_to = None
                        else:
                            send_to = None
                        belongs_to = cd['belongs_to_group']
                        content = cd['content']
                        #get all the entities
                        try:
                            if send_to:
                                send_to = JoinInUser.objects.get(user__username=send_to)
                        except JoinInUser.DoesNotExist:#TODO:
                            raise Exception("Fail to find the user to send the message. User with email:" + send_to + " does not exist.") 
                        try:
                            belongs_to = JoinInGroup.objects.get(id=belongs_to)
                        except JoinInGroup.DoesNotExist:
                            raise Exception("Fail to find the group to send the message. Group with name " + belongs_to + " does not exist.")
                        #send this message
                        msgw.send_message(web_url=web_url, send_datetime=datetime.datetime.now(),\
                                           send_to=send_to, belongs_to_group=belongs_to,\
                                            written_by=request.user.joinin_user, content=content,priority=priority)#did not include priority
                        #send notification to all of the members in that group
                        nm.send_notification(to_user=None, to_group=belongs_to, text=request.user.username+\
                                             " has posted a message in group "+belongs_to.name+".\n\n"\
                                             +str(datetime.datetime.now())+content, \
                                             url="/message_wall/view/", sys=False, email=True)
            elif "invite" in request.POST:#deal with the 
                form=InviteForm(request.POST)
                if form.is_valid():
                    cd=form.cleaned_data
                    username=cd['username']
                    #get the user
                    errors=[]
                    try:
                        user=JoinInUser.objects.get(user__username=username)
                    except JoinInUser.DoesNotExist:
                        #show the form again.
                        errors.append("Sorry! The user does not exist.")
                    #see if the user is in the group now    
                    try:
                        group.users.get(user__username=username)
                        errors.append("Sorry! The user has already been added to this group!")
                    except JoinInUser.DoesNotExist:
                        pass
                    if errors:
                        NotificationManager().send_notification(request.user.joinin_user, None, ';'.join(errors), None, True,False)
                        return HttpResponseRedirect('/message_wall/group/'+str(group.id)+'/view/')
                    #create new invitation to the user.
                    else:
                        group.invitations.add(user)
                        return HttpResponseRedirect('/message_wall/group/'+str(group.id)+'/view/')
            elif 'reply' in request.POST:#write reply
                content=request.POST['content']
                message_id=long(request.POST['message_id'])
                group_id=request.POST['group_id']
                #get message to reply to
                try:
                    message=Message.objects.get(id=message_id)
                except Message.DoesNotExist:
                    raise Exception("message not found") 
                try:
                    group=JoinInGroup.objects.get(id=group_id)
                except JoinInGroup.DoesNotExist:
                    raise Exception("group not found")
                Message.objects.create(reply_to=message,priority=1,\
                                       send_datetime=datetime.datetime.now(), \
                                       update_datetime=datetime.datetime.now(),\
                                       belongs_to_group=group,\
                                       written_by=request.user.joinin_user,content=content)
                #change the parent message's update_datetime for sorting
                message.update_datetime=datetime.datetime.now() 
                message.save()
                return HttpResponseRedirect('/message_wall/group/'+str(group.id)+'/view/')
            elif 'apply' in request.POST:
                #deal with the form
                if request.method == 'POST':
                    form=ApplyGroupForm(request.POST)
                    errors=[]
                    if form.is_valid():
                        cd=form.cleaned_data
                        group_name=cd['group_name']
                        #find the group
                        group_to_apply=None
                        try:
                            group_to_apply=JoinInGroup.objects.get(name=group_name)
                        except JoinInGroup.DoesNotExist:
                            errors.append("Sorry, group with name<b>"+group_name+"</b> does not exist, please check the name.")
                        #add the user to the appliers of that group
                        if request.user.joinin_user not in group_to_apply.appliers.all() or \
                                request.user.joinin_user not in group_to_apply.users.all():
                            group_to_apply.appliers.add(request.user.joinin_user)
                        else:#TODO:
                            raise "You have applied for this group or you have been a member of this group. Please be patient for the acceptance."
                        #send notification
                        nm.send_notification(request.user.joinin_user, None, 'You have applied to join group '+group_to_apply.name\
                                             +'.Please wait for permission. Any of the members in this group are able to allow you to join in.', None) 
                        #redirect to the private message wall
                        return HttpResponseRedirect("/message_wall/view/")
                    else:#group name is not in the right format
                        errors.append("OOps!The group name is too long...")
                    if errors:    
                        return render_to_response("accounts_modules/apply_dialog.html",{'form':form,'errors':errors},\
                                          context_instance=RequestContext(request, {}))       
                    else:
                        form=ApplyGroupForm()
                    #show the apply group dialog
                    return render_to_response("accounts_modules/apply_dialog.html",{'form':form},\
                                              context_instance=RequestContext(request, {}))
        else:
            pass
        #get all the private messages to this user
        p_msgs = msgw.retrieve_list()
        #refresh the form to render
        form = SendMessageForm(user=request.user,initial_group=group)
        #get applisers to this group
        appliers=group.appliers.all()
        return render_to_response('group_message_wall.html', \
                                  {'form':form, 'page_name':'Group '+group.name+' Message Wall',\
                                    'page_tag':'public',\
                                    'private_messages':p_msgs, "groups":request.user.joinin_user.groups.all(),\
                                    'users':users,'group':group,'appliers':appliers},\
                                   context_instance=RequestContext(request, {}))
    elif link == 'invite':
        if request.method=="POST"and "invite" in request.POST:
                form=InviteForm(request.POST)
                if form.is_valid():
                    cd=form.cleaned_data
                    username=cd['username']
                    #get the user
                    errors=[]
                    try:
                        user=JoinInUser.objects.get(user__username=username)
                    except JoinInUser.DoesNotExist:
                        #show the form again.
                        errors.append("Sorry! The user does not exist.")
                    #see if the user is in the group now    
                    try:
                        group.users.get(user__username=username)
                        errors.append("Sorry! The user has already been added to this group!")
                    except JoinInUser.DoesNotExist:
                        pass
                    if errors:
                        return render_to_response("accounts_modules/invite_dialog.html",\
                                                  {'errors':errors,'form':form,'group':group},\
                                                   context_instance=RequestContext(request, {}))
                    #create new invitation to the user.
                    else:
                        group.invitations.add(user)
                        #TODO:should send user a notification to notify success of inviting the user.
                        return HttpResponseRedirect('/message_wall/group/'+str(group.id)+'/view/')
        else:#no submit form
            form=InviteForm() 
            return render_to_response("accounts_modules/invite_dialog.html",\
                                      {'group':group,'form':form},\
                                       context_instance=RequestContext(request, {}))
    elif link == 'leave':
        #delete the current user from this group
        group.users.remove(request.user.joinin_user)
        #TODO:send notification to notify user that the user has left the group
        #redirect to the private message wall
        #if the group has no more user, this group should be deleted
        if len(group.users.all()) is 0:
            group.delete()
        return HttpResponseRedirect("/message_wall/view/")
    elif link == 'accept':
        #get user
        try:
            user_to_add= JoinInUser.objects.get(user__username=kwargs['username'])
        except JoinInUser.DoesNotExist:
            raise "User Does not exist!"#TODO:
        #see if this user is in the group, not? add!
        if user_to_add not in group.users.all()\
                and len(group.users.all())<=12:
            group.users.add(user_to_add) 
        else:
            NotificationManager().send_notification(request.user.joinin_user, None, 'User '+user_to_add.user.username+\
                                                    ' has already been in the group. Or there are already 12 members in this group, which reached the top limit.',\
                                                     None,True,False)
        #delete this user from appliers
        group.appliers.remove(user_to_add)
        #delete the user from the invitations, if there are invitation was sent to this user
        if user_to_add in group.invitations.all():
            group.invitations.remove(user_to_add)
        #send all the messages in that group as private messages to the user,
        #since the new user should see the historical messages
        for msg in group.messages.all():
            PrivateMessage.objects.create(message=msg, belongs_to=user_to_add, read=False, priority=msg.priority, trashed=False)
        
        #redirect
        return HttpResponseRedirect('/message_wall/group/'+str(group.id)+'/view/')
    elif link== 'deny':
        #get user 
        #get user
        try:
            user_to_add= JoinInUser.objects.get(user__username=kwargs['username'])
        except JoinInUser.DoesNotExist:
            raise "User Does not exist!"#TODO:
        #simply remove this joinin user from the appliers
        group.appliers.remove(user_to_add)
        return HttpResponseRedirect('/message_wall/group/'+str(group.id)+'/view/')
    else: 
        return HttpResponse("not working"+link)
Esempio n. 58
0
def graph_queryset(modeladmin, request, queryset):  # noqa
    opts = modeladmin.model._meta
    perm = "{0}.{1}".format(
        opts.app_label.lower(),
        get_permission_codename('adminactions_chart', opts))
    if not request.user.has_perm(perm):
        messages.error(
            request, _('Sorry you do not have rights to execute this action'))
        return

    MForm = graph_form_factory(modeladmin.model)

    graph_type = table = None
    extra = '{}'
    try:
        adminaction_requested.send(sender=modeladmin.model,
                                   action='graph_queryset',
                                   request=request,
                                   queryset=queryset,
                                   modeladmin=modeladmin)
    except ActionInterrupted as e:
        messages.error(request, str(e))
        return

    if 'apply' in request.POST:
        form = MForm(request.POST)
        if form.is_valid():
            try:
                adminaction_start.send(sender=modeladmin.model,
                                       action='graph_queryset',
                                       request=request,
                                       queryset=queryset,
                                       modeladmin=modeladmin,
                                       form=form)
            except ActionInterrupted as e:
                messages.error(request, str(e))
                return
            try:
                x = form.cleaned_data['axes_x']
                # y = form.cleaned_data['axes_y']
                graph_type = form.cleaned_data['graph_type']

                field, model, direct, m2m = get_field_by_name(
                    modeladmin.model, x)
                cc = queryset.values_list(x).annotate(Count(x)).order_by()
                if isinstance(field, ForeignKey):
                    data_labels = []
                    for value, cnt in cc:
                        data_labels.append(
                            str(field.rel.to.objects.get(pk=value)))
                elif isinstance(field, BooleanField):
                    data_labels = [str(l) for l, v in cc]
                elif hasattr(modeladmin.model, 'get_%s_display' % field.name):
                    data_labels = []
                    for value, cnt in cc:
                        data_labels.append(
                            smart_text(dict(field.flatchoices).get(
                                value, value),
                                       strings_only=True))
                else:
                    data_labels = [str(l) for l, v in cc]
                data = [v for l, v in cc]

                if graph_type == 'BarChart':
                    table = [data]
                    extra = """{seriesDefaults:{renderer:$.jqplot.BarRenderer,
                                                rendererOptions: {fillToZero: true,
                                                                  barDirection: 'horizontal'},
                                                shadowAngle: -135,
                                               },
                                series:[%s],
                                axes: {yaxis: {renderer: $.jqplot.CategoryAxisRenderer,
                                                ticks: %s},
                                       xaxis: {pad: 1.05,
                                               tickOptions: {formatString: '%%d'}}
                                      }
                                }""" % (json.dumps(data_labels),
                                        json.dumps(data_labels))
                elif graph_type == 'PieChart':
                    table = [list(zip(data_labels, data))]
                    extra = """{seriesDefaults: {renderer: jQuery.jqplot.PieRenderer,
                                                rendererOptions: {fill: true,
                                                                    showDataLabels: true,
                                                                    sliceMargin: 4,
                                                                    lineWidth: 5}},
                             legend: {show: true, location: 'e'}}"""

            except Exception as e:
                messages.error(request,
                               'Unable to produce valid data: %s' % str(e))
            else:
                adminaction_end.send(sender=modeladmin.model,
                                     action='graph_queryset',
                                     request=request,
                                     queryset=queryset,
                                     modeladmin=modeladmin,
                                     form=form)
    elif request.method == 'POST':
        # total = queryset.all().count()
        initial = {
            helpers.ACTION_CHECKBOX_NAME:
            request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
            'select_across':
            request.POST.get('select_across', 0)
        }
        form = MForm(initial=initial)
    else:
        initial = {
            helpers.ACTION_CHECKBOX_NAME:
            request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
            'select_across':
            request.POST.get('select_across', 0)
        }
        form = MForm(initial=initial)

    adminForm = helpers.AdminForm(form,
                                  modeladmin.get_fieldsets(request), {}, [],
                                  model_admin=modeladmin)
    media = modeladmin.media + adminForm.media

    ctx = {
        'adminform':
        adminForm,
        'action':
        'graph_queryset',
        'opts':
        modeladmin.model._meta,
        'action_short_description':
        graph_queryset.short_description,
        'title':
        u"%s (%s)" % (
            graph_queryset.short_description.capitalize(),
            smart_text(modeladmin.opts.verbose_name_plural),
        ),
        'app_label':
        queryset.model._meta.app_label,
        'media':
        media,
        'extra':
        extra,
        'as_json':
        json.dumps(table),
        'graph_type':
        graph_type
    }
    if django.VERSION[:2] > (1, 7):
        ctx.update(modeladmin.admin_site.each_context(request))
    else:
        ctx.update(modeladmin.admin_site.each_context())
    return render_to_response('adminactions/charts.html',
                              RequestContext(request, ctx))
Esempio n. 59
0
def sample_view(request, **kw):
    context = RequestContext(request, kw)
    return render_to_response("sampleapp/home.html", context)
Esempio n. 60
0
def mass_update(modeladmin, request, queryset):  # noqa
    """
        mass update queryset
    """
    def not_required(field, **kwargs):
        """ force all fields as not required"""
        kwargs['required'] = False
        return field.formfield(**kwargs)

    def _doit():
        errors = {}
        updated = 0
        for record in queryset:
            for field_name, value_or_func in list(form.cleaned_data.items()):
                if callable(value_or_func):
                    old_value = getattr(record, field_name)
                    setattr(record, field_name, value_or_func(old_value))
                else:
                    setattr(record, field_name, value_or_func)
            if clean:
                record.clean()
            record.save()
            updated += 1
        if updated:
            messages.info(request, _("Updated %s records") % updated)

        if len(errors):
            messages.error(request,
                           "%s records not updated due errors" % len(errors))
        adminaction_end.send(sender=modeladmin.model,
                             action='mass_update',
                             request=request,
                             queryset=queryset,
                             modeladmin=modeladmin,
                             form=form,
                             errors=errors,
                             updated=updated)

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

    try:
        adminaction_requested.send(sender=modeladmin.model,
                                   action='mass_update',
                                   request=request,
                                   queryset=queryset,
                                   modeladmin=modeladmin)
    except ActionInterrupted as e:
        messages.error(request, str(e))
        return

    # Allows to specified a custom mass update Form in the ModelAdmin
    mass_update_form = getattr(modeladmin, 'mass_update_form', MassUpdateForm)

    MForm = modelform_factory(modeladmin.model,
                              form=mass_update_form,
                              exclude=('pk', ),
                              formfield_callback=not_required)
    grouped = defaultdict(lambda: [])
    selected_fields = []
    initial = {
        '_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
        'select_across': request.POST.get('select_across') == '1',
        'action': 'mass_update'
    }

    if 'apply' in request.POST:
        form = MForm(request.POST)
        if form.is_valid():
            try:
                adminaction_start.send(sender=modeladmin.model,
                                       action='mass_update',
                                       request=request,
                                       queryset=queryset,
                                       modeladmin=modeladmin,
                                       form=form)
            except ActionInterrupted as e:
                messages.error(request, str(e))
                return HttpResponseRedirect(request.get_full_path())

            # need_transaction = form.cleaned_data.get('_unique_transaction', False)
            validate = form.cleaned_data.get('_validate', False)
            clean = form.cleaned_data.get('_clean', False)

            if validate:
                with compat.atomic():
                    _doit()

            else:
                values = {}
                for field_name, value in list(form.cleaned_data.items()):
                    if isinstance(form.fields[field_name],
                                  ModelMultipleChoiceField):
                        messages.error(
                            request,
                            "Unable no mass update ManyToManyField without 'validate'"
                        )
                        return HttpResponseRedirect(request.get_full_path())
                    elif callable(value):
                        messages.error(
                            request,
                            "Unable no mass update using operators without 'validate'"
                        )
                        return HttpResponseRedirect(request.get_full_path())
                    elif field_name not in [
                            '_selected_action', '_validate', 'select_across',
                            'action', '_unique_transaction', '_clean'
                    ]:
                        values[field_name] = value
                queryset.update(**values)

            return HttpResponseRedirect(request.get_full_path())
    else:
        initial.update({'action': 'mass_update', '_validate': 1})
        # form = MForm(initial=initial)
        prefill_with = request.POST.get('prefill-with', None)
        prefill_instance = None
        try:
            # Gets the instance directly from the queryset for data security
            prefill_instance = queryset.get(pk=prefill_with)
        except ObjectDoesNotExist:
            pass

        form = MForm(initial=initial, instance=prefill_instance)

    for el in queryset.all()[:10]:
        for f in modeladmin.model._meta.fields:
            if f.name not in form._no_sample_for:
                if hasattr(f, 'flatchoices') and f.flatchoices:
                    grouped[f.name] = list(
                        dict(getattr(f, 'flatchoices')).values())
                elif hasattr(f, 'choices') and f.choices:
                    grouped[f.name] = list(
                        dict(getattr(f, 'choices')).values())
                elif isinstance(f, df.BooleanField):
                    grouped[f.name] = [True, False]
                else:
                    value = getattr(el, f.name)
                    if value is not None and value not in grouped[f.name]:
                        grouped[f.name].append(value)
                    initial[f.name] = initial.get(f.name, value)

    adminForm = helpers.AdminForm(form,
                                  modeladmin.get_fieldsets(request), {}, [],
                                  model_admin=modeladmin)
    media = modeladmin.media + adminForm.media
    dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.date
                                                          ) else str(obj)
    tpl = 'adminactions/mass_update.html'
    ctx = {
        'adminform':
        adminForm,
        'form':
        form,
        'action_short_description':
        mass_update.short_description,
        'title':
        u"%s (%s)" % (
            mass_update.short_description.capitalize(),
            smart_text(modeladmin.opts.verbose_name_plural),
        ),
        'grouped':
        grouped,
        'fieldvalues':
        json.dumps(grouped, default=dthandler),
        'change':
        True,
        'selected_fields':
        selected_fields,
        'is_popup':
        False,
        'save_as':
        False,
        'has_delete_permission':
        False,
        'has_add_permission':
        False,
        'has_change_permission':
        True,
        'opts':
        modeladmin.model._meta,
        'app_label':
        modeladmin.model._meta.app_label,
        # 'action': 'mass_update',
        # 'select_across': request.POST.get('select_across')=='1',
        'media':
        mark_safe(media),
        'selection':
        queryset
    }
    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))