简体   繁体   English

Django ImageField 不上传图像

[英]Django ImageField not uploading the image

I'm developing a simple game webstore.我正在开发一个简单的游戏网上商店。 The idea is that developers can upload games that will be displayed on an iframe (so the games are simply just URLs) and then they can be played.这个想法是开发人员可以上传将在 iframe 上显示的游戏(因此游戏只是 URL),然后可以播放它们。

The problem is, when publishing a game, the icon image does not get uploaded.问题是,发布游戏时,图标图像没有上传。 So the image cannot be displayed.所以无法显示图像。

The Game model:游戏模型:

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)

I use a Django ModelForm:我使用 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'
            }),
        }

The form is generated simply like this:表单的生成方式如下:

<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>

This is my view that is used here:这是我在这里使用的观点:

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})

The URL of the image is correct, but the image itself does not get uploaded.图片的 URL 是正确的,但图片本身没有上传。 Even if I manually move the image there, it won't be displayed if I put it as the source for and image on html.即使我手动将图像移动到那里,如果我将其作为 html 上的图像和图像的源,它也不会显示。

On settings.py I have the following lines:在 settings.py 我有以下几行:

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

How can I fix this?我该如何解决这个问题?

You need to add static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urlpattern:您需要将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)

See details here .在此处查看详细信息。

There are multiple things that you should check when the image isn't showing/saving.当图像未显示/保存时,您应该检查多项内容。

  • 1 - You're missing a request.FILES parameter. 1 - 您缺少 request.FILES 参数。

    2 - You've made changes to the model but haven't made migrations yet. 2 - 您已对模型进行了更改,但尚未进行迁移。

    3 - Django couldn't create a folder to place the images in(never faced this problem) 3 - Django 无法创建一个文件夹来放置图像(从未遇到过这个问题)

    4 - There's a typo in your HTML form; 4 - 您的 HTML 表单中存在拼写错误; especially here: enctype="multipart/form-data" ;尤其是这里: enctype="multipart/form-data" (I once wrote multipart/form instead of multipart/form-data)

    5 - If you're using some old Django version then you'd have to manually add the following code in your urls.py file: python urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 5 - 如果您使用的是旧 Django 版本,则必须在urls.py文件中手动添加以下代码: python urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

    6 - There's always a possibility that your filename is extremely lengthy and it causes some unexpected behavior. 6 - 总是有可能您的文件名非常长并且会导致一些意外行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM