You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PythonAnywhere上的Django应用中为不同投票问题添加不同图片?

实现每个投票问题对应独立图片的方案

嘿,这个需求其实很常见,咱们一步步来搞定它:

1. 给Question模型添加图片字段

首先得让每个投票问题能关联自己的图片,这需要修改polls/models.py里的Question模型,同时要先安装处理图片依赖的Pillow库:

pip install pillow

然后更新模型代码:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    # 添加图片字段,upload_to指定图片存储的子路径(相对于后续配置的MEDIA_ROOT)
    image = models.ImageField(upload_to='poll_images/', blank=True, null=True)

    def __str__(self):
        return self.question_text

blank=True, null=True是为了允许暂时不给问题设置图片,后续可以补充。

2. 配置媒体文件路径

打开项目根目录的settings.py,添加媒体文件相关配置(注意PythonAnywhere要写绝对路径):

import os

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # 本地开发用这个
# PythonAnywhere上要改成实际路径,比如:/home/你的用户名/你的项目名/media
# MEDIA_ROOT = '/home/martina/my_poll_app/media'
MEDIA_URL = '/media/'

因为PythonAnywhere是生产环境,Django默认不会自动提供媒体文件的访问服务,所以要在项目的wsgi.py里补充配置:

from django.conf import settings
from django.conf.urls.static import static
from django.core.wsgi import get_wsgi_application

application = get_wsgi_application()

# 让生产环境能访问媒体文件
if not settings.DEBUG:
    application = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)(application)

3. 更新数据库

模型修改后,需要执行迁移来同步数据库表结构:

python manage.py makemigrations
python manage.py migrate

4. 给问题上传对应图片

现在你可以通过Django admin后台(如果已经配置),找到每个Question对象,上传对应的图片——比如给id=1的问题传图片1,id=2的问题传图片2。如果admin里看不到图片上传选项,记得在polls/admin.py里更新注册配置:

from django.contrib import admin
from .models import Question

class QuestionAdmin(admin.ModelAdmin):
    fields = ['pub_date', 'question_text', 'image']

admin.site.register(Question, QuestionAdmin)

5. 修改模板动态渲染图片

你的detail视图应该已经在传递对应Question对象了(比如下面这样):

# polls/views.py
from django.shortcuts import get_object_or_404, render
from .models import Question

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

接下来修改polls/detail.html,把原来固定的图片链接改成动态渲染当前问题的图片:

<!-- 替换原来的固定图片代码 -->
{% if question.image %}
    <img src="{{ question.image.url }}" alt="{{ question.question_text }}">
{% else %}
    <!-- 可选:没有图片时显示默认图 -->
    <img src="/static/polls/default.jpg" alt="默认投票图片">
{% endif %}

这样一来,访问polls/1就会显示id=1的问题对应的图片,polls/2则显示id=2的问题图片啦!

内容的提问来源于stack exchange,提问作者Martina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:23:37