我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.FieldDoesNotExist()。
def result_item(self, item, obj, field_name, row): opts = obj._meta try: f = opts.get_field(field_name) except models.FieldDoesNotExist: f = None if f: if isinstance(f, models.ImageField): img = getattr(obj, field_name) if img: db_value = str(img) if db_value.startswith('/'): file_path = urlparse.urljoin(settings.REMOTE_MEDIA_URL, db_value) else: file_path = img.url if type(self.list_gallery)==str: file_path = '%s%s'%(file_path,self.list_gallery) item.text = mark_safe('<a href="%s" target="_blank" data-gallery="gallery"><img src="%s" class="field_img"/></a>' % (file_path, file_path)) return item # Media
def get_ordering_field(self, field_name): """ Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no proper model field name can be matched. """ try: field = self.opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self, field_name): attr = getattr(self, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None)
def _get_field_aggregate(self, field_name, obj, row): item = ResultItem(field_name, row) item.classes = ['aggregate', ] if field_name not in self.aggregate_fields: item.text = "" else: try: f = self.opts.get_field(field_name) agg_method = self.aggregate_fields[field_name] key = '%s__%s' % (field_name, agg_method) if key not in obj: item.text = "" else: item.text = display_for_field(obj[key], f) item.wraps.append('%%s<span class="aggregate_title label label-info">%s</span>' % AGGREGATE_TITLE[agg_method]) item.classes.append(agg_method) except FieldDoesNotExist: item.text = "" return item
def _update_duration(ticket, data, user): """ Generic update for duration """ try: key = data.keys()[0] previous = getattr(ticket, key) data[key.replace('Duration', 'Start')] = datetime.now() Ticket.objects.filter(pk=ticket.pk).update(**data) ticket = Ticket.objects.get(pk=ticket.pk) database.log_action_on_ticket( ticket=ticket, action='update_property', user=user, property=key.replace('Duration', ''), previous_value=str(timedelta(seconds=previous)), new_value=str(timedelta(seconds=getattr(ticket, key))) ) except (FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex: raise BadRequest(str(ex.message)) return show(ticket.id, user)
def update_proof(ticket_id, proof_id, body, user): """ Update proof """ ticket = None try: ticket = Ticket.objects.get(id=ticket_id) Proof.objects.get(id=proof_id) except (ObjectDoesNotExist, ValueError): raise NotFound('Not Found') try: body.pop('id', None) body.pop('ticket', None) ticket.proof.update(**body) ticket.save() database.log_action_on_ticket( ticket=ticket, action='update_proof', user=user ) except (KeyError, FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex: raise BadRequest(str(ex.message)) return {'message': 'Proof successfully updated'}
def delete_proof(ticket_id, proof_id, user): """ Delete proof """ try: ticket = Ticket.objects.get(id=ticket_id) except (ObjectDoesNotExist, ValueError): raise NotFound('Ticket not found') try: proof = ticket.proof.get(id=proof_id) proof.delete() database.log_action_on_ticket( ticket=ticket, action='delete_proof', user=user ) except (ObjectDoesNotExist, KeyError, FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex: raise BadRequest(str(ex.message)) return {'message': 'Proof successfully deleted'}
def get_field_docs(self, fieldname): try: field = self.model._meta.get_field(fieldname) if isinstance(field, models.ForeignKey): return _serializers[field.rel.to].docs() elif isinstance(field, models.ManyToManyField): spec = _serializers[field.rel.to].docs() spec['array'] = True return spec elif isinstance(field, models.ManyToOneRel): spec = _serializers[field.related_model].docs() spec['array'] = True return spec return FieldDocs(self.model, field) except models.FieldDoesNotExist: model = getattr(self.model, fieldname).related.related_model spec = _serializers[model].docs() spec['array'] = True return spec
def serialize_instance(instance): """ Since Django 1.6 items added to the session are no longer pickled, but JSON encoded by default. We are storing partially complete models in the session (user, account, token, ...). We cannot use standard Django serialization, as these are models are not "complete" yet. Serialization will start complaining about missing relations et al. """ data = {} for k, v in instance.__dict__.items(): if k.startswith('_') or callable(v): continue try: if isinstance(instance._meta.get_field(k), BinaryField): v = force_text(base64.b64encode(v)) except FieldDoesNotExist: pass data[k] = v return json.loads(json.dumps(data, cls=DjangoJSONEncoder))
def deserialize_instance(model, data): ret = model() for k, v in data.items(): if v is not None: try: f = model._meta.get_field(k) if isinstance(f, DateTimeField): v = dateparse.parse_datetime(v) elif isinstance(f, TimeField): v = dateparse.parse_time(v) elif isinstance(f, DateField): v = dateparse.parse_date(v) elif isinstance(f, BinaryField): v = force_bytes( base64.b64decode( force_bytes(v))) except FieldDoesNotExist: pass setattr(ret, k, v) return ret
def get_form_datas(self): """ ? Request ??? Form ?????? """ if self.request_method == 'get': initial = dict(self.request.GET.items()) for k in initial: try: f = self.opts.get_field(k) except models.FieldDoesNotExist: continue if isinstance(f, models.ManyToManyField): # ????????????????? initial[k] = initial[k].split(",") return {'initial': initial} else: return {'data': self.request.POST, 'files': self.request.FILES}
def get_ordering_field(self, field_name): """ ?????? field_name ???? """ try: field = self.opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # ?? db field ??? if callable(field_name): attr = field_name elif hasattr(self, field_name): attr = getattr(self, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None)
def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = opts.get_field(name) except models.FieldDoesNotExist: # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif (model_admin is not None and hasattr(model_admin, name) and not name == '__str__' and not name == '__unicode__'): attr = getattr(model_admin, name) value = attr(obj) else: attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None else: attr = None value = getattr(obj, name) return f, attr, value
def get_ordering_field(self, field_name): """ Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no proper model field name can be matched. """ try: field = self.opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if isinstance(field_name, collections.Callable): attr = field_name elif hasattr(self, field_name): attr = getattr(self, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None)
def __setattr__(self, name, value): """ We have to intercept here because RelatedFields won't accept wrapped model instances values, so we have to trick them. """ if name in self._not_wrapped: return super().__setattr__(name, value) try: field = self._obj._meta.get_field(name) except FieldDoesNotExist: pass else: if field.many_to_one and name != field.attname and value is not None: if isinstance(value, models.Model): value = self._wrap_instance(value) if not isinstance(value, ModelInstanceWrapper): raise ValueError('value has to be None or ModelInstanceWrapper') setattr(self._obj, name, value._obj) setattr(self._obj, field.get_cache_name(), value) return super().__setattr__(name, value)
def attrlabel(widget, attrname): widget_prop = _method_label(widget, attrname) if widget_prop is not None: return widget_prop elif widget.model: model_prop = _method_label(widget.model, attrname) if model_prop is not None: # Allows to have empty description return model_prop if attrname == 'pk': fieldname = widget.model._meta.pk.name else: fieldname = attrname try: field = widget.model._meta.get_field(fieldname) return field.verbose_name except models.FieldDoesNotExist: pass return attrname
def validate_local_fields(e, opts, field_name, fields): from django.db import models if not isinstance(fields, collections.Sequence): e.add(opts, 'all %s elements must be sequences' % field_name) else: for field in fields: try: f = opts.get_field(field, many_to_many=True) except models.FieldDoesNotExist: e.add(opts, '"%s" refers to %s, a field that doesn\'t exist.' % (field_name, field)) else: if isinstance(f.rel, models.ManyToManyRel): e.add(opts, '"%s" refers to %s. ManyToManyFields are not supported in %s.' % (field_name, f.name, field_name)) if f not in opts.local_fields: e.add(opts, '"%s" refers to %s. This is not in the same model as the %s statement.' % (field_name, f.name, field_name))
def validate_list_display(self, cls, model): " Validate that list_display only contains fields or usable attributes. " if hasattr(cls, 'list_display'): check_isseq(cls, 'list_display', cls.list_display) for idx, field in enumerate(cls.list_display): if not callable(field): if not hasattr(cls, field): if not hasattr(model, field): try: model._meta.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r." % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)) else: # getattr(model, field) could be an X_RelatedObjectsDescriptor f = fetch_attr(cls, model, "list_display[%d]" % idx, field) if isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported." % (cls.__name__, idx, field))
def get_ordering_field(self, field_name): """ Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no proper model field name can be matched. """ try: field = self.lookup_opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None)