예제 #1
0
파일: views.py 프로젝트: jaredly/GameCC
def browse(request, category=None):
    if not category: category = 'latest'
    if category == 'latest':
        return list_detail.object_list(
                request,
                queryset=Project.objects.all().order_by('-modified'),
                template_name='gamecc/project_list.html',
            )
    elif category == 'popular':
        return list_detail.object_list(
                request,
                queryset=Project.objects.all().order_by('-modified'),
                template_name='gamecc/project_list.html',
            )
    elif category == 'categories':
        return list_detail.object_list(
                request,
                queryset=Category.objects.all(),
                template_name='gamecc/categories.html',
            )
    else:
        try:
            cat = Category.objects.get(slug__iexact=category)
            return list_detail.object_list(
                    request,
                    queryset=cat.project_set,
                    template_name='gamecc/category.html'
                )
        except Category.DoesNotExist:
            messages.set_level(request, messges.ERROR)
            messages.error(request, 'That category doesn\'t exist')
        return HttpResponseRedirect('/browse/categories/')
예제 #2
0
파일: views.py 프로젝트: pynchia/tdj
def list_entity(request, parid, parmodel, entmodel, tipoentev=False):
    parent = get_object_or_404(parmodel, pk=parid)
    entmodname = entmodel.__name__.lower()
    parmodname = parmodel.__name__.lower()
    try:
        curpage = int(request.GET.get('page', '1'))
    except ValueError:
        curpage = 1

    if tipoentev: # we are listing events
        return list_detail.object_list(
                                    request,
                                    queryset = entmodel.objects.filter(fkev=parid,
                                                                       tipoentev=tipoentev),
                                    template_name = 'listevento.html',
                                    template_object_name = entmodname,
                                    extra_context = {'parent': parent, 'parmodname': parmodname, 'tipoentev': tipoentev},
                                    page=curpage,
                                    paginate_by=tdj.PAGELEN
                                    )
    else: # we are listing any other entity belonging to parent
        return list_detail.object_list(
                                    request,
                                    queryset = entmodel.objects.filter(**{parmodname: parid}),
                                    template_name = 'list%s.html' % entmodname,
                                    template_object_name = entmodname,
                                    extra_context = {'parent': parent, 'parmodname': parmodname},
                                    page=curpage,
                                    paginate_by=tdj.PAGELEN
                                    )
예제 #3
0
def contact_us(request):
    from djangoproject.settings import ADMINS
    manipulator = ContactManipulator()
    email_to=ADMINS[0][1]
    if request.POST:
        new_data = request.POST.copy()
        errors = manipulator.get_validation_errors(new_data)
        if not errors:
            manipulator.do_html2python(new_data)

            # Send e-mail using new_data here...
            from django.core.mail import send_mail, BadHeaderError
            try:
                subject='djangoproject message from  %s' % new_data['name']
                from_email=new_data['your email']
                message=new_data['message']
                send_mail(subject, message, from_email,[email_to], fail_silently=False)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            nav=getnavigation()
            return list_detail.object_list(request, nav,template_name='contact_us_thanks.html')
    else:
        errors = new_data = {}
    nav=getnavigation()
    form = forms.FormWrapper(manipulator, new_data, errors)
    return list_detail.object_list(request, nav,template_name='contact_form.html',extra_context ={'form': form})
예제 #4
0
def query(request):
  #import pdb; pdb.set_trace()

  if 'new_query' in request.GET:
    form = forms.MainPopulationQueryForm(request.GET)

    if form.is_valid():
      query = models.MainDataEntry.objects.filter(active = True)

      locations = form.cleaned_data['location']
      
      if len(locations) != 0:
        location_ids = models.Location.get_location_ids_in(locations)
        query = query.filter(location__in = location_ids)

      if form.cleaned_data['begin_date']:
        query = query.filter(begin_date__gte=form.cleaned_data['begin_date'])

      if form.cleaned_data['end_date']:
        query = query.filter(end_date__lte=form.cleaned_data['end_date'])

      count_types = form.cleaned_data['count_type']

      if (len(count_types) > 1) or ((len(count_types) == 1) and count_types[0] != 'all'):
        if 'individ' in count_types:
          query = query.filter(individuals_population_value__isnull = False)

        if 'fam' in count_types:
          query = query.filter(families_population_value__isnull = False)

        if 'males' in count_types:
          query = query.filter(male_population_value__isnull = False)

        if 'females' in count_types:
          query = query.filter(female_population_value__isnull = False)

      request.session['query'] = query

      page = request.GET.get('page', '1')
     
      return list_detail.object_list(
          request,
          queryset = query,
          template_name = 'population/query_results.html',
          template_object_name = 'data_entry',
          paginate_by = 50,
          page = page)
  else:
    page = request.GET.get('page', '1')

    #TODO Allow multiple queries per session
    return list_detail.object_list(
        request,
        queryset = request.session['query'], 
        template_name = 'population/query_results.html',
        template_object_name = 'data_entry',
        paginate_by = 50,
        page = page)
예제 #5
0
def index(request):
    """
    Lists all projects where user is Member
    """

    if request.user.is_superuser:
        return object_list(request,queryset=Project.objects.all())

    return object_list(request,queryset=request.user.project_set.all())
예제 #6
0
파일: all.py 프로젝트: wrabbit/skibi
def pobierz_dane(request,dziecko=None,page=None):
        
        if request.GET.has_key('page'):
                return object_list(request,
                           queryset=Aktualnosci.objects.all().order_by('-news_date'),
                           paginate_by = 2,
                           page = page,
                           extra_context={'header':'Aktualności'},
                           template_name = 'base_tresc.html')
        if request.POST:
                
                username = request.POST['username']
                password = request.POST['passwd']
                user = authenticate(username=username, password=password)
                
        if user is not None and user.is_active:
                last_login = user.last_login
                login(request, user) # zapisuje ID uzytkownika w sesji(inaczej request.user=AnonymousUser)
                
                klasy_w = Klasy.objects.filter(wychowawca=request.user.id)
                klasy_n = Przedmioty.objects.filter(nauczyciel=request.user.id).values('klasa').distinct()
                przedmioty_n = Przedmioty.objects.filter(nauczyciel=request.user.id)
                if user.groups.count()==1 and user.groups.filter(name='Administrator'):
                        return HttpResponseRedirect('/admin')
                if klasy_w:klasa_id = klasy_w[0].id
                elif klasy_n: klasa_id = klasy_n[0]['klasa']
                
                else:
                        dziecko = Uczniowie_tmp.objects.get(uczenprofile__rodzic = request.user.id)
                        klasa_id = dziecko.klasa.id
                klasa = Klasy.objects.get(id = klasa_id)
                tmp = Przedmioty()
                news = Aktualnosci.objects.all()
                klasy_n = tmp.klasy_nauczycieli(klasy_n)
                request.session['last_login']=last_login
                request.session['klasa']=klasa
                request.session['klasa_id']=klasa_id
                request.session['klasy_w']=klasy_w
                request.session['klasy_n']=klasy_n
                request.session['przedmioty_n']=przedmioty_n
                request.session['dziecko'] = dziecko
                grupa = Group.objects.filter(user__id=request.user.id)
                grupa = [g.name for g in grupa]
                #return render_to_response('base_tresc.html',{'header':'Aktualnosci','news':news}
                #                                  ,context_instance=RequestContext(request))
   

                return object_list(request,
                           queryset=Aktualnosci.objects.all().order_by('-news_date'),
                           paginate_by = 2,
                           page = page,
                           extra_context={'header':'Aktualności','last_login':last_login},
                           template_name = 'base_tresc.html')
        else:
                return HttpResponseRedirect('/')
