Django ImageField没有上传图像

问题描述 投票:0回答:1

我正在开发一个简单的游戏网店。我们的想法是,开发人员可以上传将在iframe上显示的游戏(因此游戏只是网址)然后可以播放。

问题是,在发布游戏时,图标图像不会上传。因此无法显示图像。

游戏模型:

class Game(models.Model):
    name = models.CharField(max_length=255)
    url = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    developer = models.CharField(max_length=255, blank=True, null=True)
    icon = models.ImageField(upload_to="images/", default="images/default_game_img.png")
    description = models.CharField(max_length=255)
    published = models.DateField(auto_now=False, auto_now_add=True)

我使用Django ModelForm:

class PublishForm(forms.ModelForm):
    class Meta:
        model = Game
        fields = ['name', 'description', 'url', 'price', 'icon']
        widgets = {
            'description': Textarea(attrs={
                'cols': 80,
                'rows': 4,
                'class': 'form-control'
            }),
        }

表单生成简单如下:

<form class="form-horizonal" name="uploadform" enctype="multipart/form-data" method="post">
    {% csrf_token %}
        {{ form }}

        <div class="controls">
            <button type="submit" class="btn">Upload</button>
        </div>
    </div>
</form>

这是我在这里使用的视图:

def publish(request):
    if request.method == 'POST':
        form = PublishForm(request.POST, request.FILES)

        if form.is_valid():

            g = form.save(commit=False)
            g.developer = request.user.username

            g.save()

            profile = UserProfile.objects.get(user=request.user)
            profile.owned_games.add(g)
            profile.save()

            return render(request, 'shop/published.html')

    else:
        form = PublishForm()

    return render(request, 'shop/publish.html', {'form': form})

图像的URL是正确的,但图像本身不会上传。即使我在那里手动移动图像,如果我把它作为html的源和图像,它也不会显示。

在settings.py上,我有以下几行:

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

我怎样才能解决这个问题?

python html django forms
1个回答
2
投票

你需要将static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)添加到urlpattern:

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

查看详情here

© www.soinside.com 2019 - 2024. All rights reserved.