【问题标题】:ImageField not accepting value from html file in DJANGOImageField 不接受来自 DJANGO 中 html 文件的值
【发布时间】:2020-04-04 07:37:02
【问题描述】:

我正在 Django 中制作自定义 CMS 平台。我想上传用户的精选图片。

这是我的forms.py

class CkEditorForm(ModelForm):
    ..........
    ..........
    featuredImage = forms.ImageField(required=True)

我的模型.py

class Post(models.Model):
    ..........
    ..........
    featuredImage = models.ImageField(upload_to="featured_image/")

我的 HTML 模板

 <div class="col-sm-6">
     {{myForm.featuredImage}}
   </div>

我在模板中使用了另一种方法,但它对我不起作用-

<input type="file" name="featuredImage" accept="image/*" required id="id_featuredImage">

注意-图像已通过 Django 管理面板成功上传,但当我尝试通过模板(HTML 文件)上传时无法正常工作

此外,当我使用此方法在 html 中呈现我的表单时,它正在工作

{{myForm.as_p}}

但我想以不同的方式呈现每个表单的输入法。

{{myForm.category}}
{{myForm.tags}}
{{myForm.featuredImage}}

这里是views.py

def postView(request):

    if request.method== "GET":
        form = CkEditorForm()
        return render(request,"post/post.html",{'myForm':CkEditorForm})

    else:
        if request.method == 'POST':         
            form = CkEditorForm(request.POST)            
            if form.is_valid():            
                form.save()
                return render(request,"post/post.html",{'myForm':CkEditorForm})
            else:
                messages.error(request, "Error")
        return render(request,"post/post.html",{'myForm':CkEditorForm})

【问题讨论】:

  • 表单是名为myForms 还是myForm?你说当你使用带有“s”的myForms时它有效
  • 这是 myForm 而不是 myForms。错别字
  • 我编辑了这个问题。这是一个拼写错误。很抱歉
  • 输入是否被渲染?你得到了什么?
  • 上传文件时需要通过request.FILES-form = CkEditorForm(request.POST, request.FILES)

标签: python django django-models django-forms django-templates


【解决方案1】:

我更改了 Views.py,它对我有用...

def postView(request):

    if request.method== "GET":
        form = CkEditorForm()
        return render(request,"post/post.html",{'myForm':CkEditorForm})

    else:
        if request.method == 'POST':         
            form = CkEditorForm(request.POST,request.FILES)            
            if form.is_valid():            
                form.save()
                return render(request,"post/post.html",{'myForm':CkEditorForm})
            else:
                messages.error(request, "Error")
        return render(request,"post/post.html",{'myForm':CkEditorForm})

我只是改变这个。添加 request.FILES 以获取图像数据。

form = CkEditorForm(request.POST,request.FILES)     

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 2015-01-08
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多