예제 #7
0
def topic_detail(request, topic_id, meta=False):
    """
    Displays a Topic's Posts.
    """
    filters = {'pk': topic_id}
    if not request.user.is_authenticated() or \
       not auth.is_moderator(request.user):
        filters['hidden'] = False
    topic = get_object_or_404(Topic.objects.with_display_details(), **filters)
    if app_settings.USE_REDIS:
        redis.increment_view_count(topic)
        if request.user.is_authenticated():
            redis.update_last_read_time(request.user, topic)
            redis.seen_user(request.user, 'Viewing Topic:', topic)

    if topic.forum.section.is_managed():
        if not topic.forum.section.is_corp_authed(request.user):
            raise Http404

    if 'eve_auth' in settings.INSTALLED_APPS:
        postqs = Post.objects.with_character_details().filter(topic=topic, meta=meta).order_by('posted_at', 'num_in_topic')

        return object_list(request,
                postqs,
                paginate_by=get_posts_per_page(request.user), allow_empty=True,
                template_name='forum/topic_detail.html',
                extra_context={
                    'topic': topic,
                    'title': topic.title,
                    'avatar_dimensions': get_avatar_dimensions(),
                    'meta': meta,
                    'url': TopicURLs(topic, meta),
                    'show_fast_reply': request.user.is_authenticated() and ForumProfile.objects.get_for_user(request.user).auto_fast_reply or False,
                            },
                template_object_name='post')
    else:
        return object_list(request,
            Post.objects.with_user_details().filter(topic=topic, meta=meta) \
                                             .order_by('posted_at', 'num_in_topic'),
            paginate_by=get_posts_per_page(request.user), allow_empty=True,
            template_name='forum/topic_detail.html',
            extra_context={
                'topic': topic,
                'title': topic.title,
                'avatar_dimensions': get_avatar_dimensions(),
                'meta': meta,
                'urls': TopicURLs(topic, meta),
                'show_fast_reply': request.user.is_authenticated() and \
                    ForumProfile.objects.get_for_user(request.user).auto_fast_reply \
                    or False,
            }, template_object_name='post')
예제 #8
0
def lista_objetos(request, parametros, model, template_name, template_object_name, consulta, universo=None, msg_universo=''):
    mensagem = ''
    nenhum_param_enviado = True
    if request.method == 'POST':
        raise Exception('Essa view não pode ser acessada via POST')
    for parametro in parametros:
        if parametro:  # Se qualquer parâmetro tiver sido usado:
            nenhum_param_enviado = False
            break
    if nenhum_param_enviado:
        if universo:
            queryset = model.objects.filter(universo);
        else:
            queryset = model.objects.all();
        if queryset:
            if msg_universo:
                mensagem = msg_universo
            else:
                mensagem = 'Exibindo todos os registros.'
        else:
            mensagem = 'Não há registros a serem exibidos.'
    else:
        if universo:
            queryset = model.objects.filter(consulta & universo);
        else:
            queryset = model.objects.filter(consulta);
        if queryset:
            if len(queryset) > 1:
                mensagem = 'Foram encontrados %d resultados' % len(queryset)
            else:
                mensagem = 'Foi encontrado %d resultado' % len(queryset)
        else:
            mensagem = 'Nenhum registrado foi encontrado.'
    return list_detail.object_list(request,
    queryset=queryset,
    template_name=template_name,
    template_object_name=template_object_name, extra_context={'mensagem': mensagem})



    if not queryset:
        mensagem = 'Não há registros a serem exibidos.'
    else:
        mensagem = 'Exibindo todos os registros.'
    if queryset:
        return list_detail.object_list(request,
            queryset=queryset,
            template_name=template_name,
            template_object_name=template_object_name, extra_context={'mensagem': mensagem})
    else:
        return render_to_response(template_name, {'mensagem': mensagem}, context_instance=RequestContext(request))
예제 #9
0
def listar(request, model,pag=settings.RESULTS_PER_PAGE):   
    model_object = get_model('main', model)   
    if model_object:
        model_list = model_object.objects.all().order_by('-id')
        if model == "services":
            serv = True
            pag = 6
            model_list = Services.objects.all().order_by('id')
            return object_list(request,extra_context={'serv':serv}, queryset = model_list, paginate_by = int(pag))
        else:
            port = True
            service = Services.objects.all()
            return object_list(request,extra_context={'port':port,'service':service}, queryset = model_list, paginate_by = int(pag))       
    else:
        raise Http404()
예제 #10
0
파일: views.py 프로젝트: s7fkcu/autodealer
def cabinet_messages(request):
	page = 1
	if 'page' in request.GET:
		try: page = int(request.GET.get('page'))
		except: raise Http404()
		
	try: ds = Dealer.objects.get(user=request.user, is_banned=False, is_active=True)
	except: raise Http404()
	else:
		dsmg = DealerMessage.objects.filter(Q(dealer=ds) | Q(fdealer=ds))
		dsm_ids = [d['dealer'] for d in dsmg.values('dealer')] + [d['fdealer'] for d in dsmg.values('fdealer')]
		dsm_ids = list(set(dsm_ids))
			
		dsm = Dealer.objects.filter(id__in=dsm_ids).exclude(user=request.user)

		return list_detail.object_list(
				request,
				queryset = dsm,
				paginate_by = conf.PAGINATE_BY,
				page = page,
				template_name = 'cabinet/messages.html',
				template_object_name = 'dsm',
				extra_context = {
					'a':3,
					'a1':9,
					'ds':ds,
				},
				context_processors = [cabinet_proc],
			)
