如何在Django上从管理员端上传图像

时间:2017-12-29 18:24:49

标签: python django web

在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应用'视频创建的民意调查应用。 请帮忙。

1 个答案:

答案 0 :(得分:0)

从以下位置更改:

<img src="{{question.question_text.image.url}}">

以下一个:

<img src="{{question.image.url}}">