Best Python code snippet using Kiwi_python
selector.py
Source:selector.py  
1from plone.app.i18n.locales.browser.selector import LanguageSelector2from plone.app.layout.navigation.interfaces import INavigationRoot3from zope.component import getMultiAdapter4from AccessControl.SecurityManagement import getSecurityManager5from Acquisition import aq_chain6from Acquisition import aq_inner7from Products.CMFCore.interfaces import ISiteRoot8from ZTUtils import make_query9from Products.LinguaPlone.interfaces import ITranslatable10class TranslatableLanguageSelector(LanguageSelector):11    """Language selector for translatable content.12    """13    set_language = True14    def available(self):15        if self.tool is not None:16            selector = self.tool.showSelector()17            languages = len(self.tool.getSupportedLanguages()) > 118            return selector and languages19        return False20    def _translations(self, missing):21        # Figure out the "closest" translation in the parent chain of the22        # context. We stop at both an INavigationRoot or an ISiteRoot to look23        # for translations. We do want to find something that is definitely24        # in the language the user asked for.25        context = aq_inner(self.context)26        translations = {}27        chain = aq_chain(context)28        first_pass = True29        _checkPermission = getSecurityManager().checkPermission30        for item in chain:31            if ISiteRoot.providedBy(item):32                # We have a site root, which works as a fallback33                has_view_permission = bool(_checkPermission('View', item))34                for c in missing:35                    translations[c] = (item, first_pass, has_view_permission)36                break37            translatable = ITranslatable(item, None)38            if translatable is None:39                continue40            item_trans = item.getTranslations(review_state=False)41            for code, trans in item_trans.items():42                code = str(code)43                if code not in translations:44                    # make a link to a translation only if the user45                    # has view permission46                    has_view_permission = bool(_checkPermission('View', trans))47                    if (not INavigationRoot.providedBy(item)48                            and not has_view_permission):49                        continue50                    # If we don't yet have a translation for this language51                    # add it and mark it as found52                    translations[code] = (53                        trans, first_pass, has_view_permission54                    )55                    missing = missing - set((code, ))56            if len(missing) <= 0:57                # We have translations for all58                break59            if INavigationRoot.providedBy(item):60                # Don't break out of the navigation root jail61                has_view_permission = bool(_checkPermission('View', item))62                for c in missing:63                    translations[c] = (item, False, has_view_permission)64                break65            first_pass = False66        # return a dict of language code to tuple. the first tuple element is67        # the translated object, the second argument indicates wether the68        # translation is a direct translation of the context or something from69        # higher up the translation chain70        return translations71    def _findpath(self, path, path_info):72        # We need to find the actual translatable content object. As an73        # optimization we assume it is one of the last three path segments74        match = filter(None, path[-3:])75        current_path = filter(None, path_info.split('/'))76        append_path = []77        stop = False78        while current_path and not stop:79            check = current_path.pop()80            if check == 'VirtualHostRoot' or check.startswith('_vh_'):81                # Once we hit a VHM marker, we should stop82                break83            if check not in match:84                append_path.insert(0, check)85            else:86                stop = True87        if append_path:88            append_path.insert(0, '')89        return append_path90    def languages(self):91        context = aq_inner(self.context)92        results = LanguageSelector.languages(self)93        supported_langs = [v['code'] for v in results]94        missing = set([str(c) for c in supported_langs])95        translations = self._translations(missing)96        # We want to preserve the current template / view as used for the97        # current object and also use it for the other languages98        append_path = self._findpath(context.getPhysicalPath(),99                                     self.request.get('PATH_INFO', ''))100        formvariables = get_formvariables(self.request)101        _checkPermission = getSecurityManager().checkPermission102        non_viewable = set()103        for data in results:104            code = str(data['code'])105            data['translated'] = code in translations.keys()106            set_language = '?set_language=%s' % code107            try:108                appendtourl = '/'.join(append_path)109                if self.set_language:110                    appendtourl += '?' + make_query(formvariables,111                                                    dict(set_language=code))112                elif formvariables:113                    appendtourl += '?' + make_query(formvariables)114            except UnicodeError:115                appendtourl = '/'.join(append_path)116                if self.set_language:117                    appendtourl += set_language118            if data['translated']:119                trans, direct, has_view_permission = translations[code]120                if not has_view_permission:121                    # shortcut if the user cannot see the item122                    non_viewable.add((data['code']))123                    continue124                state = getMultiAdapter(125                    (trans, self.request), name='plone_context_state'126                )127                if direct:128                    data['url'] = state.canonical_object_url() + appendtourl129                else:130                    data['url'] = state.canonical_object_url() + set_language131            else:132                has_view_permission = bool(_checkPermission('View', context))133                # Ideally, we should also check the View permission of default134                # items of folderish objects.135                # However, this would be expensive at it would mean that the136                # default item should be loaded as well.137                #138                # IOW, it is a conscious decision to not take in account the139                # use case where a user has View permission a folder but not on140                # its default item.141                if not has_view_permission:142                    non_viewable.add((data['code']))143                    continue144                state = getMultiAdapter(145                    (context, self.request), name='plone_context_state'146                )147                try:148                    data['url'] = state.canonical_object_url() + appendtourl149                except AttributeError:150                    data['url'] = context.absolute_url() + appendtourl151        # filter out non-viewable items152        results = [r for r in results if r['code'] not in non_viewable]153        return results154def get_formvariables(request):155    formvariables = {}156    if request.get("REQUEST_METHOD", "").upper() == "GET":157        for k, v in request.form.items():158            if isinstance(v, unicode):159                formvariables[k] = v.encode('utf-8')160            else:161                formvariables[k] = v...admin.py
Source:admin.py  
...5    list_filter = ["birth_date", "first_name", "last_name"]6    search_fields = ["id", "birth_date", "first_name", "last_name"]7    def has_delete_permission(self, request, obj=None):8        return request.user.is_superuser9    def has_view_permission(self, request, obj=None):10        return request.user.is_superuser11    def has_add_permission(self, request):12        return request.user.is_superuser13    def has_change_permission(self, request, obj=None):14        return request.user.is_superuser15class InstructorAdmin(admin.ModelAdmin):16    list_display = ["user_name", "email", "birth_date"]17    list_filter = ["birth_date", "first_name", "last_name", "degree"]18    search_fields = ["birth_date", "first_name", "last_name", "degree"]19    def has_delete_permission(self, request, obj=None):20        return request.user.is_superuser21    def has_view_permission(self, request, obj=None):22        return request.user.is_superuser23    def has_add_permission(self, request):24        return request.user.is_superuser25    def has_change_permission(self, request, obj=None):26        return request.user.is_superuser27class CourseAdmin(admin.ModelAdmin):28    list_display = ["name", "id"]29    list_filter = ["name", "instructors", "users"]30    search_fields = ["instructors", "users"]31    def has_delete_permission(self, request, obj=None):32        return request.user.is_superuser or obj and request.user in obj.instructors33    def has_view_permission(self, request, obj=None):34        return True35    def has_add_permission(self, request):36        return request.user.is_superuser37    def has_change_permission(self, request, obj=None):38        return request.user.is_superuser or obj and request.user in obj.instructors39class LessonAdmin(admin.ModelAdmin):40    def has_delete_permission(self, request, obj=None):41        return request.user.is_superuser or obj and request.user in obj.course.instructors42    def has_view_permission(self, request, obj=None):43        return True44    def has_add_permission(self, request, obj=None):45        return request.user.is_superuser or obj and request.user in obj.course.instructors46    def has_change_permission(self, request, obj=None):47        return request.user.is_superuser or obj and request.user in obj.course.instructors48class EnrollmentAdmin(admin.ModelAdmin):49    pass50class QuestionAdmin(admin.ModelAdmin):51    def has_delete_permission(self, request, obj=None):52        return request.user.is_superuser or obj and request.user in obj.course.instructors53    def has_view_permission(self, request, obj=None):54        return True55    def has_add_permission(self, request, obj=None):56        return request.user.is_superuser or obj and request.user in obj.course.instructors57    def has_change_permission(self, request, obj=None):58        return request.user.is_superuser or obj and request.user in obj.course.instructors59class ChoiceAdmin(admin.ModelAdmin):60    def has_delete_permission(self, request, obj=None):61        return request.user.is_superuser or obj and request.user in obj.question.course.instructors62    def has_view_permission(self, request, obj=None):63        return True64    def has_add_permission(self, request, obj=None):65        return request.user.is_superuser or obj and request.user in obj.question.course.instructors66    def has_change_permission(self, request, obj=None):67        return request.user.is_superuser or obj and request.user in obj.question.course.instructors68class PostAdmin(admin.ModelAdmin):69    pass70class CommentAdmin(admin.ModelAdmin):71    pass72admin.site.register(Course, CourseAdmin)73admin.site.register(Lesson, LessonAdmin)74admin.site.register(Instructor, InstructorAdmin)75admin.site.register(Learner, LearnerAdmin)76admin.site.register(Question, QuestionAdmin)...base_admin.py
Source:base_admin.py  
...5from django.core.exceptions import PermissionDenied6from django.contrib import admin7from django.contrib.contenttypes.models import ContentType8class BaseAdmin(admin.ModelAdmin):9    def has_view_permission(self, request):10        model = self.model11        ct = ContentType.objects.get_for_model(model)12        return request.user.has_perm('{0}.view_{1}'.format(13                model._meta.app_label, model.__name__.lower()))14    def get_model_perms(self, request):15        perms = super(BaseAdmin, self).get_model_perms(request)16        perms['view'] = self.has_view_permission(request)17        perms['change'] = perms['view'] or perms['change']18        return perms19    def has_change_permission(self, request, obj=None):20        if getattr(request, 'readonly', False):21            return True22        return super(BaseAdmin, self).has_change_permission(request, obj)23    def changelist_view(self, request, extra_context=None):24        try:25            return super(BaseAdmin, self).changelist_view(26                request, extra_context=extra_context)27        except PermissionDenied:28            pass29        if request.method == 'POST':30            raise PermissionDenied31        if self.has_view_permission(request):32            request.readonly = True33        return super(BaseAdmin, self).changelist_view(34            request, extra_context=extra_context)35    def change_view(self, request, object_id, extra_context=None):36        try:37            return super(BaseAdmin, self).change_view(38                request, object_id, extra_context=extra_context)39        except PermissionDenied:40            pass41        if request.method == 'POST':42            raise PermissionDenied43        if self.has_view_permission(request):44            request.readonly = True45        return super(BaseAdmin, self).change_view(...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