예제 #11
0
파일: views.py 프로젝트: s7fkcu/autodealer
def search(request):
	page = 1
	if 'page' in request.GET:
		try: page = int(request.GET.get('page'))
		except: raise Http404()
	
	ds = Dealer.objects.filter(is_banned=False, is_active=True)
	
	sform = DealerSearchForm(request.GET)
	if sform.is_valid():
		cd = sform.cleaned_data
		if 'title' in cd and cd['title']: ds = ds.filter(title__icontains=cd['title'])
		if 'town' in cd and cd['town']: ds = ds.filter(town__id=cd['town'].id)
		if 'brand' in cd and cd['brand']: ds = ds.filter(brand__id=cd['brand'].id)
		
	ds = ds.order_by('title')
	
	return list_detail.object_list(
		request,
		queryset = ds,
		paginate_by = conf.PAGINATE_BY,
		page = page,
		template_name = 'dealers/search.html',
		template_object_name = 'dealsers',
		extra_context = {
			'a':1,
			'sform':sform,
			'dealer':ds,
		},
	)
예제 #12
0
def search(request):
    app = 'user-admin'
    template_name = 'user_admin/search.html'
    
    if 'scope' not in request.GET or 'query' not in request.GET:
        form = SearchForm()
        return render_to_response(template_name, locals())
    
    scope = request.GET.get('scope', 'N')
    query = request.GET.get('query', '')
    
    form = SearchForm(request.GET)
    
    p = request.GET.get('page', '1')
    if not p.isdigit():
        p = 1
    else:
        p = int(p)

    if not form.is_valid():
        return render_to_response(template_name, locals())

    user_list = util.get_users(scope, query)
    basic_info = { 'form': form, 'scope': scope, 'query': query, \
                    'show_result': True, 'app': app }
                    
    return list_detail.object_list(
        request,
        paginate_by = Per_Page,
        page = p,
        queryset = user_list,
        template_name = template_name,
        template_object_name = 'user',
        extra_context = basic_info,
    )
예제 #13
0
def user_list(request):
    check_permissions(request.user, [PERMISSION_USER_VIEW])

    return object_list(
        request,
        queryset=User.objects.exclude(is_superuser=True).exclude(is_staff=True).order_by('username'),
        template_name='generic_list.html',
        extra_context={
            'title': _(u'users'),
            'hide_link': True,
            'extra_columns': [
                {
                    'name': _(u'full name'),
                    'attribute': 'get_full_name'
                },
                {
                    'name': _(u'email'),
                    'attribute': 'email'
                },
                {
                    'name': _(u'active'),
                    'attribute': lambda x: two_state_template(x.is_active),
                }

            ],
            'multi_select_as_buttons': True,
        },
    )
예제 #14
0
def simple_archive_view(request,queryset,template_name,
                        extra_context={},paginate_by=15):
    return object_list(request,
                       queryset,
                       paginate_by=paginate_by,
                       template_name=template_name,
                       extra_context=extra_context)
예제 #15
0
파일: views.py 프로젝트: MechanisM/mirosubs
def index(request):
    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    user_langs = get_user_languages_from_request(request)
    
    if 'q' in request.REQUEST:
        form = SearchForm(request.user, user_langs, request.REQUEST)
    else:
        form = SearchForm(request.user, user_langs)
    
    qs = SearchQuerySet().none()
    
    display_mode = 'all'
    
    if form.is_valid():
        qs = form.search_qs(SearchQuerySet().models(Video))
        display_mode = form.cleaned_data.get('display', 'all')
        
    if settings.HAYSTACK_SEARCH_ENGINE == 'dummy' and settings.DEBUG:
        q = request.REQUEST.get('q', '')
        qs = Video.objects.filter(title__icontains=q)
    
    context = {
        'query': request.REQUEST.get('q', ''),
        'form': form,
        'display_mode': display_mode
    }
        
    return object_list(request, queryset=qs,
                       paginate_by=30,
                       template_name='search/index.html',
                       template_object_name='result',
                       extra_context=context)   
예제 #16
0
def post_list(request, page=0):
    return list_detail.object_list(
        request,
        queryset = Post.objects.published(),
        paginate_by = 20,
        page = page,
    )
예제 #17
0
def project_index(request, username=None, tag=None):
    """
    The list of projects, which will optionally filter by user or tag,
    in which case a 'person' or 'tag' will be added to the context
    """
    queryset = Project.objects.live()
    if username:
        user = get_object_or_404(User, username=username)
        queryset = queryset.filter(user=user)
    else:
        user = None

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

    return object_list(
        request,
        queryset=queryset,
        extra_context={'person': user, 'tag': tag},
        page=int(request.GET.get('page', 1)),
        template_object_name='project',
    )
예제 #18
0
파일: views.py 프로젝트: s7fkcu/autodealer
def cabinet_for_dealer(request):
	page = 1
	if 'page' in request.GET:
		try: page = int(request.GET.get('page'))
		except: raise Http404()
		
	try: ds = Dealer.objects.get(user=request.user, is_banned=False, is_active=True)
	except: raise Http404()
	else:
		if not ds.is_license: return HttpResponseRedirect('/cabinet/license/')
		
		dsc = Category.objects.filter(Q(is_active=True) | Q(dealer=ds))

		return list_detail.object_list(
			request,
			queryset = dsc,
			paginate_by = conf.PAGINATE_BY,
			page = page,
			template_name = 'cabinet/for_dealer.html',
			template_object_name = 'dsc',
			extra_context = {
				'a':3,
				'a1':6,
				'ds':ds,
			},
			context_processors = [cabinet_proc],
		)
예제 #19
0
파일: views.py 프로젝트: s7fkcu/autodealer
def cabinet_bookmark(request):
	page = 1
	if 'page' in request.GET:
		try: page = int(request.GET.get('page'))
		except: raise Http404()
		
	try: ds = Dealer.objects.get(user=request.user, is_banned=False, is_active=True)
	except: raise Http404()
	else:
		dsbm = Bookmark.objects.filter((Q(category__is_active=True) | Q(category__dealer=ds)) & Q(dealer=ds))

		return list_detail.object_list(
			request,
			queryset = dsbm,
			paginate_by = conf.PAGINATE_BY,
			page = page,
			template_name = 'cabinet/bookmark.html',
			template_object_name = 'dsbm',
			extra_context = {
				'a':3,
				'a1':7,
				'ds':ds,
				'dsbm':dsbm
			},
			context_processors = [cabinet_proc],
		)
예제 #20
0
def category_detail(request, slug, page=0, **kwargs):
    """
    Category detail

    Template: ``blog/post_list.html``
    Context:
        object_list
            List of posts specific to the given category.
        category
            Given category.
    """
    category = get_object_or_404(Category, slug__iexact=slug)

    return list_detail.object_list(
        request,
        queryset=category.post_set.published(),
        paginate_by=blog_settings.BLOG_PAGESIZE,
        page=page,
        extra_context={
            'type': 'category',
            'query': category.id,
            'query_pretty': category.title.capitalize()
        },
        template_name='blog/post_list.html',
        **kwargs
    )
