我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.admin.widgets.ForeignKeyRawIdWidget()。
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = _('None') if db_field.blank else None if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = _('None') if db_field.blank else None if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = _('None') if db_field.blank else None if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = _('None') if db_field.blank else None queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs)
def formfield_for_dbfield(self, db_field, **kwargs): formfield = super(SlideInline, self).formfield_for_dbfield(db_field, **kwargs) if (formfield and isinstance(formfield.widget, ForeignKeyRawIdWidget)): widget = ForeignKeyRawIdWidgetWrapper(formfield.widget) formfield.widget = widget return formfield
def render(self, name, value, attrs=None): obj = self.obj_for_value(value) css_id = attrs.get('id') css_id_folder = "%s_folder" % css_id css_id_description_txt = "%s_description_txt" % css_id if attrs is None: attrs = {} related_url = None if value: try: folder = Folder.objects.get(pk=value) related_url = folder.get_admin_directory_listing_url_path() except Exception: pass if not related_url: related_url = reverse('admin:filer-directory_listing-last') params = self.url_parameters() params['_pick'] = 'folder' if params: url = '?' + urlencode(sorted(params.items())) else: url = '' if 'class' not in attrs: # The JavaScript looks for this hook. attrs['class'] = 'vForeignKeyRawIdAdminField' super_attrs = attrs.copy() hidden_input = super(ForeignKeyRawIdWidget, self).render(name, value, super_attrs) # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. context = { 'hidden_input': hidden_input, 'lookup_url': '%s%s' % (related_url, url), 'lookup_name': name, 'span_id': css_id_description_txt, 'object': obj, 'clear_id': '%s_clear' % css_id, 'descid': css_id_description_txt, 'noimg': 'filer/icons/nofile_32x32.png', 'foldid': css_id_folder, 'id': css_id, 'LTE_DJANGO_1_7': LTE_DJANGO_1_7, } html = render_to_string('admin/filer/widgets/admin_folder.html', context) return mark_safe(html)
def render(self, name, value, attrs=None): obj = self.obj_for_value(value) css_id = attrs.get('id', 'id_image_x') related_url = None if value: try: file_obj = File.objects.get(pk=value) related_url = file_obj.logical_folder.get_admin_directory_listing_url_path() except Exception as e: # catch exception and manage it. We can re-raise it for debugging # purposes and/or just logging it, provided user configured # proper logging configuration if filer_settings.FILER_ENABLE_LOGGING: logger.error('Error while rendering file widget: %s', e) if filer_settings.FILER_DEBUG: raise if not related_url: related_url = reverse('admin:filer-directory_listing-last') params = self.url_parameters() params['_pick'] = 'file' if params: lookup_url = '?' + urlencode(sorted(params.items())) else: lookup_url = '' if 'class' not in attrs: # The JavaScript looks for this hook. attrs['class'] = 'vForeignKeyRawIdAdminField' # rendering the super for ForeignKeyRawIdWidget on purpose here because # we only need the input and none of the other stuff that # ForeignKeyRawIdWidget adds hidden_input = super(ForeignKeyRawIdWidget, self).render(name, value, attrs) context = { 'hidden_input': hidden_input, 'lookup_url': '%s%s' % (related_url, lookup_url), 'object': obj, 'lookup_name': name, 'id': css_id, 'admin_icon_delete': ( 'admin/img/icon_deletelink.gif' if LTE_DJANGO_1_8 else 'admin/img/icon-deletelink.svg' ), 'LTE_DJANGO_1_7': LTE_DJANGO_1_7, } html = render_to_string('admin/filer/widgets/admin_file.html', context) return mark_safe(html)
def lookup_allowed(self, lookup, value): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for l in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(l): l = l() for k, v in widgets.url_params_from_lookup_dict(l).items(): if k == lookup and v == value: return True relation_parts = [] prev_field = None for part in lookup.split(LOOKUP_SEP): try: field = model._meta.get_field(part) except FieldDoesNotExist: # Lookups on non-existent fields are ok, since they're ignored # later. break # It is allowed to filter on values that would be found from local # model anyways. For example, if you filter on employee__department__id, # then the id value would be found already from employee__department_id. if not prev_field or (prev_field.concrete and field not in prev_field.get_path_info()[-1].target_fields): relation_parts.append(part) if not getattr(field, 'get_path_info', None): # This is not a relational field, so further parts # must be transforms. break prev_field = field model = field.get_path_info()[-1].to_opts.model if len(relation_parts) <= 1: # Either a local field filter, or no fields at all. return True clean_lookup = LOOKUP_SEP.join(relation_parts) valid_lookups = [self.date_hierarchy] for filter_item in self.list_filter: if isinstance(filter_item, type) and issubclass(filter_item, SimpleListFilter): valid_lookups.append(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.append(filter_item[0]) else: valid_lookups.append(filter_item) return clean_lookup in valid_lookups
def lookup_allowed(self, lookup, value): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for fk_lookup in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(fk_lookup): fk_lookup = fk_lookup() for k, v in widgets.url_params_from_lookup_dict(fk_lookup).items(): if k == lookup and v == value: return True relation_parts = [] prev_field = None for part in lookup.split(LOOKUP_SEP): try: field = model._meta.get_field(part) except FieldDoesNotExist: # Lookups on non-existent fields are ok, since they're ignored # later. break # It is allowed to filter on values that would be found from local # model anyways. For example, if you filter on employee__department__id, # then the id value would be found already from employee__department_id. if not prev_field or (prev_field.concrete and field not in prev_field.get_path_info()[-1].target_fields): relation_parts.append(part) if not getattr(field, 'get_path_info', None): # This is not a relational field, so further parts # must be transforms. break prev_field = field model = field.get_path_info()[-1].to_opts.model if len(relation_parts) <= 1: # Either a local field filter, or no fields at all. return True clean_lookup = LOOKUP_SEP.join(relation_parts) valid_lookups = [self.date_hierarchy] for filter_item in self.list_filter: if isinstance(filter_item, type) and issubclass(filter_item, SimpleListFilter): valid_lookups.append(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.append(filter_item[0]) else: valid_lookups.append(filter_item) return clean_lookup in valid_lookups
def __init__(self, *args, **kwargs): super(PagePermissionInlineAdminForm, self).__init__(*args, **kwargs) user = get_current_user() # current user from threadlocals sub_users = get_subordinate_users(user) limit_choices = True use_raw_id = False # Unfortunately, if there are > 500 users in the system, non-superusers # won't see any benefit here because if we ask Django to put all the # user PKs in limit_choices_to in the query string of the popup we're # in danger of causing 414 errors so we fall back to the normal input # widget. if get_cms_setting('RAW_ID_USERS'): if sub_users.count() < 500: # If there aren't too many users, proceed as normal and use a # raw id field with limit_choices_to limit_choices = True use_raw_id = True elif get_user_permission_level(user) == 0: # If there are enough choices to possibly cause a 414 request # URI too large error, we only proceed with the raw id field if # the user is a superuser & thus can legitimately circumvent # the limit_choices_to condition. limit_choices = False use_raw_id = True # We don't use the fancy custom widget if the admin form wants to use a # raw id field for the user if use_raw_id: from django.contrib.admin.widgets import ForeignKeyRawIdWidget # This check will be False if the number of users in the system # is less than the threshold set by the RAW_ID_USERS setting. if isinstance(self.fields['user'].widget, ForeignKeyRawIdWidget): # We can't set a queryset on a raw id lookup, but we can use # the fact that it respects the limit_choices_to parameter. if limit_choices: self.fields['user'].widget.rel.limit_choices_to = dict( id__in=list(sub_users.values_list('pk', flat=True)) ) else: self.fields['user'].widget = UserSelectAdminWidget() self.fields['user'].queryset = sub_users self.fields['user'].widget.user = user # assign current user self.fields['group'].queryset = get_subordinate_groups(user)
def lookup_allowed(self, lookup, value): model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for l in model._meta.related_fkey_lookups: for k, v in widgets.url_params_from_lookup_dict(l).items(): if k == lookup and v == value: return True parts = lookup.split(LOOKUP_SEP) # Last term in lookup is a query term (__exact, __startswith etc) # This term can be ignored. if len(parts) > 1 and parts[-1] in QUERY_TERMS: parts.pop() # Special case -- foo__id__exact and foo__id queries are implied # if foo has been specifically included in the lookup list; so # drop __id if it is the last part. However, first we need to find # the pk attribute name. rel_name = None for part in parts[:-1]: try: field, _, _, _ = model._meta.get_field_by_name(part) except FieldDoesNotExist: # Lookups on non-existent fields are ok, since they're ignored # later. return True if hasattr(field, 'rel'): if field.rel is None: # This property or relation doesn't exist, but it's allowed # since it's ignored in ChangeList.get_filters(). return True model = field.rel.to rel_name = field.rel.get_related_field().name elif isinstance(field, RelatedObject): model = field.model rel_name = model._meta.pk.name else: rel_name = None if rel_name and len(parts) > 1 and parts[-1] == rel_name: parts.pop() if len(parts) == 1: return True clean_lookup = LOOKUP_SEP.join(parts) return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy