3
votes
Template error:

In template D:\virtualEnv\alumni\member\templates\member\index.html, error at line 15

The 'photo' attribute has no file associated with it.   5 :     <!-- Albums -->
   6 :     <div class="row">
   7 :         <div class="col-sm-12">
   8 :             <h3>{{ user.username }}'s Albums</h3>
   9 :         </div>
   10 :         {% if all_persons %}
   11 :             {% for person in all_persons %}
   12 :                 <div class="col-sm-4 col-lg-2">
   13 :                     <div class="thumbnail">
   14 :                         <a href="{% url 'member:detail' person.id %}">
   15 :                             <img src=" {{ person.photo.url }} " class="img-responsive">
   16 :                         </a>
   17 :                         <div class="caption">
   18 :                             <h2>{{ person.name }}</h2>
   19 :                             <h4>{{ person.category }}</h4>
   20 : 
   21 :                             <!-- View Details -->
   22 :                             <a href="{% url 'member:detail' person.id %}" class="btn btn-primary btn-sm" role="button">View Details</a>
   23 : 
   24 :                             
   25 : 

Traceback:

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _resolve_lookup 885. current = current[bit]

During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:

File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request)

File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request)

File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render()

File "D:\virtualEnv\lib\site-packages\django\template\response.py" in render 109. self.content = self.rendered_content

File "D:\virtualEnv\lib\site-packages\django\template\response.py" in rendered_content 86. content = template.render(context, self._request)

File "D:\virtualEnv\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 208. return self._render(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\loader_tags.py" in render 61. result = self.nodelist.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\defaulttags.py" in render 323. return nodelist.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render_annotated(context))

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 1044. output = self.filter_expression.resolve(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in resolve 711. obj = self.var.resolve(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in resolve 852. value = self._resolve_lookup(context)

File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _resolve_lookup 893. current = getattr(current, bit)

File "D:\virtualEnv\lib\site-packages\django\db\models\fields\files.py" in _get_url 68. self._require_file()

File "D:\virtualEnv\lib\site-packages\django\db\models\fields\files.py" in _require_file 46. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)

Exception Type: ValueError at / Exception Value: The 'photo' attribute has no file associated with it.

my views:

class IndexView(generic.ListView):
    template_name = 'member/index.html'
    context_object_name = 'all_persons'

    def get_queryset(self):
        return Person.objects.all()

class DetailView(generic.DetailView):
    model = Person
    template_name = 'member/detail.html'


class AlbumCreate(CreateView):
    model = Person
    fields = '__all__'

My models are:

class Person(models.Model):
    name = models.CharField(max_length=128)
    present_position=models.CharField(max_length=100)
    organization= models.CharField(max_length=150,blank=True)
    address = models.CharField(max_length=150, blank=True)
    tele_land = models.CharField(max_length=15,blank=True)
    tele_cell = models.CharField(max_length=15, blank=True)
    email = models.EmailField(max_length=70, blank=True, null=True, unique=True)
    photo= models.ImageField(upload_to='persons/%Y/%m/%d/',max_length=70, blank=True )
    category = models.ForeignKey('Membership', on_delete=models.CASCADE)

    def get_absolute_url(self):
        return reverse('member:detail', kwargs={'pk': self.pk})

class Membership(models.Model):
    category = models.CharField(max_length=50, blank=False)

Ursl:

from . import views    
app_name = 'member'
urlpatterns = [    
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'member/add/$', views.AlbumCreate.as_view(), name='member-add'),
]

detail template:

<div class="col-sm-4 col-md-3">
            <div class="panel panel-default">
                <div class="panel-body">
                    <a href="{% url 'member:detail' person.id %}">
                        {% if member.photo %}
                            <img src="{{ member.photo.url }}" class="img-responsive">
                        {% else %}
                            <h3>No image to display</h3>
                        {% endif %}
                    </a>
                    <p>{{member.name}}</p>
                    <p>{{member.present_position}}</p>
                    <p>{{member.organization}}</p>
                    <p>{{member.address}}</p>
                    <p>{{member.tele_land}}</p>
                    <p>{{member.tele_cell}}</p>
                    <p>{{member.email}}</p>
                </div>
            </div>
        </div>

Project urls:

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from  django.conf.urls.static import static
from member import urls as member_urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include(member_urls, namespace="member")),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Why photo field gives these errors?

5

5 Answers

9
votes

I solved this using an answer of Stackoverflow, in the Model:

@property
def photo_url(self):
    if self.photo and hasattr(self.photo, 'url'):
        return self.photo.url

In the template, using default_if_none as for default url:

<img src="{{ person.photo_url|default_if_none:'#' }}" />

This actually provides me correct answers after lots of searching and spending many times.

Hope it will helps other to load images in the django template.

0
votes

Try returning the "full URL" by not calling the FileField field/property name without the .url part e.g. person.photo and not person.photo.url.

N/B: I have only tested it on a REST API in a DRF(djangorestframework) serializer class am not sure if it'll work for django template's but it's worth a try

0
votes

My dear friend, ohid's solving is good but not enough because If user hasn't profile picture you should show default image. So you can follow below steps:

Add this method to your person model:

@property
def get_photo_url(self):
    if self.photo and hasattr(self.photo, 'url'):
        return self.photo.url
    else:
        return "/static/images/user.jpg"

You can use any path (/media, /static etc.) but don't forget putting default user photo as user.jpg to your path.

And change your code in template like below:

<img src="{{ person.get_photo_url }}" class="img-responsive thumbnail " alt="img">
0
votes

May be your ImageField is not getting any image at some point, but somewhere else you are trying to use the path of the image(which is non-existent). Others have also pointed the same thing. This can happen in the template {{ post.post_image.url }} or in the views.py or even in the models.py when you are trying to preprocess the image before saving the image. Where ever you are using it be careful and use try-except block.

from PIL import Image     # I was using pillow to pre-process
...
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    try:
        img = Image.open(self.post_image.path)
    except:
        print("Do something.. break or return")
        return  
0
votes

Delete all the previous records which have no image attribute or use

<img src="{{ person.photo_url|default_if_none:'#' }}" />