예제 #21
0
def question_detail(request, question_id):
    """
    Displays a question's detail, comments and such
    on post, will store a new answer
    """
    question = get_object_or_404(Question, pk=question_id)

    ordering_posibilities = {"oldest": "added_on", "newest": "-added_on"}

    ordering = "-votes_result"
    if "order_by" in request.REQUEST:
        order_by = request.REQUEST["order_by"]
        if order_by in ordering_posibilities.keys():
            ordering = ordering_posibilities["order_by"]

    form = AnswerForm()
    if request.method == "POST":
        user = request.user
        if user.is_authenticated():
            form = AnswerForm(request.POST)
            if form.is_valid():
                answer = form.save(question, user)
                question.save()  # updates answer count
                user.message_set.create(message=strings.ANSWER_SAVED)
                return HttpResponseRedirect(question.get_absolute_url())
        else:
            # User is not authenticated but somehow submitted a POST request
            return HttpResponseNotAllowed(["GET"])

    return object_list(
        request,
        question.answers.order_by(ordering),
        template_name="emptyheap/question_detail.html",
        extra_context={"object": question, "form": form},
    )
예제 #22
0
def index_req(request):
    return object_list(request,
                       queryset = ExternalApplication.objects.order_by('ea_name'),
                       template_name = 'applications/index.html',
                       paginate_by = 20,
                       allow_empty = True,
                       extra_context = default_context(request))
예제 #23
0
def tag_detail(request, slug, page=0, **kwargs):
    """
    Tag detail

    Template: ``blog/post_list.html``
    Context:
        object_list
            List of posts specific to the given tag.
        tag
            Given tag.
    """
    tag = get_object_or_404(Tag, slug__iexact=slug)

    return list_detail.object_list(
        request,
        queryset=Post.objects.filter(tags__name__in=[tag]),
        paginate_by=blog_settings.BLOG_PAGESIZE,
        page=page,
        extra_context={
            'type': 'tag',
            'query': tag.id,
            'query_pretty': tag
        },
        template_name='blog/post_list.html',
        **kwargs
    )
예제 #24
0
파일: views.py 프로젝트: GunioRobot/price
def search(request):
    query = request.GET.get('q', '')
    if query:
        results = Goods.objects.filter(title__icontains=query).distinct()
    else:
        results = []
    return object_list(request, queryset=results, paginate_by=25)
예제 #25
0
파일: views.py 프로젝트: barontxu/djbookru
def topic(request, pk):
    user = request.user
    topic = get_object_or_404(Topic, pk=pk)

    if not topic.has_access(user):
        raise Http404

    Topic.objects.filter(pk=pk).update(views=F('views') + 1)
    qs = topic.posts.all()
    form = None

    if topic.can_post(user):
        form = AddPostForm(topic, user)

    topic.mark_visited_for(user)

    extra_context = {
        'form': form,
        'forum': topic.forum,
        'topic': topic,
        'has_access': topic.has_access(user)
    }
    return object_list(request, qs, POSTS_ON_PAGE,
                       template_name='djforum/topic.html',
                       extra_context=extra_context)
예제 #26
0
파일: views.py 프로젝트: B-Rich/M2M
def city_list(request, **kwargs):
    return list_detail.object_list(
        request,
        queryset = City.objects.all(),
        paginate_by = 20,
        **kwargs
    )
예제 #27
0
def language_detail(request, slug):
    language = get_object_or_404(Language, slug=slug)
    return object_list(request,
                       queryset=language.snippet_set.all(),
                       paginate_by =10,
                       template_name='codeman/language_detail.html',
                       extra_context={'language': language})
예제 #28
0
파일: views.py 프로젝트: B-Rich/M2M
def place_list(request, **kwargs):
    return list_detail.object_list(
        request,
        queryset = Place.objects.all(),
        paginate_by = 20,
        **kwargs
    )
예제 #29
0
def forum(request, slug):
    """
    显示当前论坛下面的帖子数
    select_related()增加了缓存性能
    """
    the_groups = request.user.groups.all()


    # 防止直接输入不存在或者没有权限的地址进行访问
    try:
        f = Forum.objects.for_groups(the_groups).select_related().get(slug=slug)
    except Forum.DoesNotExist:
        raise Http404

    form = CreateThreadForm()
    child_forums = f.child.for_groups(the_groups)
    return object_list( request,
                        queryset=f.thread_set.select_related().all(),
                        paginate_by=FORUM_PER_PAGE,
                        template_object_name='thread',
                        template_name='forum/thread_list.html',
                        extra_context = {
                            'forum': f,
                            'child_forums': child_forums,
                            'form': form,
                        })
예제 #30
0
def thread(request, thread):
    """
    增加帖子子的点击数
    并显示本帖子里发布的话题
    """
    try:
        t = Thread.objects.select_related().get(pk=thread)
        if not Forum.objects.has_access(t.forum, request.user.groups.all()):
            raise Http404
    except Thread.DoesNotExist:
        raise Http404

    p = t.post_set.select_related('author').all().order_by('time')

    # 增加帖子的访问量
    t.views += 1
    t.save()

    form = ReplyForm()

    return object_list( request,
                        queryset=p,
                        paginate_by=FORUM_PER_PAGE,
                        template_object_name='post',
                        template_name='forum/thread.html',
                        extra_context = {
                            'forum': t.forum,
                            'thread': t,
                            'form': form,
                        })
예제 #31
0
def tags(request, user_id=0, tag_id=0):
    context_map,user,view_user=\
        init_context(request, user_id=user_id, context_map={})
    usertags = view_user.usertag_set.all()[:100]
    context_map['usertags'] = usertags
    if tag_id:
        usertag = UserTag.objects.get(pk=tag_id)
        context_map['tag'] = usertag
        photos = usertag.photos.all()
    else:
        photos = view_user.photo_set.all()
        if not is_superuser(user):
            photos = photos.filter(show_type='s')
        photos = photos.order_by("-create_date")
    #context_map['self_photos']=self_photos
    return object_list(request,
                       photos,
                       paginate_by=20,
                       template_name='space/tags.html',
                       extra_context=context_map,
                       allow_empty=True)
예제 #32
0
def bysite(request, site):
    topinfo=''
    if site=='features':
        stories = Post.objects.published().filter(is_featured=True)   
    else:
        stories = Post.objects.published().filter(whichsite=site)  

    if site=='FLIT':
        t='flit.html'
    elif site=='SS':
        t='ss.html'
    else:
        t='posts_lede.html'

    return list_detail.object_list(request,
                    queryset=stories,
                    paginate_by=POSTS_PER_PAGE,
                    template_name=t,
                    template_object_name='post', allow_empty=True,
                    extra_context={'topinfo': topinfo},
                    )
