在Models.py中,
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length= 100)
pub_date = models.DateTimeField('Date Is Published')
image = models.ImageField(upload_to="Question_Image", blank=True)
def __str__(self):
return self.question_text
class Choice(models.Model):
choice_text = models.CharField(max_length= 200)
votes = models.IntegerField(default= 0)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
def __str__(self):
return self.choice_text
在settings.py中,我添加了
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite/media')
在mysite / urls.py中
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls', namespace= "polls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
在index.html中,
{% extends 'polls/base.html' %}
{% block main_content %}
{% if latest_questions %}
<ul>
{% for question in latest_questions %}
<li><a href={% url 'polls:detail' question.id %}>
<b>{{question.question_text}}</b>
<img src="{{question.question_text.image.url}}">
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p> You have no questions. Please add some.</p>
{% endif %}
{% endblock %}
但似乎没有上传图像,这是我想添加到YouTube上的“我的第一个django应用程序”视频创建的民意调查应用程序。请帮忙。
改变这个:
<img src="{{question.question_text.image.url}}">
对于以下一个:
<img src="{{question.image.url}}">