简体   繁体   English

将图像上传到 Django 中的 ModelForm 中?

[英]Uploading image into ModelForm in Django?

I am having trouble uploading an image into with a form through Django.我无法通过 Django 将图像上传到表单中。 The file does not appear in my `templates/auctions' directory, nor does it render in my template (probably because it never uploaded).该文件没有出现在我的`templates/auctions' 目录中,也没有出现在我的模板中(可能是因为它从未上传过)。

In my views.py :在我的views.py

@login_required(login_url="login")
def createListing(request):
    if request.method == "POST":
        filled_form = CreateListing(request.POST, request.FILES)
        if filled_form.is_valid():
            user = User.objects.get(username=request.user)
            
            new_listing = filled_form.save(commit=False)
            new_listing.listed_by = user
            new_listing.save()
            return HttpResponseRedirect(reverse("index"))
        else:
            context = {
        "createlistingform": filled_form
    }    
    else:
        context = {
            "createlistingform": CreateListing()
        }

    return render(request, "auctions/createlisting.html", context)

I tried to replicate the approach in"Handing uploads with a file" and it's still not working.我试图复制“使用文件处理上传”中的方法,但它仍然无法正常工作。

My AuctionListing model in models.py has this field:我在models.py AuctionListing模型有这个字段:

image = models.ImageField(blank=True, upload_to="images/")

and my project file settings.py has this configuration:我的项目文件settings.py具有以下配置:

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

Is my commit=False in the views.py creating an issue?我在views.py中的commit=False是否创建了问题?

From the link you shared,从您分享的链接中,

Note that request.FILES will only contain data if the request method was POST, at least one file field was actually posted, and the that posted the request has the attribute enctype="multipart/form-data".请注意,如果请求方法是 POST,则 request.FILES 将只包含数据,至少一个文件字段被实际发布,并且发布请求的具有属性 enctype="multipart/form-data"。 Otherwise, request.FILES will be empty.否则, request.FILES 将为空。

Also use commit = False when you get most of your model data from a form, but need to populate some null=False fields with non-form data.当您从表单中获取大部分模型数据时,也可以使用 commit = False,但需要使用非表单数据填充一些 null=False 字段。

Figured it out, my form in createlisting.html was missing the encoding type.想通了,我在createlisting.html中的表单缺少编码类型。

<form enctype="multipart/form-data" action="{% url 'createlisting' %}" method="post">
    {% csrf_token %}
    {{ createlistingform }}
    <input type="submit">
</form>

This fixed the problem!这解决了问题!

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

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