예제 #33
0
def view(request, pk, slug=None, count=15):
    """
    Displays the videos of a given playlist.
    """
    playlist = get_object_or_404(Playlist, pk=pk)
    if playlist.status != Playlist.PUBLIC:
        if not request.user_is_admin() and \
                request.user != playlist.user:
            raise Http404
    if request.path != playlist.get_absolute_url():
        return HttpResponsePermanentRedirect(playlist.get_absolute_url())
    return object_list(request=request,
                       queryset=playlist.video_set,
                       paginate_by=count,
                       template_name='localtv/playlists/view.html',
                       allow_empty=True,
                       template_object_name='video',
                       extra_context={
                           'playlist': playlist,
                           'video_url_extra': '?playlist=%i' % playlist.pk
                       })
예제 #34
0
def category_detail(request,
                    slug,
                    template_name='blog/category_detail.html',
                    **kwargs):
    """
    Category detail

    Template: ``blog/category_detail.html``
    Context:
        object_list
            List of posts specific to the given category.
        category
            Given category.
    """
    category = get_object_or_404(Category, slug__iexact=slug)

    return list_detail.object_list(request,
                                   queryset=category.post_set.published(),
                                   extra_context={'category': category},
                                   template_name=template_name,
                                   **kwargs)
예제 #35
0
def video_list(request):
    qs = Video.objects.filter(is_subtitled=True)
    ordering = request.GET.get('o')
    order_type = request.GET.get('ot')
    extra_context = {}
    order_fields = [
        'languages_count', 'widget_views_count', 'subtitles_fetched_count',
        'was_subtitled'
    ]
    if ordering in order_fields and order_type in ['asc', 'desc']:
        qs = qs.order_by(('-' if order_type == 'desc' else '') + ordering)
        extra_context['ordering'] = ordering
        extra_context['order_type'] = order_type
    else:
        qs = qs.order_by('-widget_views_count')
    return object_list(request,
                       queryset=qs,
                       paginate_by=50,
                       template_name='videos/video_list.html',
                       template_object_name='video',
                       extra_context=extra_context)
예제 #36
0
파일: views.py 프로젝트: llimllib/Sqft
def results(request):
    apts = Rental.objects.filter(
        bedrooms__gte=request.POST['bedFloor'],
        full_bathrooms__gte=request.POST['bathFloor'],
        monthly_rent__gte=request.POST['priceFloor'],
        monthly_rent__lte=request.POST['priceCeiling'])
    if len(request.POST['neighborhoods']) > 0:
        apts = apts.filter(neighborhood__in=request.POST['neighborhoods'].split(","))
        
    aptsjson = serializers.serialize("json", apts)

    hood_groups = {}
    for apt in apts:
        hood = apt.neighborhood.name
        center = apt.neighborhood.center_point
        hood_groups.setdefault(hood, [center]).append(apt)
    
    hoods = Neighborhood.objects.all()

    hood_data = []
    for hood in hoods[:PAGE_SIZE]:
        hood = _serialize(hood)
        hood_data.append(hood)

    feature_data = {}
    for f in Feature.objects.all():
        feature_data.setdefault(f.room, []).append({'feature_id': f.pk, 'name': f.name})

    
    return object_list(request,
                       template_name        = 'results.html',
                       queryset             = apts,
                       template_object_name = 'rentals',
                       extra_context        = {'aptsjson':  aptsjson,
                                               'hood_apts': hood_groups,
                                               'hood_names': _get_hood_groups(),
                                               'hood_data': simplejson.dumps(hood_data),
                                               'features': simplejson.dumps(feature_data),
                                               'search_request': request.POST, 
                                               'gmaps_key': GMAPS_API_KEY})
예제 #37
0
def video_search(request, count=None, sort=None):
    count = count_or_default(count)

    query = ''
    pks = []

    if 'query' in request.GET and 'q' not in request.GET:
        # old-style templates
        GET = request.GET.copy()
        GET['q'] = GET['query']
        request.GET = GET

    if request.GET.get('q'):
        form = VideoSearchForm(request.GET)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
            pks = [result.pk for result in results if result is not None]

    if not pks:
        queryset = models.Video.objects.none()
    elif sort == 'latest':
        queryset = models.Video.objects.new(site=request.sitelocation.site,
                                            status=models.VIDEO_STATUS_ACTIVE,
                                            pk__in=pks)
    else:
        queryset = models.Video.objects.filter(
            site=request.sitelocation.site,
            status=models.VIDEO_STATUS_ACTIVE,
            pk__in=pks).order_by()
        order = ['-localtv_video.id = %i' % int(pk) for pk in pks]
        queryset = queryset.extra(order_by=order)
    return object_list(request=request,
                       queryset=queryset,
                       paginate_by=count,
                       template_name='localtv/video_listing_search.html',
                       allow_empty=True,
                       template_object_name='video',
                       extra_context={'query': query})
예제 #38
0
def session_detail(request, profile_id, session_id, template_name='spider/session_detail.html'):
    profile = get_object_or_404(SpiderProfile, pk=profile_id)
    session = get_object_or_404(profile.sessions.all(), pk=session_id)
    queryset = session.results.all()
    
    max_id = queryset.aggregate(max_id=Max('id'))['max_id'] or 0
    
    if request.is_ajax():
        max_id = int(request.GET.get('max_id', max_id))
        context = {'max_id': max_id, 'complete': session.complete, 'results': []}
        
        queryset = queryset.order_by('-pk')
        results = queryset.filter(pk__gt=max_id).order_by('-id')
        
        if results:
            context['max_id'] = results[0].pk
            context['results'] = [
                render_to_string('spider/includes/result_list.html', {'object': r}) \
                    for r in results
            ]
        
        return json_response(context)
    else:
        ordering = request.GET.get('ordering', '').lstrip('-')
        if ordering in ('response_time', 'content_length', 'url', 'response_status'):
            queryset = queryset.order_by(request.GET['ordering'])
        else:
            queryset = queryset.order_by('-response_status', 'url')
        
        return object_list(
            request,
            queryset=queryset,
            template_name=template_name,
            paginate_by=50,
            page=int(request.GET.get('page', 1)),
            extra_context={
                'session': session,
                'max_id': max_id,
            }
        )
예제 #39
0
def user_list(request):
    Permission.objects.check_permissions(request.user, [PERMISSION_USER_VIEW])

    return object_list(
        request,
        queryset=User.objects.exclude(is_superuser=True).exclude(
            is_staff=True).order_by('username'),
        template_name='generic_list.html',
        extra_context={
            'title':
            _(u'users'),
            'hide_link':
            True,
            'extra_columns': [
                {
                    'name': _(u'full name'),
                    'attribute': 'get_full_name'
                },
                {
                    'name': _(u'email'),
                    'attribute': 'email'
                },
                {
                    'name':
                    _(u'active'),
                    'attribute':
                    encapsulate(lambda x: two_state_template(x.is_active)),
                },
                {
                    'name':
                    _(u'has usable password?'),
                    'attribute':
                    encapsulate(
                        lambda x: two_state_template(x.has_usable_password())),
                },
            ],
            'multi_select_as_buttons':
            True,
        },
    )
