def get_urls(self): original_urls = super(AdminViews, self).get_urls() added_urls = [] for link in self.admin_views: if hasattr(self, link[1]): view_func = getattr(self, link[1]) if len(link) == 3: # View requires permission view_func = permission_required(link[2], raise_exception=True)(view_func) added_urls.extend( patterns('', url(regex=r'%s' % link[1], name=link[1], view=self.admin_site.admin_view(view_func) ) ) ) self.local_view_names.append(link[0]) # Build URL from known info info = self.model._meta.app_label, self.model._meta.module_name self.output_urls.append(( 'view', link[0], "%s/%s/%s/%s" % (ADMIN_URL_PREFIX, info[0], info[1], link[1]), link[2] if len(link) == 3 else None, ) ) else: self.direct_links.append(link) self.output_urls.append(('url', link[0], link[1], link[2] if len(link) == 3 else None)) return added_urls + original_urls
def as_view(cls, **initkwargs): view = super(PermMixin, cls).as_view(**initkwargs) if cls.perms: view = permission_required(cls.perms, login_url="/403/")(view) return view
def edit_member(request, member_id): if not _check_access_permitted_for_member_key('toolkit.write', request, member_id): # Manually wrap this function in the standard 'permission_required' # decorator and call it to get the redirect to the login page: return permission_required('toolkit.write')(edit_member)(request, member_id) # (To elaborate: # permission_required('toolkit.write') # is the decorator used elsewhere. Writing: # permission_required('toolkit.write')(edit_member) # returns the function with the decorator applied, then # permission_required('toolkit.write')(edit_member)(request, member_id) # calls the wrapped function, passing in the arguments originaly supplied. # Capice? member = get_object_or_404(Member, id=member_id) context = {} if request.method == 'POST': form = MemberForm(request.POST, instance=member) if form.is_valid(): logger.info(u"Saving changes to member '{0}' (id: {1})".format(member.name, member.pk)) form.save() messages.add_message(request, messages.SUCCESS, u"Member {0} updated".format(member.number)) if request.user.has_perm('toolkit.write'): return HttpResponseRedirect(reverse("search-members")) else: form = MemberForm(instance=member) context = { 'member': member, 'form': form, } return render(request, 'form_member.html', context)
def unsubscribe_member(request, member_id): if not _check_access_permitted_for_member_key('toolkit.write', request, member_id): # Manually wrap this function in the standard 'permission_required' # decorator and call it to get the redirect to the login page: return permission_required('toolkit.write')(unsubscribe_member)( request, member_id) member = get_object_or_404(Member, id=member_id) if request.method == 'POST': # Default to unsubscribe action = request.POST.get('action', 'unsubscribe') confirm = request.POST.get('confirm', False) if confirm == "yes" and action in ('unsubscribe', 'subscribe'): member.mailout = (action == 'subscribe') member.save() logger.info(u"{0} member '{1}' (id: {2}) from mailing list" .format(action, member.name, member.pk)) messages.add_message(request, messages.SUCCESS, u"Member {0} {1}d".format( member.number, action)) action = 'unsubscribe' if member.mailout else 'subscribe' return render(request, 'form_member_edit_subs.html', {'member': member, 'action': action})
def get_urls(self): from django.conf.urls import url urlpatterns = [ url(r'^send/$', api.send, name='statsy.send'), url(r'^$', self.stats_view(views.dashboard), name='statsy.dashboard'), url(r'^get_stats/$', self.stats_view(views.get_stats), name='statsy.get_stats'), url(r'^custom/$', self.stats_view(views.custom), name='statsy.custom'), url(r'^today/$', self.stats_view(views.today), name='statsy.today'), ] url_map = dict() for view_name, (view, _, permission) in self._registry.items(): url_part = self._get_url_part(view_name) url_name = 'statsy.{0}'.format(view_name, url_part) stats_view = self.stats_view(view) if permission: stats_view = permission_required(permission)(stats_view) urlpatterns.append( url(r'^custom/{0}/'.format(url_part), stats_view, name=url_name) ) url_map[view_name] = url_name self._build_url_map(url_map) return urlpatterns
def events_permission_required(perm, login_url='/admin/login', raise_exception=False): """ Sobrescreve o metodo que exige login para acessar a view Usar com decorator sobre o metodo que desejar o login: @method_decorator(events_login_required) """ return permission_required(perm, login_url=login_url, raise_exception=raise_exception)
def get_urls(self): urls = super(RecebimentoAdmin, self).get_urls() my_urls = [ url(r'recebimentos_parcela/(?P<id_parcela>\d+)/$', self.admin_site.admin_view(retorna_recebimentos_parcela)), url(r'recebimentos_conta/(?P<id_conta>\d+)/$', self.admin_site.admin_view(retorna_recebimentos_conta)), url(r'efetiva_recebimento_parcela/(?P<id_parcela>\d+)/$', permission_required('contas_receber.add_recebimento')(EfetivaRecebimentoParcela.as_view())), ] return my_urls + urls
def _wrapped_view(request, *args, **kwargs): ct = ContentType.objects.get(model=kwargs['model']) app_label = ct.app_label model = ct.model perm = '%s.manage_%ss' % (app_label, model) redirect = '/permission/denied/' return permission_required(perm, redirect)(view_func)(request, *args, **kwargs)
def __init__(self, login_required=True, login_url=None, permission=None): self.module = self.__module__.split('.')[-2] if permission: self.view = permission_required(permission, login_url)(self.view) if login_required: self.view = lr(self.view, login_url) self.context = {} self.css, self.js = self.get_css_js()
def decorator(cls): if (not isinstance(cls, type) or not issubclass(cls, View)): raise ImproperlyConfigured( "require_authenticated_permission must be applied to subclasses of View class.") check_auth = method_decorator(login_required) check_perm = method_decorator(permission_required(permission, raise_exception=True)) cls.dispatch = check_auth(check_perm(cls.dispatch)) return cls
def _wrapped_view(request, *args, **kwargs): draft = get_object_or_404(ContentDraft, id=kwargs['id']) app_label = draft.content_type.app_label model = draft.content_type.model perm = '%s.manage_%ss' % (app_label, model) redirect = '/permission/denied/' return permission_required(perm, redirect)(view_func)(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): dispatch = super(AuthMixin, self).dispatch required_permissions = self.get_required_permissions(request) for required_permission in required_permissions: dispatch = permission_required(required_permission)(dispatch) return dispatch(request, *args, **kwargs)
def __call__(self, function): permission_req_wrapper = permission_required(self.permission)(function) def wrapper(request, *args, **kwargs): if request.META['REMOTE_ADDR'] in self.ip_addresses: return function(request, *args, **kwargs) else: return permission_req_wrapper(request, *args, **kwargs) return wrapper
def wrapper(cls): if not isinstance(cls, type) or not issubclass(cls, View): raise ImproperlyConfigured('{} class must be subclass of View class' .format(cls.__name__)) check_login = method_decorator(login_required) check_perms = method_decorator(permission_required(perms, raise_exception=True)) cls.dispatch = check_login(check_perms(cls.dispatch)) return cls
def dispatch(self, request, *args, **kwargs): if (self.permission_required is None or '.' not in self.permission_required): raise ImproperlyConfigured("PermissionRequiredMixin must have a " "permission_required attribute.") decorator = permission_required(self.permission_required, self.login_url, self.raise_exception) decorated_dispatch = decorator(super(PermissionRequiredMixin, self).dispatch) return decorated_dispatch(request, *args, **kwargs)
def get_seo_urlpattern(cls, model_klass, form_klass=None, template_name='manage/seo/seo.html'): """Prepare urlpattern for seo tab and give it a name based on the model name to be unique """ klass_name = cls.get_unique_klass_name(model_klass) view_obj = cls.as_view(form_klass=form_klass, model_klass=model_klass, template_name=template_name) # lfs.manage.seo.views return url(r'^manage-seo/%s/(?P<id>\d*)/$' % klass_name, permission_required("core.manage_shop")(view_obj), name='lfs_manage_%s_seo' % klass_name),
def permission_required_on_urlpatterns(*args, **kwargs): """ Same API as django.contrib.auth.decorators.permission_required But to be applied on urlpatterns instead of view e.g. permission_required_on_urlpatterns('user.is_helpdesk')(include('states.urls'))) """ return decorator_on_urlpatterns(permission_required(*args, **kwargs))
def get_urls(self): urls = super(PagamentoAdmin, self).get_urls() my_urls = [ url(r"pagamentos_parcela/(?P<id_parcela>\d+)/$", self.admin_site.admin_view(retorna_pagamentos_parcela)), url(r"pagamentos_conta/(?P<id_conta>\d+)/$", self.admin_site.admin_view(retorna_pagamentos_conta)), url( r"efetiva_pagamento_parcela/(?P<id_parcela>\d+)/$", permission_required("contas_pagar.add_pagamento")(EfetivaPagamentoParcela.as_view()), ), ] return my_urls + urls
def get_seo_urlpattern(cls, model_klass, form_klass=None, template_name='manage/seo/seo.html'): """Prepare urlpattern for seo tab and give it a name based on content type of the model """ ct = ContentType.objects.get_for_model(model_klass).pk view_obj = cls.as_view(form_klass=form_klass, model_klass=model_klass, template_name=template_name) return patterns('lfs.manage.seo.views', url(r'^manage-seo/%s/(?P<id>\d*)/$' % ct, permission_required("core.manage_shop")(view_obj), name='lfs_manage_%s_seo' % ct), )
def __init__(self, login_required=True,login_url=None, permission=None): self.module = self.__module__.split('.')[-2] #self.widgets = self.unique_list(map(operator.itemgetter(1), # sorted(Widget._registry[self.url], key=operator.itemgetter(0)) # ) # ) self.widgets = [] if permission: self.view = permission_required(permission,login_url)(self.view) if login_required: self.view = lr(self.view,login_url) self.context={} self.css, self.js = self.get_css_js()
def check_perms(user): if perm_check not in ALLOWED_CHECK: raise NotValidCheck( 'perm_check is not valid expected is "AND", ' ' "OR", "NOT" but found %s' % perm_check) if not perm_check == 'NOT': if not isinstance(perm, list): return permission_required( perm, login_url=login_url, raise_exception=raise_exception) else: if perm_check == 'OR': return check_or_perms(user, perm) elif perm_check == 'AND': return check_and_perms(user, perm) else: return check_not_perms(user, perm)
def get_seo_urlpattern(cls, model_klass, form_klass=None, template_name='manage/seo/seo.html'): """Prepare urlpattern for seo tab and give it a name based on content type of the model """ try: ct = ContentType.objects.get_for_model(model_klass).pk view_obj = cls.as_view(form_klass=form_klass, model_klass=model_klass, template_name=template_name) return patterns('lfs.manage.seo.views', url(r'^manage-seo/%s/(?P<id>\d*)/$' % ct, permission_required("core.manage_shop")(view_obj), name='lfs_manage_%s_seo' % ct), ) # starting from django 1.4.10 (or slightly less) seems that urlpatterns are loaded during syncdb # so we have to handle DatabaseError when ContentType table doesn't exist yet except DatabaseError as e: return []
def unsubscribe_member_right_now(request, member_id): if not _check_access_permitted_for_member_key('toolkit.write', request, member_id): return permission_required('toolkit.write')(unsubscribe_member)( request, member_id) member = get_object_or_404(Member, id=member_id) action = 'unsubscribe' member.mailout = False member.save() logger.info(u"{0} member '{1}' (id: {2}) from mailing list" .format(action, member.name, member.pk)) messages.add_message(request, messages.SUCCESS, u"Member {0} {1}d".format(member.number, action)) return render(request, 'form_member_edit_subs.html', {'member': member, 'action': action})
def opt_in(request, member_id): if not _check_access_permitted_for_member_key('toolkit.write', request, member_id): return permission_required('toolkit.write')(unsubscribe_member)( request, member_id) member = get_object_or_404(Member, id=member_id) if request.method == 'POST': # Default to opt-in action = request.POST.get('action', 'opt-in') confirm = request.POST.get('confirm', False) if confirm == "yes": if action == 'opt-in': member.gdpr_opt_in = timezone.now() messages.add_message(request, messages.SUCCESS, u"Thank you {0} for opting in to continue to receive our emails" .format(member.name) ) else: # opt-out member.gdpr_opt_in = None messages.add_message(request, messages.SUCCESS, (u"We are sorry to see you have opted out. " u"If you do not opt-in by 25 May 2018 " u"we will delete your membership from our records.") ) member.save() logger.info(u"Member '{0}' (id: {1}) <{2}>: {3} on {4}" .format(member.name, member.pk, member.email, action, member.gdpr_opt_in) ) action = 'opt-out' if member.gdpr_opt_in else 'opt-in' return render(request, 'form_member_edit_opt_in.html', {'member': member, 'action': action})
condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated)
2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.contrib.auth.views import LoginView, logout_then_login, PasswordResetView from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth import views as auth_views from .views import * urlpatterns = [ path('login/', LoginView.as_view(template_name='usuarios/login.html'), name='login' ), path('logout/',logout_then_login, name='logout'), path('',login_required(main_mage), name="main"), path('listausers/',permission_required('usuarios.usuarios')(login_required(lista_usuarios_view.as_view())), name='listausers'), path('addpermission/<int:pk>/',permission_required('usuarios.usuarios')(login_required(permisos_view.as_view())), name='addpermission'), path('createuser/',permission_required('usuarios.usuarios')(login_required(create_user_view.as_view())), name='createuser'), path('asignacion/<int:pk>/',permission_required('usuarios.usuarios')(login_required(asignar_evaluacion_view.as_view())), name='asignacion'), path('listadesig/<int:pk>/',permission_required('usuarios.usuarios')(login_required(lista_usuarios_designacion_view.as_view())), name='listadesig'), path('deleteasig/<int:pk>/',permission_required('usuarios.usuarios')(login_required(borrar_evaluacion_view.as_view())), name='deleteasig'), path('confgeneral',permission_required('usuarios.usuarios')(login_required(configuracion_general_view.as_view())),name='confgeneral'), ]
from django.urls import path from . import views from django.contrib.auth.decorators import permission_required, login_required app_name = 'user_centrum' urlpatterns = [ path('', views.Index.as_view(), name='index'), path('applications/', views.ApplicationList.as_view(), name='application-list'), path('applications/<int:pk>', views.ApplicationDetail.as_view(), name='application-detail'), path('applications/add', permission_required('user_centrum.add_application')( views.ApplicationCreate.as_view()), name='application-create'), path('applications/<int:pk>/edit', permission_required('user_centrum.change_application')( views.ApplicationUpdate.as_view()), name='application-update'), path('applications/<int:pk>/delete', permission_required('user_centrum.delete_application')( views.ApplicationDelete.as_view()), name='application-delete'), path('applications/<int:pk>/accept', permission_required('user_centrum.accept_application')( views.ApplicationAccept.as_view()), name='application-accept'), path('applications/<int:pk>/cancel', permission_required('user_centrum.cancel_application')(
assert (set(l.keys()) == keys) sorted_items = [sorted(l.items()) for l in to_merge] sorted_values = [zip(*l)[1] for l in sorted_items] return dict(zip(sorted(keys), zip(*sorted_values))) class ProfileList(generic.TemplateView): template_name = "profiler/profile_list.html" def get_context_data(self, **kwargs): context = super(ProfileList, self).get_context_data(**kwargs) context['profiles'] = get_storage().get_versions() return context profile_list = permission_required('profile')(ProfileList.as_view()) class ProfileKCacheGrind(generic.View): def get(self, request, version): storage = get_storage(version) data = merge([storage.get_time(), storage.get_count()]) self.function_locations = self._get_functions_locations(data) calls = list(self._get_calls(data)) last_times = list(self._get_last_times(data)) self.merged_calls = self._merge_duplicates(calls) self.last_times_merged = self._merge_duplicates(last_times) raport = self._get_raport() return http.HttpResponse(raport) def _merge_duplicates(self, calls):
class SetkaImagesView(View): @method_decorator(csrf_exempt) @method_decorator(permission_required('is_stuff', raise_exception=True)) def dispatch(self, request, *args, **kwargs): return super(SetkaImagesView, self).dispatch(request, *args, **kwargs) @staticmethod def get(request, *args, **kwargs): images = ImageDocument.objects.all().order_by('-id') data = [{ 'id': image.slug, 'name': image.name, 'url': request.build_absolute_uri(_build_image_url(image.slug)), 'thumbUrl': request.build_absolute_uri(_build_image_url(image.slug)), 'alt': image.alt if image.alt else '' } for image in images] return JsonResponse({'postimages': data}, status=200) @staticmethod def post(request, *args, **kwargs): temp = request.FILES['file'] name = temp.name slug = '{}.{}.{}'.format(slugify(name, max_length=50), '0', name.split('.')[-1]) # checking for copies existing = [x[0] for x in ImageDocument.objects.values_list('slug')] copy_count = 1 while slug in existing: slug_elems = slug.split('.') slug_elems[-2] = '.' + str(copy_count) slug = '.'.join(slug_elems) copy_count += 1 try: ImageDocument(name=name, slug=slug).save() with default_storage.open(os.path.join('images', slug), 'wb+') as dest: for chunk in temp.chunks(): dest.write(chunk) return JsonResponse({'id': slug, 'url': _build_image_url(slug)}) except IntegrityError: return JsonResponse({}, status=500) @staticmethod def delete(request, *args, **kwargs): slug = request.path.split('/')[-1] try: ImageDocument.objects.get(slug=slug).delete() except ImageDocument.DoesNotExist: return JsonResponse({}, status=404) path = os.path.join('images', slug) if default_storage.exists(path): default_storage.delete(path) return JsonResponse({}, status=200) @staticmethod def put(request, *args, **kwargs): slug = request.path.split('/')[-1] try: image = ImageDocument.objects.get(slug=slug) except ImageDocument.DoesNotExist: return JsonResponse({}, status=404) data = json.loads(request.body) if 'alt' in data: image.alt = data['alt'] if 'name' in data: image.name = data['name'] image.save() return JsonResponse({}, status=200)
"""URL definitions for accounts app.""" # pylint: disable=no-value-for-parameter,invalid-name from django.conf.urls import patterns, url from django.contrib.auth.decorators import permission_required from open_connect.accounts import views from open_connect.connectmessages.views import DirectMessageCreateView urlpatterns = patterns( 'accounts.views', url(r'^(?P<user_uuid>[\d\w-]+)/update/$', views.UserUpdateView.as_view(), name='update_user'), url(r'^(?P<user_uuid>[\d\w-]+)/permissions/$', permission_required('accounts.can_modify_permissions')( views.UpdateUserPermissionView.as_view(), ), name='update_user_permissions'), url(r'^(?P<pk>\d+)/message/$', DirectMessageCreateView.as_view(), name='message_user'), url(r'^(?P<user_uuid>[\d\w-]+)/ban/$', permission_required('accounts.can_ban')(views.BanUserView.as_view(), ), name='ban_user'), url(r'^(?P<user_uuid>[\d\w-]+)/unban/$', permission_required('accounts.can_unban')( views.UnBanUserView.as_view(), ), name='unban_user'), url(r'^profile/$', views.UserProfileRedirectView.as_view(), name='user_profile'), url(r'^invites/create/$',
from webcomic_site.views import AjaxableResponseMixin, UserResponseMixin, OnlyAuthorOrSuperuserAccessMixin from .models import Genre, Comic, ComicChapter, ChapterImage # Create your views here. def genre_detail(request, slug): genre = get_object_or_404(Genre, slug=slug) context = { 'genre': genre, } return render(request, 'genre/detail.html', context=context) # check https://docs.djangoproject.com/en/2.1/topics/class-based-views/intro/ for decorating the class @method_decorator(login_required, name='dispatch') @method_decorator(permission_required('comic.add_comic', raise_exception=True), name='dispatch') class ComicCreateView(SuccessMessageMixin, AjaxableResponseMixin, CreateView): model = Comic fields = ['title', 'description', 'genre'] template_name = 'comic/create.html' success_message = 'Congratulation! You have created a new comic.' def get_success_url(self): return reverse('comic_detail', args=[self.object.slug]) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def render_to_response(self, context, **response_kwargs):
from django.conf.urls import patterns, url from schoolpage.views import SchoolpageListView, SchoolpageCreateView, SchoolpageUpdateView from django.contrib.auth.decorators import permission_required urlpatterns=patterns('', url(r'^$', SchoolpageListView.as_view(), name='schoolpage-list-view'), url(r'^add/$', permission_required('classlists.is_kksastaff', login_url='/registration/login/')(SchoolpageCreateView.as_view())), url(r'^modify/(?P<pk>\d+)/$', permission_required('classlists.is_kksastaff', login_url='/registration/login/')(SchoolpageUpdateView.as_view())), )
class ProjectModuleAddView(View): def __init__(self): self.context = {} @method_decorator(login_required) @method_decorator( permission_required("cmdb.add_projectmodule", raise_exception=True)) def get(self, request, *args, **kwargs): projectmodule_add_form = ProjectModuleAddForm() self.context = {"projectmodule_add_form": projectmodule_add_form} return render(request, "cmdb/projectmodule/projectmodule_add.html", self.context) @method_decorator(login_required) @method_decorator( permission_required("cmdb.add_projectmodule", raise_exception=True)) def post(self, request, *args, **kwargs): projectmodule_add_form = ProjectModuleAddForm(request.POST) if projectmodule_add_form.is_valid(): module_name = request.POST["module_name"] module_desc = request.POST["module_desc"] module_service_type = request.POST["service_type"] module_git_url = request.POST["git_url"] module_project_id = request.POST["project"] module_cluster_list = request.POST.getlist("cluster") if module_project_id == "": module_project = None else: module_project = Project.objects.get(pk=module_project_id) projectmodule = ProjectModule(module_name=module_name, module_desc=module_desc, service_type=module_service_type, git_url=module_git_url, project=module_project) projectmodule.save() for c in module_cluster_list: projectmodule.cluster.add(c) projectmodule.save() name = module_project.name.split("-")[0] yaml_dict = {"projectmodule": module_name, "project": name} create_state_dir(module_name) cwd = os.path.dirname(os.path.abspath(__file__)) init_tpl = os.path.join( os.path.join(os.path.dirname(os.path.dirname(cwd)), "saltjob"), "init.json.j2") install_tpl = os.path.join( os.path.join(os.path.dirname(os.path.dirname(cwd)), "saltjob"), "install.json.j2") init_file = os.path.join( os.path.join( os.path.join(os.path.dirname(os.path.dirname(cwd)), "saltjob"), module_name), "init.sls") install_file = os.path.join( os.path.join( os.path.join(os.path.dirname(os.path.dirname(cwd)), "saltjob"), module_name), "install.sls") write_yaml_file(yaml_dict, init_tpl, init_file) write_yaml_file(yaml_dict, install_tpl, install_file) return HttpResponsePermanentRedirect(reverse("projectmodule")) else: self.context = { "projectmodule_add_form": projectmodule_add_form, "project_add_errors": projectmodule_add_form.errors } return render(request, "cmdb/projectmodule/projectmodule_add.html", self.context)
signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) return next_redirect(request.POST.copy(), next, delete_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/delete.html', {'comment': comment, "next": next}, template.RequestContext(request) ) delete = permission_required("comments.can_moderate")(delete) #@permission_required("comments.can_moderate") def approve(request, comment_id, next=None): """ Approve a comment (that is, mark it as public and non-removed). Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: `comments/approve.html`, Context: comment the `comments.comment` object for approval """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST
from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import views, sales from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', permission_required('customer.view_customer', login_url='account_login')(views.users), name='customers'), url(r'^add/$', permission_required('customer.add_customer', login_url='account_login')(views.user_add), name='customer-add'), url(r'^customer_process/$', views.user_process, name='customer_process'), url(r'^d/(?P<pk>[0-9]+)/$', views.user_detail, name='customer-detail'), url(r'^sd/(?P<pk>[0-9]+)/$', views.sales_detail, name='customer-sales-detail'), url(r'^cst/pdf/detail/(?P<pk>[0-9]+)/$', sales.sales_detail, name='cust-pdf-sale-detail'), url(r'^std/(?P<pk>[0-9]+)/(?P<ck>[0-9]+)/$', views.sales_items_detail, name='customer-sales-items-detail'), url(r'^delete/(?P<pk>[0-9]+)/$', permission_required('customer.delete_customer', login_url='account_login')(views.user_delete), name='customer-delete'),
from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import views, subcategories urlpatterns = [ url(r'^$', permission_required('product.view_category', login_url='not_found') (views.category_list), name='category-list'), url(r'^(?P<root_pk>[0-9]+)/$', permission_required('product.view_category', login_url='not_found') (views.category_list), name='category-list'), url(r'^paginate/$', views.paginate_category, name='category-paginate'), url(r'^paginate/(?P<root_pk>[0-9]+)/$', views.paginate_category, name='category-paginate'), url(r'^search/category/$', views.category_search, name='category-search'), url(r'^search/paginate/(?P<root_pk>[0-9]+)/$', views.category_search, name='category-search'), url(r'^add/$', permission_required('product.add_category', login_url='not_found') (views.category_create), name='category-add'), url(r'^add/cat32/$', permission_required('product.add_category', login_url='not_found') (views.category_create32), name='category-add32'), url(r'^(?P<root_pk>[0-9]+)/add/$', permission_required('product.add_category', login_url='not_found') (views.category_create), name='category-add'), url(r'^(?P<root_pk>[0-9]+)/edit/$', permission_required('product.change_category', login_url='not_found') (views.category_edit), name='category-edit'), url(r'^(?P<pk>[0-9]+)/delete/$', permission_required('product.delete_category', login_url='not_found') (views.category_delete), name='category-delete'),
ignore_conflicts=True) tags = Tag.objects.in_bulk(tags, field_name='name') obj = form.save(commit=False) obj.author_id = self.request.user.id obj.save() obj.collections.set(form.cleaned_data['collections']) obj.tags.add(*[tag.id for tag in tags.values()]) return HttpResponseRedirect(self.get_success_url()) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs @method_decorator(permission_required('image_handling.add_image'), name='dispatch') class ImageCreateFormView(ImageBaseFormView, CreateView, LoginRequiredMixin): form_class = ImageCreateForm template_name = 'image_upload.html' extra_context = {'title': 'Image upload'} def get_success_url(self): return reverse('author_detail_image', args=[self.request.user.id]) @method_decorator(permission_required('image_handling.change_image'), name='dispatch') class ImageUpdateFormView(ImageBaseFormView, UpdateView, LoginRequiredMixin): model = Image form_class = ImageUpdateForm
return redirect(return_url) return render( request, 'ems/user/timesheet/change.html', { 'action': action, 'timesheet_user': user, 'from_date': from_date, 'to_date': to_date - relativedelta(days=1), 'return_url': return_url, 'hours': hours, }) # Project timesheets @cbv_decorator(permission_required('entries.view_project_timesheet')) class ProjectTimesheet(DetailView): template_name = 'ems/project/timesheet.html' model = Project context_object_name = 'project' pk_url_kwarg = 'project_id' def get(self, *args, **kwargs): if 'csv' in self.request.GET: request_get = self.request.GET.copy() request_get.pop('csv') return_url = reverse('view_project_timesheet_csv', args=(self.get_object().pk, )) return_url += '?%s' % urlencode(request_get) return redirect(return_url) return super(ProjectTimesheet, self).get(*args, **kwargs)
mimetype = "application/pdf" def get_object(self, queryset=None): try: obj = Fight.objects.get( round__tournament=self.request.user.profile.tournament, id=self.kwargs['fight_id']).pdf_jury_feedback if not obj.status in [Pdf.SUCCESS, Pdf.UPLOAD]: raise Pdf.DoesNotExist("File not yet available") return obj.file except: raise Pdf.DoesNotExist("File does not exist") @method_decorator(login_required, name='dispatch') @method_decorator(permission_required('jury.delete_all_jurorsessions', raise_exception=False), name='dispatch') class JuryClean(ConfirmedDeleteView): def get_objects(self, request, *args, **kwargs): trn = request.user.profile.tournament return JurorSession.objects.filter( fight__round__tournament=trn, fight__round__order__gt=kwargs["fix_rounds"]) def get_redirection(self, request, *args, **kwargs): next = request.GET.get('next', None) if next: return redirect("jury:assign_preview", id=next) else: return redirect("jury:assign")
from django.http import JsonResponse from django.contrib.auth import get_user_model from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import render, get_object_or_404, redirect, HttpResponse from lyche import forms as lyche_forms from lyche import models as lyche_models User = get_user_model() # End: imports ----------------------------------------------------------------- perms_example = [ login_required, permission_required('lyche.view_examplemodel', login_url='lyche:forbidden') ] @method_decorator(perms_example, name='dispatch') class AllExampleModels(View): template = 'lyche/all_examplemodels.html' def get(self, request): examplemodels = lyche_models.ExampleModel.objects.all() return render(request, self.template, { 'examplemodels': examplemodels, }) class AddExampleModel(main_views.GenericAddModel):
from django.contrib.auth.decorators import permission_required from django.urls import path, include from . import views app_name = 'employee' employment = [ path('', views.EmploymentListEmployee.as_view(), name='list'), path('create/', permission_required('is_superuser')(views.EmploymentCreate.as_view()), name='create'), path('<int:pk>/', views.EmploymentDetail.as_view(), name='detail'), path('<int:pk>/update/', permission_required('is_superuser')(views.EmploymentUpdate.as_view()), name='update'), path('<int:pk>/delete/', permission_required('is_superuser')(views.EmploymentDelete.as_view()), name='delete'), ] employee = [ path('', views.EmployeeList.as_view(), name='list'), path('create/', permission_required('is_superuser')(views.EmployeeCreate.as_view()), name='create'), path('<slug:slug>/', views.EmployeeDetail.as_view(), name='detail'), path('<slug:slug>/update/', permission_required('is_superuser')(views.EmployeeUpdate.as_view()), name='update'), path('<slug:slug>/delete/', permission_required('is_superuser')(views.EmployeeDelete.as_view()), name='delete'), path('<slug:slug>/employment/', include((employment, 'employment'))), ] urlpatterns = [ path('employment/', include(([path('', views.EmploymentList.as_view(), name='list'), ], 'employment'))), path('', include((employee, 'employee'))), ]
from django.core.paginator import Paginator from django.db import transaction from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.http import require_POST from bookwyrm import forms, models from bookwyrm.settings import PAGE_LENGTH # pylint: disable= no-self-use @method_decorator(login_required, name="dispatch") @method_decorator( permission_required("bookwyrm.control_federation", raise_exception=True), name="dispatch", ) class Federation(View): """what servers do we federate with""" def get(self, request): """list of servers""" servers = models.FederatedServer.objects sort = request.GET.get("sort") sort_fields = ["created_date", "application_type", "server_name"] if not sort in sort_fields + ["-{:s}".format(f) for f in sort_fields]: sort = "created_date" servers = servers.order_by(sort) paginated = Paginator(servers, PAGE_LENGTH)
from django.contrib.auth.decorators import permission_required from django.utils.decorators import method_decorator from hostlookup_abstract.views import BaseHostLookupView from .utils import host_lookup @method_decorator(permission_required("hostlookup_netdisco.can_view_module", raise_exception=True), name='dispatch') class HostLookupView(BaseHostLookupView): def host_lookup(self): q = self.request.GET.get('q', '') return host_lookup(q)
class QuizMarkerMixin(object): @method_decorator(login_required) @method_decorator(permission_required('quiz.view_sittings')) def dispatch(self, *args, **kwargs): return super(QuizMarkerMixin, self).dispatch(*args, **kwargs)
from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import api from . import views, products, subcategory_products urlpatterns = [ url(r'^$', permission_required('product.view_product', login_url='not_found')(products.view), name='product-list'), url(r'^list-paginate/$', products.paginate, name='product-list-paginate'), url(r'^list/search/$', products.search, name='product-list-search'), url(r'^(?P<pk>[0-9]+)/update/$', permission_required('product.change_product', login_url='not_found')(views.product_edit), name='product-update'), url(r'^(?P<pk>[0-9]+)/update/(?P<name>[\w\-]+)$', permission_required('product.change_product', login_url='not_found')(views.product_edit), name='product-update'), url(r'^(?P<pk>[0-9]+)/delete/$', permission_required('product.delete_product', login_url='not_found')(views.product_delete), name='product-delete'), url(r'^add/(?P<class_pk>[0-9]+)/$', permission_required('product.add_product', login_url='not_found')(views.product_create), name='product-add'), url(r'^add/$', permission_required('product.add_product', login_url='not_found')(views.product_create),
import django_tables2 as tables from django_tables2.utils import A from jsignature.utils import draw_signature from django.forms.models import inlineformset_factory import csv # Create your views here. class Asset_Create(CreateView): form_class = AssetForm template_name = "hr/generic_form.html" success_url = "/assets/asset-list.html" assetcreate = permission_required('asset_access')(Asset_Create.as_view()) class Asset_View(DetailView): model = Asset template_name = 'assets/asset_view.html' def get_context_data(self, **kwargs): ctx = super(Asset_View, self).get_context_data(**kwargs) pk = self.kwargs['pk'] checks = Check.objects.filter(asset=pk) ctx['checks'] = checks return ctx assetview = permission_required('asset_access')(Asset_View.as_view())
test_plan.emailing.notify_on_case_update = form.cleaned_data[ 'notify_on_case_update'] test_plan.emailing.auto_to_plan_author = form.cleaned_data[ 'auto_to_plan_author'] test_plan.emailing.auto_to_case_owner = form.cleaned_data[ 'auto_to_case_owner'] test_plan.emailing.auto_to_case_default_tester = form.cleaned_data[ 'auto_to_case_default_tester'] test_plan.emailing.save() # _____________________________________________________________________________ # view functons @method_decorator(permission_required('testplans.add_testplan'), name='dispatch') class NewTestPlanView(View): template_name = 'testplans/mutable.html' def get(self, request): form = NewPlanForm() context_data = {'form': form} return render(request, self.template_name, context_data) def post(self, request): form = NewPlanForm(request.POST) form.populate(product_id=request.POST.get('product'))
class QuickEntry(View): """ View handling the quick post of a short Entry. """ @method_decorator(permission_required('events.add_entry')) def dispatch(self, *args, **kwargs): """ Decorate the view dispatcher with permission_required. """ return super(QuickEntry, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): """ GET only do a redirection to the admin for adding and entry. """ return redirect('admin:zinnia_entry_add') def post(self, request, *args, **kwargs): """ Handle the datas for posting a quick entry, and redirect to the admin in case of error or to the entry's page in case of success. """ data = { 'title': request.POST.get('title'), 'slug': slugify(request.POST.get('title')), 'status': DRAFT if 'save_draft' in request.POST else PUBLISHED, 'sites': [Site.objects.get_current().pk], 'authors': [request.user.pk], 'content_template': 'events/_entry_detail.html', 'detail_template': 'entry_detail.html', 'creation_date': timezone.now(), 'last_update': timezone.now(), 'content': request.POST.get('content'), 'tags': request.POST.get('tags') } form = QuickEntryForm(data) if form.is_valid(): form.instance.content = self.htmlize(form.cleaned_data['content']) entry = form.save() return redirect(entry) data = { 'title': smart_str(request.POST.get('title', '')), 'content': smart_str(self.htmlize(request.POST.get('content', ''))), 'tags': smart_str(request.POST.get('tags', '')), 'slug': slugify(request.POST.get('title', '')), 'authors': request.user.pk, 'sites': Site.objects.get_current().pk } return redirect('%s?%s' % (reverse('admin:zinnia_entry_add'), urlencode(data))) def htmlize(self, content): """ Convert to HTML the content if the MARKUP_LANGUAGE is set to HTML to optimize the rendering and avoid ugly effect in WYMEditor. """ if MARKUP_LANGUAGE == 'html': return linebreaks(content) return content
ArticleDetailView.as_view(), name="magazine-article-detail"), url("^article/list%s$" % _slash, ArticleListView.as_view(), name="magazine-article-list"), url("^article/list/(?P<keyword>.*)%s$" % _slash, ArticleListView.as_view(), name="magazine-article-list"), url("^topic/detail/(?P<slug>.*)%s$" % _slash, TopicDetailView.as_view(), name='topic-detail'), url("^object-autocomplete/$", ObjectAutocomplete.as_view(), name='object-autocomplete'), url("^dynamic-content-article/$", DynamicContentArticleView.as_view(), name='dynamic-content-article'), url("^article-event-list/$", ArticleEventView.as_view(), name='article-event-list'), url('^team/(?P<slug>.*)/article-event-list/$', ArticleEventTeamView.as_view(), name='article-event-team-list'), url( "^dynamic-content-magazine/$", permission_required('organization_magazine.change_magazine')( DynamicContentMagazineContentView.as_view()), # noqa: E501 name='dynamic-content-magazine'), url("^magazine/$", MagazineDetailView.as_view(), name='magazine'), ]
user = request.user if IS_CONTRACTOR.enabled(user.username) or user.is_superuser: return view_func(request, *args, **kwargs) else: return HttpResponseRedirect(reverse("no_permissions")) return _inner # Parallel to what we did with login_and_domain_required, above domain_admin_required = domain_admin_required_ex() cls_domain_admin_required = cls_to_view(additional_decorator=domain_admin_required) ######################################################################################################## # couldn't figure how to call reverse, so login_url is the actual url require_superuser = permission_required("is_superuser", login_url='/no_permissions/') cls_require_superusers = cls_to_view(additional_decorator=require_superuser) cls_require_superuser_or_contractor = cls_to_view(additional_decorator=require_superuser_or_contractor) def check_domain_migration(view_func): def wrapped_view(request, domain, *args, **kwargs): if DATA_MIGRATION.enabled(domain): return HttpResponse('Service Temporarily Unavailable', content_type='text/plain', status=503) return view_func(request, domain, *args, **kwargs) wrapped_view.domain_migration_handled = True return wraps(view_func)(wrapped_view)
class PermissionAddView(LoginRequiredMixin, View): '''独立templateview template_name = "permission_add.html" def get_context_data(self, **kwargs): context = super(PermissionAddView, self).get_context_data(**kwargs) contentType_objs = ContentType.objects.values('id', 'app_label', 'model') context['contenttypes'] = list(contentType_objs) return context 重写post方法引入form表单验证 def post(self, request): content_type_id = request.POST.get('content_type', None) codename = request.POST.get('codename', None) name = request.POST.get('name', None) #content_type = ContentType.objects.get_for_model() if not codename or codename.find(" ") >= 0: msg = "codename 不合法" return redirect("error", next="permission_add", msg=msg) try: content_type = ContentType.objects.get(pk=content_type_id) except ContentType.DoseNotExist: return redirect("error", next='permission_add', msg='模型不存在') try: #Permission.objects.create(codename=codename, name=name, content_type_id=content_type_id) Permission.objects.create(codename=codename, name=name, content_type=content_type) return redirect("success", next="permission_list") except Exception as e: print(e) msg = "添加权限出错" return redirect("error", next="permission_add", msg=msg) ''' @method_decorator(permission_required('auth.add_permission')) def post(self, request): permission_form = CreatePermissionForm(request.POST) if permission_form.is_valid(): permission = Permission(**permission_form.cleaned_data) try: permission.save() return redirect('success', next='permission_list') except Exception as e: return redirect('error', next='permission_add', msg=e.args) else: return redirect('error', next='permission_add', msg=json.dumps(json.load(permission_form.errors.as_json()), ensure_ascii=False)) def get(self, request): response = {} if request.user.has_perm('auth.view_permission'): permission_id = request.GET.get('id', None) if permission_id: try: permission_obj = Permission.objects.get(id=permission_id) response['status'] = 0 response['permission_name'] = permission_obj.name return JsonResponse(response) except: response['status'] = 1 response['errmsg'] = '获取权限内容出错' GetLogger().get_logger().error(traceback.format_exc()) return JsonResponse(response) else: response['status'] = 1 response['errmsg'] = '权限ip为空' return JsonResponse(response) else: response['status'] = 1 response['errmsg'] = '没有查看权限的权限' return JsonResponse(response) def patch(self, request): response = {} if request.user.has_perm('auth.change_permission'): permission_form = UpdatePermissionNameForm(QueryDict(request.body)) if permission_form.is_valid(): permission_name = permission_form.cleaned_data.get('name') permission_id = permission_form.cleaned_data.get('id') try: permission_obj = Permission.objects.get(id=permission_id) permission_obj.name = permission_name permission_obj.save() response['status'] = 0 return JsonResponse(response) except: GetLogger().get_logger().error(traceback.format_exc()) response['status'] = 1 response['errmsg'] = '更改permission name 出错' return JsonResponse(response) else: response['status'] = 1 response['errmsg'] = '缺少数据' return JsonResponse(response) else: response['status'] = 1 response['errmsg'] = '没有修改权限名的权限' return JsonResponse(response)
print(form.errors) return redirect(reverse('admin:login')) def AdminLogout(request): logout(request) return redirect(reverse('admin:login')) """ 管理员主页面 """ @method_decorator(login_required(login_url='admin:login'), name='dispatch') @method_decorator(permission_required('add_logentry', login_url='admin:login'), name='dispatch') class AdminIndexView(View): def get(self, request, *args, **kwargs): return render(request, 'admin_home.html') """ 管理员商品页面 """ @method_decorator(login_required(login_url='admin:login'), name='dispatch') @method_decorator(permission_required('add_logentry', login_url='admin:login'), name='dispatch') class AdminCommodityListView(ListView):
urlpatterns = patterns('', # Examples: (r'^$', 'core.views.index'), (r'^home$', 'core.views.home'), (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'public/login.html'}), (r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/'}), (r'^cadastros$', 'core.views.cadastro'), url(r'^accounts/', include('django.contrib.auth.urls')), (r'^mudar_pwd$', 'core.views.pass_change'), (r'home$', 'django.contrib.auth.views.password_change_done', {'template_name' : 'private/home.html'}), (r'^professor$', 'core.views.professor'), (r'^professor/list$', permission_required("core.professor",login_url="/home")(ListView.as_view(model=Professor, template_name="private/professor/list.html"))), (r'^professor/create$', 'core.views.criar_professor'), (r'^professor/detail/(?P<pk>\d+)$', DetailView.as_view(model=Professor, template_name='private/professor/professor.html')), (r'^aluno$', 'core.views.aluno'), (r'^aluno/list$', permission_required("core.professor",login_url="/home")(ListView.as_view(model=Aluno, template_name="private/aluno/list.html"))), (r'^aluno/create$', 'core.views.criar_aluno'), (r'^aluno/create_m$', 'core.views.criar_alunos'), (r'^aluno/detail/(?P<pk>\d+)$', DetailView.as_view(model=Aluno, template_name='private/aluno/aluno.html')), (r'^grupo$', 'core.views.grupo'), (r'^grupo/list$', permission_required("core.professor",login_url="/home")(ListView.as_view(model=Grupo, template_name="private/disciplina/list.html"))), (r'^grupo/create$', 'core.views.criar_grupo'), (r'^grupo/detail/(?P<pk>\d+)$', 'core.views.show_grupo'), (r'^grupo/add/(?P<pk>\d+)$', 'core.views.adicionar_alunos_grupo'),
# Ajax urls url(r'^ajax/keyword/(?P<prefix>.*)$', signbank.dictionary.views.keyword_value_list), url(r'^ajax/tags/$', signbank.dictionary.tagviews.taglist_json), url(r'^ajax/gloss/(?P<prefix>.*)$', signbank.dictionary.adminviews.gloss_ajax_complete, name='gloss_complete'), url(r'^ajax/handshape/(?P<prefix>.*)$', signbank.dictionary.adminviews.handshape_ajax_complete, name='handshape_complete'), url(r'^ajax/morph/(?P<prefix>.*)$', signbank.dictionary.adminviews.morph_ajax_complete, name='morph_complete'), url(r'^ajax/user/(?P<prefix>.*)$', permission_required('dictionary.change_gloss')( signbank.dictionary.adminviews.user_ajax_complete), name='user_complete'), url(r'^ajax/searchresults/$', signbank.dictionary.adminviews.gloss_ajax_search_results, name='ajax_search_results'), url(r'^ajax/handshapesearchresults/$', signbank.dictionary.adminviews.handshape_ajax_search_results, name='handshape_ajax_search_results'), url(r'^missingvideo.html$', signbank.dictionary.views.missing_video_view), url( r'^import_images/$', permission_required('dictionary.change_gloss')( signbank.dictionary.views.import_media), {'video': False}), url( r'^import_videos/$', permission_required('dictionary.change_gloss')(
return qs def get_context_data(self, **kwargs): context = super(NewsListView, self).get_context_data(**kwargs) tags = self.get_tags() if tags: context['news_tags'] = tags context['news_year'] = getattr(self, 'kwargs', {}).get('year', None) context['news_month'] = getattr(self, 'kwargs', {}).get('month', None) context['news_day'] = getattr(self, 'kwargs', {}).get('day', None) return context item_list = NewsListView.as_view(paginate_by=15) upcoming_item_list = permission_required('newsy.change_newsitem')( NewsListView.as_view(published=False, paginate_by=15)) def item_view(request, year, month, day, slug): try: page = NewsItem.objects.get(publication_date__year=year, publication_date__month=month, publication_date__day=day, slug=slug) except NewsItem.MultipleObjectsReturned: raise Http404() except NewsItem.DoesNotExist: try: page = NewsItem.objects.get(slug=slug) return HttpResponseRedirect(page.get_absolute_url()) except NewsItem.DoesNotExist, NewsItem.MultipleObjectsReturned: raise Http404()
from dataclasses import asdict from django.utils.decorators import method_decorator from django.contrib.auth.decorators import permission_required from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi from .serializers import HostLookupResponseSerializer from hostlookup_abstract.utils import HostLookupResult @method_decorator(permission_required( 'example_hostlookup_dummy.can_view_module', raise_exception=True, ), name='dispatch') class BaseHostView(ABC, APIView): @abstractmethod def host_lookup(self, request, q='') -> Iterable[HostLookupResult]: return NotImplemented @swagger_auto_schema( manual_parameters=[ openapi.Parameter('q', openapi.IN_QUERY, description='Host lookup query term.', type=openapi.TYPE_STRING), ], responses={
def permiso_admin(fn): return permission_required("is_superuser")(fn)
url(r'^sistema/core/cep/', include(CepCrud.get_urls())), url(r'^sistema/core/regiaomunicipal/', include(RegiaoMunicipalCrud.get_urls())), url(r'^sistema/core/distrito/', include(DistritoCrud.get_urls())), url(r'^sistema/core/bairro/', include(BairroCrud.get_urls())), url(r'^sistema/core/tipologradouro/', include(TipoLogradouroCrud.get_urls())), url(r'^sistema/core/logradouro/', include(LogradouroCrud.get_urls())), url(r'^sistema/core/trecho/', include(TrechoCrud.get_urls())), url(r'^sistema/usuario/', include(UserCrud.get_urls())), url(r'^sistema/core/impressoenderecamento/', include(ImpressoEnderecamentoCrud.get_urls())), #url(r'^sistema/parlamentar/partido/', include(PartidoCrud.get_urls())), url(r'^sistema/$', permission_required( 'core.menu_tabelas_auxiliares', login_url='cmj.core:login')( TemplateView.as_view(template_name='cmj_sistema.html')), name="tabelas_auxiliares"), url(r'^sistema$', permission_required( 'core.menu_tabelas_auxiliares', login_url='cmj.core:login')( TemplateView.as_view(template_name='cmj_sistema.html')), name="tabelas_auxiliares"), ]
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import permission_required from django.conf.urls import patterns from django.conf.urls import url from server.views import EditView from server.views import ModerateView from server.views import ReportView from server.views import AjaxServerResendView from server.views import AjaxServerCreateView from server.views import AjaxServerDeleteView from server.views import AjaxServerModerateView from server.views import AjaxServerResubmitView from server.views import AjaxServerUpdateView urlpatterns = patterns( 'server.views', url(r'^$', login_required(EditView.as_view()), name='server'), url(r'^moderate/$', permission_required('server.moderate')(ModerateView.as_view()), name='server_moderation'), url(r'^ajax/$', AjaxServerCreateView.as_view(), name='server_create'), url(r'^ajax/delete/(?P<pk>\w+)/$', AjaxServerDeleteView.as_view(), name='server_delete'), url(r'^ajax/moderate/(?P<pk>\w+)/$', AjaxServerModerateView.as_view(), name='server_moderate'), url(r'^ajax/report/(?P<pk>\w+)$', ReportView.as_view(), name='server_report'), url(r'^ajax/resend/(?P<pk>\w+)$', AjaxServerResendView.as_view(), name='server_resend'), url(r'^ajax/resubmit/(?P<pk>\w+)$', AjaxServerResubmitView.as_view(), name='server_resubmit'), url(r'^ajax/update/(?P<pk>\w+)/$', AjaxServerUpdateView.as_view(), name='server_update'), )
from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # paymentoption urls url(r'^$', permission_required('sale.view_table', login_url='account_login') (views.list), name='table-list'), url(r'^add/$', permission_required('sale.add_paymentoption', login_url='account_login') (views.add), name='table-add'), url(r'^delete/(?P<pk>[0-9]+)/$', permission_required('sale.delete_paymentoption', login_url='account_login') (views.delete), name='table-delete'), url(r'^detail/(?P<pk>[0-9]+)/$', views.detail, name='table-detail'), url(r'^update/(?P<pk>[0-9]+)/$', views.edit, name='update-table'), url( r'^search/$', views.searchs, name = 'table-search' ), url(r'^paginate/', views.paginate, name='table_paginate'), ] if settings.DEBUG: # urlpatterns += [ url(r'^static/(?P<path>.*)$', serve)] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)