【问题标题】:The 'img' attribute has no file associated with it'img' 属性没有与之关联的文件
【发布时间】:2019-06-12 10:35:13
【问题描述】:

我正在尝试为我的 Django 项目使用 基于类的视图。 我制作了一个简单的表单,管理员可以使用 CreateView 添加新数据。 数据已成功添加,但在用户被重定向到另一个页面的表单提交后,图像没有上传。 因此,当我加载我的主页时,会生成一个错误,我无法找到解决方案。

追溯错误

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.21
Python Version: 2.7.16
Installed Applications:
['projectfiles',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\projectfiles\templates\projectfiles\HomePage.html, error at line 16
   The 'food_pic' attribute has no file associated with it.   6 : 
   7 : {% block asd %}
   8 : 
   9 : <div class='box' align='right'>
   10 : Food<hr>
   11 : {% if food_count %}
   12 : {% for i in food_data %}
   13 :     {{ i.item_name }}
   14 :     Rs.{{ i.item_price }}
   15 :     if
   16 :     <img src="{{ i.food_pic }}" alt=' {{ i.food_pic.url }} ' width="124" height="124"/>
   17 :     <img>
   18 : {% endfor %}
   19 : {% else %}
   20 : <h6>NO DATA</h6>
   21 : {% endif %}
   22 : </div>
   23 : 
   24 : 
   25 : <br>
   26 : <div class='box' align='right'>


Traceback:

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response
  215.                 response = response.render()

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\response.py" in render
  107.             self.content = self.rendered_content

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\response.py" in rendered_content
  84.         content = template.render(context, self._request)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render
  207.                     return self._render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\loader_tags.py" in render
  63.                 result = self.nodelist.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\defaulttags.py" in render
  322.                 return nodelist.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\defaulttags.py" in render
  216.                     nodelist.append(node.render_annotated(context))

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in render
  1040.             output = self.filter_expression.resolve(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in resolve
  708.                 obj = self.var.resolve(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in resolve
  849.             value = self._resolve_lookup(context)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\template\base.py" in _resolve_lookup
  890.                         current = getattr(current, bit)

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\fields\files.py" in url
  69.         self._require_file()

File "C:\Users\BITSWI~1\Desktop\Maala\Maala\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 /home/
Exception Value: The 'food_pic' attribute has no file associated with it.

models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from datetime import date, datetime




class Food_Data(models.Model):
    item_name = models.CharField(max_length=50)
    item_price = models.SmallIntegerField(blank=False,null=False)
    food_pic = models.ImageField( upload_to='images', blank=True, null=True)


    def __str__(self):
        return self.item_name

    class Meta:
        verbose_name_plural = ("Food Data")
        verbose_name = ("Food Data")



forms.py

# -*- coding: utf-8 -*-
from .models import *
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import *



class FoodForm(forms.ModelForm):

    class Meta:
        model = Food_Data
        fields = ("item_name","item_price","food_pic")

home.html

<title>Home</title>
{% include 'projectfiles/base.html' %}

<br><br><br>
<h1 align='center'>TESTING</h1>

{% block asd %}

<div class='box' align='right'>
Food<hr>
{% if food_count %}
{% for i in food_data %}
    {{ i.item_name }}
    Rs.{{ i.item_price }}

    <img src="{{ i.food_pic }}" alt='{{ i.food_pic.url }}' width="124" height="124"/>
    <img>
{% endfor %}
{% else %}
<h6>NO DATA</h6>
{% endif %}
</div>

{% endblock asd %}

views.py


class HomeView(TemplateView):
    template_name = "projectfiles\HomePage.html"

#Takes data from the Food database and renders it.
    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)

        #Food Model
        context['food_data'] = Food_Data.objects.all()
        context['food_count'] = Food_Data.objects.all().count

        return context




class Food_CreateView(CreateView):
    model = Food_Data
    form_class = FoodForm
    template_name = 'projectfiles\Create_food_View.html'
    # renamed it because of /f error

    def get_success_url(self):
            return reverse('Add-Food')

我希望页面能够用图像呈现新输入的数据。 如果我注释掉它加载的食物的 img 标签。

提前致谢。

【问题讨论】:

    标签: django django-models django-class-based-views


    【解决方案1】:

    你只需要检查是否找到相关图片,然后尝试获取它的url属性。

    <title>Home</title>
    {% include 'projectfiles/base.html' %}
    
    <br><br><br>
    <h1 align='center'>TESTING</h1>
    
    {% block asd %}
    <div class='box' align='right'>
    Food<hr>
    {% if food_count %}
    {% for i in food_data %}
        {{ i.item_name }}
        Rs.{{ i.item_price }}
        {% if i.food_pic %}
            <img src="{{ i.food_pic }}" alt='{{ i.food_pic.url }}' width="124" height="124"/>
            <img>
        {% endif %}
    {% endfor %}
    {% else %}
    <h6>NO DATA</h6>
    {% endif %}
    </div>
    {% endblock asd %}
    

    【讨论】:

    • 我想向用户展示商品图片。图片未通过表单上传。我不知道为什么。
    • @TalhaMurtaza 可能出于任何原因,我对此一无所知。我需要更多详细信息来指导您。
    • @TalhaMurtaza 但问题标题和报告的错误与{% if i.food_pic %} 有关,而您的回答与另一个问题有关!
    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2023-02-21
    • 2021-11-18
    • 2021-02-11
    • 2020-03-08
    相关资源
    最近更新 更多