예제 #40
0
def project_search(request):
    q = request.GET.get('q', '')
    form = ProjectSearchForm()
    q = q.strip()

    if request.method == "POST":
        form = ProjectSearchForm(request.POST)
        if form.is_valid():
            q = form.cleaned_data['q'].strip()
        else:
            q = None

    if q is None:
        projects = ProjectApplication.objects.none()
    else:
        accepted_projects = request.user.projectmembership_set.filter(
            ~Q(acceptance_date__isnull=True)).values_list('project', flat=True)
        projects = ProjectApplication.objects.search_by_name(q)
        projects = projects.filter(~Q(project__last_approval_date__isnull=True))
        projects = projects.exclude(project__in=accepted_projects)

    table = tables.UserProjectApplicationsTable(projects, user=request.user,
                                                prefix="my_projects_")
    if request.method == "POST":
        table.caption = _('SEARCH RESULTS')
    else:
        table.caption = _('ALL PROJECTS')

    RequestConfig(request, paginate={"per_page": settings.PAGINATE_BY}).configure(table)

    return object_list(
        request,
        projects,
        template_name='im/projects/project_list.html',
        extra_context={
          'form': form,
          'is_search': True,
          'q': q,
          'table': table
        })
예제 #41
0
def for_dealers_info(request, id, slug):
	page = 1
	if 'page' in request.GET:
		try: page = int(request.GET.get('page'))
		except: raise Http404()
		
	try: ds = Dealer.objects.get(user=request.user, is_banned=False, is_active=True)
	except: raise Http404()
	else:
		if not ds.is_license: return HttpResponseRedirect('/cabinet/license/')
		
		try: cs = Category.objects.get(id=id, is_active=True)
		except: raise Http404()
		else:	
			dsic = CategoryItem.objects.filter(is_active=True, category=cs)
			for ic in dsic:
				if ic.is_only_town:
					if not Dealer.objects.filter(
						user=request.user, is_banned=False, is_active=True,
						town__id__in=[tw.id for tw in ic.dealer.town.filter(is_active=True)]
					).count(): dsic = dsic.exclude(id=ic.id)
				if ic.is_only_brand:
					if not Dealer.objects.filter(
						user=request.user, is_banned=False, is_active=True,
						brand__id__in=[br.id for br in ic.dealer.brand.filter(is_active=True)]
					).count(): dsic = dsic.exclude(id=ic.id)
					
			siform = DealerAccountCategoryInfoSearchForm()
			
			return list_detail.object_list(
				request,
				queryset = dsic,
				paginate_by = conf.PAGINATE_BY,
				page = page,
				template_name = 'for_dealers/for_dealers_info.html',
				template_object_name = 'dsic',
				extra_context = {
					'a':2, 'siform':siform, 'ds':ds, 'cs':cs,
				},
			)
예제 #42
0
파일: views.py 프로젝트: itsbenweeks/Amara
def inbox(request, message_pk=None):
    user = request.user
    qs = Message.objects.for_user(user)

    extra_context = {
        'send_message_form':
        SendMessageForm(request.user, auto_id='message_form_id_%s'),
        'messages_display':
        True,
        'user_info':
        user
    }

    reply = request.GET.get('reply')

    if reply:
        try:
            reply_msg = Message.objects.get(pk=reply, user=user)
            reply_msg.read = True
            reply_msg.save()
            extra_context['reply_msg'] = reply_msg
        except (Message.DoesNotExist, ValueError):
            pass

    response = object_list(request,
                           queryset=qs,
                           paginate_by=MESSAGES_ON_PAGE,
                           template_name='messages/inbox.html',
                           template_object_name='message',
                           extra_context=extra_context)
    try:
        last_message = qs[:1].get()
        max_age = 60 * 60 * 24 * 365
        expires = cookie_date(time.time() + max_age)
        response.set_cookie(Message.hide_cookie_name, last_message.pk, max_age,
                            expires)
    except Message.DoesNotExist:
        pass

    return response
예제 #43
0
def vote_tag(request, tag):
    tag_instance = get_tag(tag)
    if tag_instance is None:
        raise Http404(_('No Tag found matching "%s".') % tag)

    extra_context = {'tag':tag_instance}
    extra_context['tag_url'] = reverse('vote-tag',args=[tag_instance])
    if 'member' in request.GET:
        extra_context['member'] = get_object_or_404(Member, pk=request.GET['member'])
        extra_context['member_url'] = reverse('member-detail',args=[extra_context['member'].id])
        extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s by %(member)s') % {'tag': tag, 'member':extra_context['member'].name}
        qs = extra_context['member'].votes.all()
    else: # only tag is given
        extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s') % {'tag': tag}
        qs = Vote

    queryset = TaggedItem.objects.get_by_model(qs, tag_instance)
    vote_attendence = [v.votes.all() for v in TaggedItem.objects.get_by_model(Vote, tag_instance)]
    d = {}
    for vote in vote_attendence:
        for v in vote:
            d[v] = d.get(v,0)+1
    # now d is a dict: MK -> number of votes in this tag
    mks = d.keys()
    if mks:
        for mk in mks:
            mk.count = d[mk]
        average = float(sum([mk.count for mk in mks]))/len(mks)
        mks = [mk for mk in mks if mk.count>=average]
        mks = tagging.utils.calculate_cloud(mks)
        extra_context['members'] = mks
    if request.user.is_authenticated():
        extra_context['watched_members'] = \
            request.user.get_profile().members
    else:
        extra_context['watched_members'] = False

    return object_list(request, queryset,
    #return tagged_object_list(request, queryset_or_model=qs, tag=tag,
        template_name='laws/vote_list_by_tag.html', extra_context=extra_context)
예제 #44
0
def full(request,
         id,
         template_name='gallery/item.html',
         extra_context=None,
         context_processors=None,
         template_loader=loader):
    page = 1
    if 'page' in request.GET and request.GET.get('page'):
        try:
            page = int(request.GET.get('page'))
        except ValueError:
            raise Http404()

    try:
        id = int(id)
    except ValueError:
        raise Http404()

    try:
        cat = CategoryGallery.activs.get(id=id)
    except ValueError:
        raise Http404()

    objs = PhotoGallery.activs.filter(category=cat)

    return list_detail.object_list(
        request,
        queryset=objs,
        paginate_by=conf.PAGINATE_FOTO_BY,
        page=page,
        template_name=template_name,
        template_object_name='item',
        extra_context={'cat': cat},
        context_processors=context_processors,
        template_loader=template_loader,
    )


