我是 Django 新手,我正在做一個簡單的 Web 應用程式來保存和顯示產品。但我的問題是當我嘗試顯示產品資訊時,我可以顯示除產品影像之外的所有內容。你可以在下面看到我的代碼。
靜態部分中的 settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
主要的 urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
path('products/',include('products.urls')),
] static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Products 應用程式的 models.py:
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField, DateField, DateTimeField
from datetime import datetime
from django.db.models.fields.related import ForeignKey, ManyToManyField
# Create your models here.
class Product(models.Model):
categories = [
('Phone', 'Phone'),
('Computer', 'Computer'),
]
name = models.CharField(max_length = 50, default='Nothing', verbose_name='title')
content = models.TextField(default='Empty', null = True, blank = True, verbose_name='description')
price = models.DecimalField(max_digits = 5, decimal_places = 2, default=0.0)
image = models.ImageField(upload_to = 'photos/%y/%m/%d', default='media/photos/default/default_product.png',
verbose_name='picture')
active = models.BooleanField(default = True)
category = models.CharField(max_length=50, null=True, choices=categories)
def __str__(self):
return self.name
class Meta:
#verbose_name = 'name'
ordering = ['-name']
最后在 products.html 中:
{% block content %}
{% comment "" %}{{pro}}{% endcomment %}
{% for product in pro %}
<h1>{{product.name}}</h1>
<h1>{{product.content}}</h1>
<h1>{{product.price}}</h1>
</img src="{{product.image}}" alt="">
<h1>-----------------------------------</h1>
{% endfor %}
{% endblock content %}
uj5u.com熱心網友回復:
試試這個。請注意,要獲取影像,您必須訪問 .url
{% block content %}
{% comment "" %}{{pro}}{% endcomment %}
{% for product in pro %}
<h1>{{product.name}}</h1>
<h1>{{product.content}}</h1>
<h1>{{product.price}}</h1>
<img src="{{ product.image.url }}" alt=""/>
<h1>-----------------------------------</h1>
{% endfor %}
{% endblock content %}
uj5u.com熱心網友回復:
您的img標簽中有錯字
更改此行
</img src="{{product.image}}" alt="">
到
<img src="{{ product.image.url }}" alt=""/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404795.html
標籤:
上一篇:如何列出同一日期的物件?
下一篇:在Django的視圖中編輯專案
