Django The 'image' attribute has no file associated with it

后端 未结 7 940
萌比男神i
萌比男神i 2020-12-01 07:09

When a user registers for my app.I receive this error when he reaches the profile page.

The \'image\' attribute has no file associated with it.
Exception Typ         


        
相关标签:
7条回答
  • 2020-12-01 07:38

    i think your problem in model field, try to put a default image value , like this :

    PRF_image = models.ImageField(upload_to='profile_img', blank=True, null=True , default='profile_img/925667.jpg')
    
    0 讨论(0)
  • 2020-12-01 07:47

    Not exactly what OP was looking for, but another possible solution would be to set a default value for ImageField:

     class Profile(models.Model):
        # rest of the fields here
        image = models.ImageField(
            upload_to='profile_pics/',
            default='profile_pics/default.jpg')
    
    0 讨论(0)
  • 2020-12-01 07:50

    bob and person are the same object,

    person = Person.objects.get(user=request.user)
    bob = Person.objects.get(user=request.user)
    

    So you can use just person for it.

    In your template, check image exist or not first,

    {% if person.image %}
        <img src="{{ person.image.url }}">
    {% endif %}
    
    0 讨论(0)
  • 2020-12-01 07:50

    You can also use the Python 3 built-in function getattr to create your new property:

    @property
    def image_url(self):
        """
        Return self.photo.url if self.photo is not None, 
        'url' exist and has a value, else, return None.
        """
        if self.image:
            return getattr(self.photo, 'url', None)
        return None
    

    and use this property in your template:

    <img src="{{ my_obj.image_url|default_if_none:'#' }}" />
    
    0 讨论(0)
  • 2020-12-01 07:56

    Maybe this helps but my database didn't save on of the pictures for the object displayed on the page.

    As that object in models.py has blank=False and also I am looping through object, it constantly gave an error until I added a replacement picture in the admin for the database to render.

    0 讨论(0)
  • 2020-12-01 07:59

    The better approach which would not violate DRY is to add a helper method to the model class like:

    @property
    def image_url(self):
        if self.image and hasattr(self.image, 'url'):
            return self.image.url
    

    and use default_if_none template filter to provide default url:

    <img src="{{ object.image_url|default_if_none:'#' }}" />
    
    0 讨论(0)
提交回复
热议问题