Value error on Image field when trying to comvert model to dict

丶灬走出姿态 提交于 2020-06-26 14:48:06

问题


I have 2 models, 1st is Garage

class Garage(models.Model):
    name = models.CharField(verbose_name=_('Garage'), max_length=200)

    @property
    def cars(self) -> list:
        from django.forms.models import model_to_dict

        cars = []
        for i in Car.objects.filter(garage=self.id):
            cars.append(model_to_dict(i))

        return cars

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _('Garage')

My 2nd model is Car,

class Car(models.Model):
    name = models.CharField(verbose_name=_('Car Name'), max_length=200)
    garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT)
    price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2)
    image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _("Car")
        verbose_name_plural = _("Cars")

Now, when I try to run, the property 'cars' in the Garage model throws ValueError.

ValueError: The 'image' attribute has no file associated with it.

The complete error log is:

Traceback (most recent call last):
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/response.py", line 72, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 107, in render
    allow_nan=not self.strict, separators=separators
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/json.py", line 28, in dumps
    return json.dumps(*args, **kwargs)
  File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/encoders.py", line 67, in default
    return tuple(item for item in obj)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/encoders.py", line 67, in <genexpr>
    return tuple(item for item in obj)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/files/base.py", line 78, in __iter__
    for chunk in self.chunks():
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/files/base.py", line 55, in chunks
    self.seek(0)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/files/utils.py", line 20, in <lambda>
    seek = property(lambda self: self.file.seek)
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/db/models/fields/files.py", line 41, in _get_file
    self._require_file()
  File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/db/models/fields/files.py", line 38, in _require_file
    raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'image' attribute has no file associated with it.

I am not able to solve this error and I need the image field to be serialized. How can I solve this error?


回答1:


So, I was able to solve my problem. I just created a property and generated the image url for cars model.

Cars models.py

class Car(models.Model):
    name = models.CharField(verbose_name=_('Car Name'), max_length=200)
    garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT)
    price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2)
    image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None)

    @property
    def image_url(self):
        from django.contrib.sites.models import Site

        domain = Site.objects.get_current().domain
        url = 'http://{domain}'.format(domain=domain)

        if self.image and hasattr(self.image, 'url'):
            return url + self.image.url

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _("Car")
        verbose_name_plural = _("Cars")

And just included this image_url property in model_to_dict fields filter.

model_to_dict(i, fields=[..., 'image_url', ...]


来源:https://stackoverflow.com/questions/57288568/value-error-on-image-field-when-trying-to-comvert-model-to-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!