##########################################################################
##########################################################################
예제 #45
0
def all_projects(request):
    """View to show all projects. Basically a view wrapped around
    a generic view. This was previously in the urls.py file (sans the 
    view). However,  extra_context has a queryset,  and it would only get
    executed *once*!"""

    projects_info = {
        'queryset': CollabProject.objects.all(),
        'template_object_name': 'projects',
        'template_name': 'project/projects.html',
        'extra_context': {
            'site_info':
            SiteInfo.objects.all()[:1],
            'teleconferences':
            TeleConference.objects.filter(
                time__gt=datetime.date.today(),
                time__lte=(datetime.date.today() +
                           datetime.timedelta(days=7))).order_by('time').all()
        }
    }

    return list_detail.object_list(request, **projects_info)
예제 #46
0
def list(
    request,
    app_label=None,
    model_name=None,
    id=None,
):
    ''' List checkins for object

    '''

    try:
        ct = ContentType.objects.get(app_label=app_label, model=model_name)
        obj = ct.get_object_for_this_type(id=id)

    except:
        raise Http404

    checkins = CheckIn.objects.filter(content_type=ct, object_id=obj.id)

    paginator = Paginator(checkins, 25)

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

    # If page request (9999) is out of range, deliver last page of results.
    try:
        page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        page = paginator.page(paginator.num_pages)

    return object_list(
        request,
        queryset=checkins,
        template_name='checkins/checkins_text_list.html',
        paginate_by=25,
        extra_context=locals(),
    )
예제 #47
0
def profileList(request):
    extra_context = {
        'sport_list': Sport.objects.annotate(Count('matchday_sport'))
    }
    if request.method == 'POST':
        since = request.POST['since']
        if since != '':
            since = datetime.strptime(since, "%d-%m-%Y")
            extra_context['since'] = since
        response = list_detail.object_list(
            request,
            extra_context=extra_context,
            queryset=PlayerProfile.objects.all(),
            template_name="profiles/profile_list.html",
        )
    else:
        response = profile_list(
            request,
            extra_context=extra_context,
            queryset=PlayerProfile.objects.all(),
        )
    return response
예제 #48
0
파일: views.py 프로젝트: klenks/jobsportal
def job_search(request):
    ''' A search view, does the job but not great. Job searches should be
        handled by a proper search app, namely django-haystack.
    '''
    query_string = ''
    found_entries = Job.objects.none()
    extra_context = {'keywords': ' '}
    if ('keywords' in request.POST) and request.POST['keywords'].strip():
        request.session['keywords'] = request.POST['keywords']
        query_string = request.session['keywords']
        extra_context['keywords'] = query_string
        search_fields = ['title', 'description', 'category',
                             'jobtype', 'city', 'outside_location', 'company',]
        entry_query = get_query(query_string, search_fields)
        jobs_per_search = djobberbase_settings.DJOBBERBASE_JOBS_PER_SEARCH
        found_entries = Job.objects.filter(entry_query)\
                                     .order_by('-created_on')[:jobs_per_search]
        search = JobSearch(keywords=query_string)
        search.save()
    return object_list(request, queryset=found_entries,
                    extra_context=extra_context,
                    paginate_by=djobberbase_settings.DJOBBERBASE_JOBS_PER_PAGE)
예제 #49
0
def entry_search(request):
    """Search entries matching with a pattern"""
    error = None
    pattern = None
    entries = Entry.published.none()

    if request.GET:
        pattern = request.GET.get('pattern', '')
        if len(pattern) < 3:
            error = _('The pattern is too short')
        else:
            entries = Entry.published.search(pattern)
    else:
        error = _('No pattern to search found')

    return object_list(request,
                       queryset=entries,
                       template_name='zinnia/entry_search.html',
                       extra_context={
                           'error': error,
                           'pattern': pattern
                       })
예제 #50
0
def detail_old(request, slug, is_debugging=False, languages=None):
    team = Team.get(slug, request.user)

    if languages is None:
        languages = get_user_languages_from_request(request)
    if bool(is_debugging):
        languages = request.GET.get("langs", "").split(",")

    data = team.get_videos_for_languages(languages, CUTTOFF_DUPLICATES_NUM_VIDEOS_ON_TEAMS)
    mqs = data['videos']
    
    extra_context = widget.add_onsite_js_files({})    
    extra_context.update({
        'team': team,
        'can_edit_video': team.can_edit_video(request.user)
    })

    general_settings = {}
    add_general_settings(request, general_settings)
    extra_context['general_settings'] = json.dumps(general_settings)

    if team.video:
        extra_context['widget_params'] = base_widget_params(request, {
            'video_url': team.video.get_video_url(), 
            'base_state': {}
        })

    if bool(is_debugging) and request.user.is_staff:
        extra_context.update(data)
        extra_context.update({
            'languages': languages,
            })
        return render_to_response("teams/detail-debug.html", extra_context, RequestContext(request))
    
    return object_list(request, queryset=mqs, 
                       paginate_by=VIDEOS_ON_PAGE, 
                       template_name='teams/detail.html', 
                       extra_context=extra_context, 
                       template_object_name='team_video_md')
예제 #51
0
def completed_videos(request, slug):
    team = Team.get(slug, request.user)
    
    qs = SearchQuerySet().models(TeamVideo).filter(team_id=team.id) \
        .filter(is_complete=True).order_by('-video_complete_date')

    extra_context = widget.add_onsite_js_files({})    
    extra_context.update({
        'team': team
    })
    
    if team.video:
        extra_context['widget_params'] = base_widget_params(request, {
            'video_url': team.video.get_video_url(), 
            'base_state': {}
        })

    return object_list(request, queryset=qs, 
                       paginate_by=VIDEOS_ON_PAGE, 
                       template_name='teams/completed_videos.html', 
                       extra_context=extra_context, 
                       template_object_name='team_video')    
예제 #52
0
def liaison_approval_list(request):
    if is_secretariat(request.user):
        to_approve = LiaisonDetail.objects.filter(
            approved=None).order_by("-submitted")
    else:
        person = get_person_for_user(request.user)
        approval_codes = IETFHM.get_all_can_approve_codes(person)
        if settings.USE_DB_REDESIGN_PROXY_CLASSES:
            to_approve = approvable_liaison_statements(
                approval_codes).order_by("-submitted")
        else:
            to_approve = LiaisonDetail.objects.filter(
                approval__isnull=False,
                approval__approved=False,
                from_raw_code__in=approval_codes).order_by("-submitted_date")

    return object_list(
        request,
        to_approve,
        allow_empty=True,
        template_name='liaisons/liaisondetail_approval_list.html',
    )
