我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.views.generic.View()。
def anuncio(request): anuncios = getTodosAnunciosValidos() form = formBusca() edit_forms = getFormsEdicaoDeAnuncios(anuncios) return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':"Localidade ", 'editforms':edit_forms }) ################################################################################################### #View que renderiza anuncios do banco de dados filtrados por localidade. # #Nome: anuncioPorLocal #Autor: Renan Basilio #Versao: 1.0 # #Algoritmo: # 1. Chama o metodo getAnunciosPorLocalidade com o parametro localidade fornecido pela url # 2. Inicializa uma form de busca # 3. Chama o metodo render # ####################################################################################################
def anuncioPorLocal(request, localidade): anuncios = getAnunciosPorLocalidade(localidade) edit_forms = getFormsEdicaoDeAnuncios(anuncios) nome_local = Localidade.objects.get(nome_filtro=localidade).nome + ' ' form = formBusca() return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':nome_local, 'editforms':edit_forms}) ################################################################################################### #View que renderiza anuncios do banco de dados filtrados por um termo de busca # #Nome: anuncioPorBusca #Autor: Renan Basilio #Versao: 1.0 # #Algoritmo: # 1. Inicializa uma form de busca # 2. Chama o metodo getAnunciosPorSubstring com o parametro 't' fornecido pela url # 3. Chama o metodo render # ####################################################################################################
def anuncioPorBusca(request): form = formBusca(request.GET) anuncios = getAnunciosPorSubstring(request.GET.get('t')) edit_forms = getFormsEdicaoDeAnuncios(anuncios) return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':"Localidade ", 'editforms':edit_forms}) ################################################################################################### #View que renderiza anuncios do banco de dados filtrados pelo usuario que os criou # #Nome: anuncioPorUsuario #Autor: Renan Basilio #Versao: 1.0 # #Algoritmo: # 1. Verifica se o usuario esta autenticado # 2. Se nao retorna uma HttpResponseForbidden # 3. Se sim, inicializa form de busca e constroi lista de anuncios a partir do metodo getAnunciosPorUsuario # 4. Chama o metodo render # ####################################################################################################
def __init__(self, view_class, *args, **kwargs): """ view_class : View Class used to render content popup dialog view_class must be subclass of django.views.generic.View """ # Check view_class inherit from django View if not issubclass(view_class, View): raise PopupViewIsNotSubclassView() view_class_name = view_class.__name__ popup_dialog_title = kwargs.pop("popup_dialog_title", _("Popup Dialog: Select value")) super(PopupViewField, self).__init__( widget=PopupViewWidget( view_class_name=view_class_name, popup_dialog_title=popup_dialog_title ), *args, **kwargs )
def test_rate(self): req = rf.post('/') class TwiceView(RatelimitMixin, View): ratelimit_key = 'ip' ratelimit_rate = '2/m' def post(self, request, *args, **kwargs): return request.limited get = post twice = TwiceView.as_view() assert not twice(req), 'First request is not limited.' assert not twice(req), 'Second request is not limited.' assert twice(req), 'Third request is limited.'
def test_bad_cache(self): """The RATELIMIT_USE_CACHE setting works if the cache exists.""" self.skipTest('I do not know why this fails when the other works.') class BadCacheView(RatelimitMixin, View): ratelimit_key = 'ip' def post(self, request, *args, **kwargs): return request get = post view = BadCacheView.as_view() req = rf.post('/') with self.assertRaises(InvalidCacheBackendError): view(req)
def attach_profile_and_content_to_context(request, content_path, context): """Attaches UserProfile data and yaml content to a request context. Args: request: a Request instance passed to the View content_path: path to our static yaml content context: a base context to be modified Returns: the modified context """ if not request.user.is_anonymous(): context['user_profile'] = UserProfile.objects.get(user=request.user) if content_path: with open(content_path) as content_file: content = yaml.safe_load(content_file) for item in content: context[item] = content[item] return context
def dispatch(self, request, *args, **kwargs): """ Most views in a CMS require a login, so this is the default setup. If a login is not required then the requires_login property can be set to False to disable this. """ if self.requires_login: if settings.LOGIN_URL is None or settings.LOGOUT_URL is None: raise ImproperlyConfigured( 'LOGIN_URL and LOGOUT_URL ' 'has to be defined if requires_login is True' ) if not request.user.is_authenticated(): return redirect('%s?next=%s' % ( resolve_url(settings.LOGIN_URL), quote(request.get_full_path()))) return super(View, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs): context = super(View, self).get_context_data(**kwargs) context['page_title'] = self.get_page_title() context['page_description'] = self.get_page_description() context['menu'] = menu(user=self.request.user, request=self.request) context['urls'] = self.get_urls() context['breadcrumbs'] = self.get_breadcrumbs() context['tabs'] = self.get_tabs() context['index_url'] = self.get_index_url() context['SITE_NAME'] = self.get_site_name() context['SITE_TITLE'] = self.get_site_title() context['SITE_LOGO'] = self.get_site_logo() context['SIDEBAR_BACKGROUND'] = self.get_sidebar_background() context['SIDEBAR_COLOR'] = self.get_sidebar_color() context['SIDEBAR_ALT_COLOR'] = self.get_sidebar_alt_color() context['HIGHLIGHT_BACKGROUND'] = self.get_highlight_background() context['HIGHLIGHT_COLOR'] = self.get_highlight_color() context['DATETIME_FORMATS'] = self.get_datetime_formats() context['LOGIN_URL'] = self.get_login_url() context['LOGOUT_URL'] = self.get_logout_url() context['media'] = self.media context['form_display'] = self.get_form_display() return context
def get(self, request, poet_id, slug_id, id): try: poem = Poem.objects.get(id=id, author_id=poet_id) if poem.is_shown == 0 and (not request.user or request.user.id != poem.added_user_id): raise Http404('Page not found') except Poem.DoesNotExist: raise Http404('Page not found') view, created = View.objects.get_or_create(poem_id=poem.id) view.views_count = view.views_count + 1 view.save() poet = Poet.objects.get(id=poet_id) return render(request, self.template_name, { 'poem': poem, 'poet': poet, })
def post(self, request): """ Handling GET method :param request: Request to View :return: HttpResponse with code 201 if user is created or HttpResponseBadRequest if request contain incorrect data """ verification_code = request.GET.get("code", "") invitation = AdviserInvitations.get_invitation(verification_code) user_registration_form = UserRegistrationForm(json.loads(request.body)) if not user_registration_form.is_valid(): return HttpResponseBadRequest("Invalid input data. Please edit and try again.") AdviserUser.create_user(user_registration_form, invitation) invitation.close_invitation() return HttpResponse(status=201)
def post(self, request): """Handling GET method :param request: Request to View :return: HttpResponse with code 201 if user is invited or HttpResponseBadRequest if request contain incorrect data """ invite_form = UserInvitationForm(json.loads(request.body)) if not invite_form.is_valid(): return HttpResponseBadRequest("Invalid input data. Please edit and try again.") if AdviserUser.objects.filter(user__email=invite_form.data[u'email']).exists(): return HttpResponseBadRequest("User with this e-mail is registered") if AdviserInvitations.objects.filter(email=invite_form.data[u'email']).exists(): return HttpResponseBadRequest("User with this e-mail is already invited") sender = EmailSender(invite_form.data[u'email']) sender.send_invite(invite_form.data[u'id_company']) return HttpResponse(status=201)
def put(self, request): """ :param request: Request to View :return: change user info """ data = json.loads(request.body) user_form = UserForm(data['User']) if not user_form.is_valid(): return HttpResponseBadRequest('Invalid input data', status=400) adviser_user = AdviserUser.objects.get(id=data['AdviserUser']['id']) adviser_user.set_adviser_user(data['AdviserUser']) user = User.objects.get(id=data['User']['id']) user.last_name = data['User']['last_name'] user.first_name = data['User']['first_name'] user.save() return HttpResponse(status=201)
def get(self, request, *args, **kwargs): """ Main entry. This View only responds to GET requests. """ context = self.chart_instance.chartjs_configuration(*args, **kwargs) return self.render_json_response(context)
def anuncioPorUsuario(request): if request.user.is_authenticated(): form = formBusca() anuncios = getAnunciosPorUsuario(request.user) edit_forms = getFormsEdicaoDeAnuncios(anuncios) return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':"Localidade ", 'editforms':edit_forms}) else: return HttpResponseForbidden() ################################################################################################### #View que renderiza anuncios do banco de dados com aprovacao pendente # #Nome: anuncioPendendoAp #Autor: Renan Basilio #Versao: 0.1 # #Algoritmo: # 1. Verifica se o usuario esta autenticado, se nao retorna uma HttpResponseForbidden # 2. Se sim verifica se o usuario tem permissao para aprovar anuncios, se nao tiver passa o controle # para a view geral # 3. Se sim: # Inicializa form de busca # Recupera os anuncios com aprovacao pendente pelo metodo getAnunciosApPendente # Chama o metodo render # ####################################################################################################
def __call__(self, func): if hasattr(func, '__params__'): func.__params__.append(self) return func @wraps(func) def _decorator(*args, **kwargs): if len(args) < 1: # Call function immediately, maybe raise an error is better. return func(*args, **kwargs) extra_kwargs = None if isinstance(args[0], View): request = args[0].request # Update the kwargs from Django REST framework's APIView class if isinstance(args[0], APIView): extra_kwargs = args[0].kwargs else: # Find the first request object for arg in args: if isinstance(arg, (RestRequest, HttpRequest)): request = arg break else: request = args[0] if request: # Checkout all the params first. for _param in _decorator.__params__: _param._parse(request, kwargs, extra_kwargs) # Validate after all the params has checked out, because some validators needs all the params. for _param in _decorator.__params__: for validator in _param.validators: validator(_param.related_name, kwargs, _param.verbose_name) return func(*args, **kwargs) _decorator.__params__ = [self] return _decorator
def thumber_feedback(view): # Cannot wrap view functions or classes that don't inherit from class-based View if type(view) is types.FunctionType or not issubclass(view, View): raise ImproperlyConfigured('Only class-based views can be decorated with `thumber_feedback') # Make a new class that inherits from the ThumberView, and the wrapped view class return type('ThumberFeedbackView', (ThumberView, view,), {})
def test_registry_validate(self): # This class is not subclass django.views.generic.View class PopupView(object): pass with self.assertRaises(PopupViewIsNotSubclassView): registry_popup_view.validate(PopupView) with self.assertRaises(PopupViewIsNotSubclassView): registry_popup_view.register(PopupView)
def test_register_unregister(self): class PopupView(View): pass with self.assertRaises(PopupViewNotRegistered): registry_popup_view.unregister(PopupView) # First register registry_popup_view.register(PopupView) # Second register with self.assertRaises(PopupViewAlreadyRegistered): registry_popup_view.register(PopupView) # Get view class by name assert registry_popup_view.get("PopupView") == PopupView # Unregister class registry_popup_view.unregister(PopupView) with self.assertRaises(PopupViewNotRegistered): registry_popup_view.get("PopupView") # Register and unregister by name registry_popup_view.register(PopupView) registry_popup_view.unregister_by_name("PopupView") with self.assertRaises(PopupViewNotRegistered): registry_popup_view.unregister_by_name("PopupView")
def validate(self, view_class): if not issubclass(view_class, View): raise PopupViewIsNotSubclassView()
def unregister(self, view_class): self.validate(view_class) view_class_name = view_class.__name__ if view_class_name not in self._registry: raise PopupViewNotRegistered('Popup View {0} not registered'.format(view_class_name)) self._registry.pop(view_class_name, None)
def get(self, view_class_name): view_class = self._registry.get(view_class_name, None) if view_class is None: raise PopupViewNotRegistered('Popup View {0} not registered'.format(view_class_name)) else: return view_class
def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) # Post function to handle Facebook messages
def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) # Post function to handle Telegram messages
def test_limit_ip(self): class RLView(RatelimitMixin, View): ratelimit_key = 'ip' ratelimit_method = ratelimit.ALL ratelimit_rate = '1/m' ratelimit_block = True rlview = RLView.as_view() req = rf.get('/') assert rlview(req), 'First request works.' with self.assertRaises(Ratelimited): rlview(req)
def test_block(self): class BlockedView(RatelimitMixin, View): ratelimit_group = 'cbv:block' ratelimit_key = 'ip' ratelimit_method = ratelimit.ALL ratelimit_rate = '1/m' ratelimit_block = True def get(self, request, *args, **kwargs): return request.limited class UnBlockedView(RatelimitMixin, View): ratelimit_group = 'cbv:block' ratelimit_key = 'ip' ratelimit_method = ratelimit.ALL ratelimit_rate = '1/m' ratelimit_block = False def get(self, request, *args, **kwargs): return request.limited blocked = BlockedView.as_view() unblocked = UnBlockedView.as_view() req = rf.get('/') assert not blocked(req), 'First request works.' with self.assertRaises(Ratelimited): blocked(req) assert unblocked(req), 'Request is limited but not blocked.'
def test_method(self): post = rf.post('/') get = rf.get('/') class LimitPostView(RatelimitMixin, View): ratelimit_group = 'cbv:method' ratelimit_key = 'ip' ratelimit_method = ['POST'] ratelimit_rate = '1/m' def post(self, request, *args, **kwargs): return request.limited get = post class LimitGetView(RatelimitMixin, View): ratelimit_group = 'cbv:method' ratelimit_key = 'ip' ratelimit_method = ['POST', 'GET'] ratelimit_rate = '1/m' def post(self, request, *args, **kwargs): return request.limited get = post limit_post = LimitPostView.as_view() limit_get = LimitGetView.as_view() assert not limit_post(post), 'Do not limit first POST.' assert limit_post(post), 'Limit second POST.' assert not limit_post(get), 'Do not limit GET.' assert limit_get(post), 'Limit first POST.' assert limit_get(get), 'Limit first GET.'
def test_method_decorator(self): class TestView(View): @ratelimit(key='ip', rate='1/m', block=False) def post(self, request): return request.limited view = TestView.as_view() req = rf.post('/') assert not view(req) assert view(req)
def get_view_name(view_cls, suffix=None): """ Given a view class, return a textual name to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_NAME_FUNCTION` setting. """ name = view_cls.__name__ name = formatting.remove_trailing_string(name, 'View') name = formatting.remove_trailing_string(name, 'ViewSet') name = formatting.camelcase_to_spaces(name) if suffix: name += ' ' + suffix return name
def _post(self, request): raise NotImplementedError("You have to define this method in children View class")
def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs)
def _handle_api_callback(self, request): """handle redirect from instagram when user denied access""" global HOST logger.debug("Dropbox handling get-request: " "identified as API callback") try: redirect_dropbox = HOST + "/dropbox/authenticate" access_token, userid, url_state = DropboxOAuth2Flow(APP_KEY, APP_SECRET, redirect_dropbox, request.session, "dropbox-auth-csrf-token" ).finish(request.GET) return self._save_user(access_token, userid, url_state, request) except DropboxOAuth2Flow.BadRequestException as e: logger.error("[Dropbox - View - auth-finish] BadRequestException") return self.error(request) except DropboxOAuth2Flow.BadStateException as e: return redirect(reverse("dropbox:connect")) except DropboxOAuth2Flow.CsrfException as e: logger.error("[Dropbox - View - auth-finish] ... CsrfException") return self.error(request) except DropboxOAuth2Flow.NotApprovedException as e: logger.error("[Dropbox - View - auth-finish] ... 403") return self.error(request) except DropboxOAuth2Flow.ProviderException as e: logger.error("[Dropbox - View - auth-finish] ... NotApprovedException") return self.error(request)
def _save_user(self, access_token, userid, url_state, request): dbx = dropbox.Dropbox(access_token) account = dbx.users_get_current_account() disk = dbx.users_get_space_usage() if disk.allocation.is_individual() is False: return self.error(request) init_dropbox_folder = dbx.files_list_folder(path='', recursive=True, include_media_info=True, include_deleted=True) # to convert the bytes to megabytes MEGA_BYTE = 1000000 used = (disk.used / MEGA_BYTE) allocated = (disk.allocation.get_individual().allocated / MEGA_BYTE) dropbox_account = DropboxAccount(user = request.user, access_token = access_token, cursor = init_dropbox_folder.cursor) dropbox_account.save() dropbox_user = DropboxUser(dropbox_account = dropbox_account, dropbox_userid = userid, display_name = account.name.display_name, email = account.email, profile_photo_url = account.profile_photo_url, disk_used = used, disk_allocated = allocated) dropbox_user.save() logger.debug('[Dropbox - View - auth-finish] \ DropboxUser added to user: {}'.format(request.user.username)) return self.success(request)
def get(self, request): logger.debug("DropBox handling GET webhook") if request.method == "GET": logger.debug('[Dropbox - View - dropbox_call_webhook] \ DropBox - send Hook-Test') return HttpResponse(request.GET.get('challenge'))
def post(self, request): """Receive a list of changed user IDs from Dropbox and process each.""" # Make sure this is a valid request from Dropbox logger.debug('[Dropbox - View - Webhook] received a webhook') signature = request.environ.get('HTTP_X_DROPBOX_SIGNATURE') try: request_body_size = int(request.environ.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 pass request_body = request.environ['wsgi.input'].read(request_body_size) request_hashed = hmac.new( APP_SECRET.encode("utf-8"), request_body, sha256).hexdigest() if not hmac.compare_digest(signature, request_hashed): error_url = '{}?status=error'.format(self.get_redirect(request)) return redirect(error_url) try: data = json.loads(request_body.decode('utf-8')) for user in data['delta']['users']: logger.debug('[Dropbox - View - webhook] \ firedTrigger for user with id:{}'.format(user)) tasks.fireTrigger(user) except json.decoder.JSONDecodeError: pass return HttpResponse()
def get(self, request): """ Handling GET method :param request: Request to View :return: rendered registration page """ return render(request, "register.html")
def get(self, request): """ :param request: Request to View :return: user profile page """ user = request.user data = {} data['AdviserUser'] = model_to_dict(AdviserUser.objects.get(user_id=user.id)) data['User'] = model_to_dict(User.objects.get(id=user.id)) return HttpResponse(json.dumps(data, default=self.datetime_handler))
def test_fallback_class_based_view(self): class OtherTestView(View): def get(self, request, *args, **kwargs): return HttpResponse('fallback cbv') view = TestView.as_view( flag_name=self.flag_name, condition=True, fallback=OtherTestView.as_view() ) response = view(self.request()) self.assertContains(response, 'fallback cbv')
def project_detail_view(): class FakeProjectDetailView(mixins.PhaseDispatchMixin, View): model = models.Project def get(self, request, *args, **kwargs): return HttpResponse('project_detail') return FakeProjectDetailView.as_view()
def get_permission_denied_message(self): logger.info("Access Denied - Cannot View") return "You do not have access to view this Lawn! Please go back, and create your own."
def index(request): logger.debug("Index View (homepage)") return render(request, "planner/index.html", {})
def clear_session_view(request): """ View that clears the session and restarts the user flow. @param request: the HTTP request """ request.session.flush() return redirect(build_view_url(request, PaymentMethodChoiceView.url_name))