【问题标题】:Images are not displayed in my home page from model.py来自model.py的图像未显示在我的主页中
【发布时间】:2019-07-25 15:33:04
【问题描述】:

我已经为用户创建了一个表单来发布他们的东西,所有其他的东西都可以正常工作,只有图像不能显示在我的主页上

我一次又一次地试图忽略代码似乎没问题,我的猜测是图像文件夹的结构。我不确定如何为图像构建文件夹。请帮忙!!

views.py

@login_required
def PostNew(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('loststuffapp:IndexView')
    else:
        form = PostForm()
    return render(request, 'loststuffapp/form.html', {'form': form})

models.py

class Documents(models.Model):
    docs_name = models.CharField(max_length=200,verbose_name="Names in Documents")
    item_type = models.CharField(default="", max_length=100,verbose_name="Item type" )
    police_station = models.CharField(max_length=255, verbose_name="Police station")
    phone_no = models.CharField(verbose_name="Phone number", max_length=10, blank=False, 
validators=[int_list_validator(sep=''),MinLengthValidator(10),], 
default='0766000000')
    date = models.DateTimeField(default=timezone.now,verbose_name="Date")
    Description = models.TextField(blank=True, null=True,verbose_name="Description")
    pay_no = models.IntegerField(default=0,verbose_name="payment number")
    publish = models.BooleanField(default=False)

    image = models.ImageField(default="add Item image",
                          upload_to="media",blank=False, verbose_name="Images")
"""docstring for Documents"""

    def __str__(self):
        return self.docs_name

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Documents
        fields = ['docs_name', 'item_type', 'police_station','phone_no', 'Description', 'image']
        labels = {'docs_name': 'Name in Documents','item_type':'Item type','police_station':'Police station',
     'phone_no':'Phone number','Description':'Description','image':'Images'
    }

setting.py

STATIC_URL = '/static/'

MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'loststuff/media')

home.html

{% for Doc in documents %}
 <div class="content-wrapper">
  <div class="card">
    <div class="card-image">

        <p><label style="font-size:15px; font-weight: bold;color: black;">Names in documents:  </label>{{Doc.docs_name}}</p>
        <p><label style="font-size:15px; font-weight: bold;color: black;">Item Type:  </label>{{Doc.item_type}}</p>
        <p><label style="font-size:15px; font-weight: bold;color: black;">Police station:  </label>{{Doc.police_station}}</p>
        <p><label style="font-size:15px; font-weight: bold;color: black;">Phone number:  </label>{{Doc.phone_no}}</p>
        <p><label style="font-size:15px; font-weight: bold;color: black;">Description:  </label>{{Doc.Description}}</p>
        <p><label style="font-size:15px; font-weight: bold;color: black;">Images:  </label><img src = "/media/{{Doc.image.url}}" style="width: 450px; height: 300px;"/></p>
        <p>{{Doc.date}}</p>

</div>

{% endfor %}

urls.py

urlpatterns = [

         path('', views.IndexView, name="IndexView"),
         path('IndexView', views.IndexView, name="IndexView"),
         path('PostNew/', views.PostNew, name="PostNew"),
         path('register/', views.register, name="register"),
         path('logout/', views.logout_request, name="logout"),
         path('login/', views.login_request, name="login"),
         path('ContactForm/', views.ContactForm, name="ContactForm"),
         path('About/', views.About, name="About"),
         path('Help/', views.Help, name="Help"),

] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

文件结构

【问题讨论】:

    标签: django python-3.x django-models


    【解决方案1】:

    您看到/media 中的图像了吗?根据您显示的代码,它看起来不像您的binding the upload files to the form

    你会希望你的视图看起来像这样:

    @login_required
    def PostNew(request):
        if request.method == "POST":
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                post = form.save(commit=False)
                post.author = request.user
                post.save()
                return redirect('loststuffapp:IndexView')
        else:
            form = PostForm()
        return render(request, 'loststuffapp/form.html', {'form': form})
    

    请注意添加了request.FILES 作为表单构造函数的第二个参数。您还需要确保您的上传表单设置 enctype,如下所示:

    <form action="{% url 'your-url-here' %}" method="post" enctype="multipart/form-data">
    

    您在Documents 中定义image 字段的方式似乎也存在问题。您需要将其更新为如下所示:

    image = models.ImageField(upload_to="documents", blank=False, verbose_name="Images")
    

    请注意,我替换了 upload_to 参数中的“媒体”。它已经在settings.MEDIA_ROOT 中设置。我还删除了 default 参数,因为它在这种情况下没有意义。

    【讨论】:

    • 我只看到两张图片,但我已经发布了很多次,这意味着我应该看到很多图片。所以我想在某些时候它是好的,但我没有注意到
    • 对如何将表单绑定到图像字段有点困惑,因为链接中的示例与我的完全不同,并且仍然是python的初学者
    • 别担心,我的答案再填写一点,详细说明如何解决这个问题。
    • 我已经进行了更改,现在我收到另一个错误,称为“未找到 'PostNew' 的反向。'PostNew' 不是有效的视图函数或模式名称。”,我想知道因为这个 PostNew 是视图中的正确功能
    • 你能发布 urls.py 吗?
    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多