예제 #53
0
def news_by_day(request):
    d = {}
    d['user'] = request.user
    d['news_by_day'] = True

    manipulator = QueryManipulator()

    date = datetime.datetime.now().date()
    date_next = date + datetime.timedelta(1)

    if request.method == 'GET':
        try:
            date_tuple = request.GET['date'].split('-')
            date_tuple = map(int, date_tuple)

            date = datetime.date(date_tuple[0], date_tuple[1], date_tuple[2])
            date_next = date + datetime.timedelta(1)
            d['date_next'] = date_next

        except:
            pass

    d['date'] = date

    date_previous = date + datetime.timedelta(-1)

    d['date_previous'] = date_previous

    qs = Newsitem.objects.select_related().filter(
        time__range=(date, date_next)).filter(
            Q(source__name="AFP") | Q(source__name="AP")
            | Q(source__name="Reuters")
            | Q(source__name="ATS")).order_by('-time')

    return object_list(request,
                       qs,
                       paginate_by=1000,
                       template_name="nm/news_by_day.html",
                       extra_context=d)
예제 #54
0
파일: views.py 프로젝트: modamania/otdohni
def photoreport_list(request, tag_slug=None, **kwargs):
    queryset = PhotoReport.objects.active().select_related()

    tags = Tag.objects.filter(
        photoreports__is_published=True, ).distinct().annotate(
            total=Count('photoreports'))
    tags = calculate_tag_cloud(tags)
    kwargs['extra_context'] = {'tags': tags}

    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        queryset = queryset.filter(tags=tag)
        kwargs['extra_context'] = {
            'tag': tag,
            'tags': tags,
        }

    load_related_m2m(queryset, 'tags')
    kwargs['queryset'] = queryset
    kwargs['template_object_name'] = "photoreport"

    return object_list(request, **kwargs)
예제 #55
0
def generic_wrapper(request, *args, **kwargs):
    """
    This allows us to get the mediatype variable from the url and pass the 
    correct queryset to the generic view
    """
    if 'mediatype' in kwargs and kwargs['mediatype'] in media_dict:
        mediatype = kwargs.pop('mediatype')
        queryset = media_dict[mediatype]['queryset']
        if 'extra_context' in kwargs:
            kwargs['extra_context'].update({'mediatype': mediatype})
        else:
            kwargs['extra_context'] = {'mediatype': mediatype}
        if 'enlarge' in kwargs:
            kwargs.pop('enlarge')
            kwargs[
                'template_name'] = 'massmedia/enlarge_%s_detail.html' % mediatype
        if 'slug' in kwargs or 'object_id' in kwargs:
            return object_detail(request, queryset, *args, **kwargs)
        if 'template_name' not in kwargs:
            kwargs['template_name'] = 'massmedia/list.html'
        return object_list(request, queryset, *args, **kwargs)
    return HttpResponseNotFound()
예제 #56
0
def all_teleconferences(request, project_name):
    """Takes in the the project id and shows all teleconferences (upcoming and archived)."""

    project = get_object_or_404(CollabProject, slug=project_name)
    project_id = project.id
    
    if not is_allowed(request,  project_id,  TeleConference._meta.verbose_name,  'Viewable'):
        return handle_privilege(request, "You do not have privileges to view teleconferences!", project.get_absolute_url())

    if is_allowed(request,  project_id,  TeleConference._meta.verbose_name,  'Editable'):
        editable = True
    else:
        editable = False

    teleconferences_list = {
                          'queryset': TeleConference.objects.filter(project__id=project_id).filter(time__gte=datetime.date.today()).order_by('time'),   
                          'template_name': 'teleconference/alltele.html', 
                          'template_object_name': 'upcoming_tele', 
                          'extra_context': {'past_tele': TeleConference.objects.filter(project__id=project_id).filter(time__lt=datetime.date.today()).order_by('-time'),  'project': project, 'editable': editable}, 
                        }
    
    return list_detail.object_list(request,  **teleconferences_list)
예제 #57
0
def admin_user_posts(request, group, user_id):
    if not has_permission_flag(request.user, 'community_manage_users'):
        raise PermissionDenied()

    user = get_object_or_404(User, pk=user_id)

    orderby = request.GET.get('orderby', '-postdate')
    post_list = Post.objects.filter(author=user).order_by(orderby)

    template_name = 'sphene/sphboard/admin_user_posts.html'
    context = {'author': user, 'orderby': orderby}

    res = object_list(
        request=request,
        queryset=post_list,
        template_name=template_name,
        template_object_name='post',
        extra_context=context,
        allow_empty=True,
        paginate_by=10,
    )
    return res
예제 #58
0
파일: views.py 프로젝트: skripkar/noc
 def view_view(self, request, refbook_id):
     """
     Refbook preview
     :param request:
     :param refbook_id:
     :return:
     """
     rb = get_object_or_404(RefBook, id=int(refbook_id))
     can_edit = (not rb.is_builtin and Permission.has_perm(
         request.user, "main.change_refbookdata"))
     queryset = rb.refbookdata_set.all()
     # Search
     if (request.GET and "query" in request.GET and request.GET["query"]):
         query = request.GET["query"]
         # Build query clause
         w = []
         p = []
         for f in rb.refbookfield_set.filter(search_method__isnull=False):
             x = f.get_extra(query)
             if not x:
                 continue
             w += x["where"]
             p += x["params"]
         w = " OR ".join(["(%s)" % x for x in w])
         queryset = queryset.extra(where=["(%s)" % w], params=p)
     else:
         query = ""
         # Use generic view for final result
     return list_detail.object_list(
         request,
         queryset=queryset,
         template_name=self.get_template_path("view.html")[0],
         extra_context={
             "rb": rb,
             "can_edit": can_edit,
             "query": query
         },
         paginate_by=100,
     )
예제 #59
0
def visible_survey_list(request,
                        group_slug=None,
                        group_slug_field=None,
                        group_qs=None,
                        login_required=False,
                        template_name="survey/survey_list.html",
                        extra_context=None,
                        *args,
                        **kw):
    login_user = request.user
    if login_required and not login_user.is_authenticated():
        return redirect_to_login(request.path)
    else:
        return object_list(
            request, **{
                'queryset': Survey.objects.filter(visible=True),
                'allow_empty': True,
                'template_name': template_name,
                'extra_context': {
                    'title': _('Surveys')
                }
            })
예제 #60
0
def group_list(request):
    Permission.objects.check_permissions(request.user, [PERMISSION_GROUP_VIEW])

    return object_list(
        request,
        queryset=Group.objects.all(),
        template_name='generic_list.html',
        extra_context={
            'title':
            _(u'groups'),
            'hide_link':
            True,
            'extra_columns': [
                {
                    'name': _(u'members'),
                    'attribute': 'user_set.count'
                },
            ],
            'multi_select_as_buttons':
            True,
        },
    )