简体   繁体   English

django 图像给我一个错误“此字段是必需的。”

[英]django image gives me an error "This field is required."

When I send an image to the bank to save, it always returns this message "This field is required."当我将图像发送到银行进行保存时,它总是返回此消息“此字段为必填项”。 but I fill the field with an image but it always returns this error.但我用图像填充该字段,但它总是返回此错误。

Views观点

def criar (request): 
    form = forms_user() 

    if request.method == 'GET':
        return render(request, 'create.html', {'form': form})

    if request.method == 'POST':
        form = forms_user(request.POST, request.FILES )
               
        if form.is_valid():
            form.save()      
            messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
            form_clean = forms_user()
            return render(request, 'create.html', {'form': form_clean})    
            
        else:
            print(form.errors)
            messages.add_message(request, constants.ERROR, f'{form.errors}')
            return render(request, 'create.html', {'form': form}) 

Models楷模

class items(models.Model):

    titulo:models.CharField(max_length=30, blank=False)
    descricao = models.TextField(max_length=50, blank=False)
    usuario = models.CharField(max_length=20, blank=False)
    Preco = models.BooleanField(blank=False)
    royalties = models.PositiveIntegerField(blank=False)
    image = models.ImageField(upload_to='image/', null=True, blank=True)

Forms Forms

class forms_user (forms.ModelForm):
    class Meta:
        model = items
        fields = '__all__'

HTML HTML

<form id="contact" action="" method="post" enctype="multipart/form-data">

  <fieldset>
                  
   <label for="file">Seu arquivo</label>
                    
    {% render_field form.image type="file" id="file" name="myfiles[]" %}                    
                  
   </fieldset>

</form>

Here in the forms I just put the form and the IMG field so it doesn't get too big but the other fields I put everything right.在 forms 中,我只放置了表单和 IMG 字段,因此它不会变得太大,但其他字段我都放置正确。

At first there's a typo in model field titulo it should be = not : .起初在titulo字段标题中有一个拼写错误,它应该是= not :

Secondly, you should always return an HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general, so use following view:其次,你应该总是在处理POST数据后返回一个 HttpResponseRedirect,这个提示并不特定于 Django,它通常是一个很好的 web 实践,所以使用下面的视图:

def criar(request): 
    if request.method == 'GET':
        return render(request, 'create.html', {'form': forms_user()})

    else:
        form = forms_user(request.POST, request.FILES )
               
        if form.is_valid():
            form.save()      
            messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
            return redirect("success")   
            
        else:
            print(form.errors)
            messages.add_message(request, constants.ERROR, f'{form.errors}')
            return render(request, 'create.html', {'form': forms_user()}) 

If you have created modelform then render image field as below, and you can also remove the action attribute as Django by default takes current page route.如果你已经创建了 modelform 然后渲染图像字段如下,你也可以删除action属性,因为 Django 默认采用当前页面路由。

Html: Html:

<form id="contact" method="POST" enctype="multipart/form-data">

  <fieldset>
                  
   <label for="file">Seu arquivo</label>
                    
    {{form.image}}                                    
   </fieldset>
</form>

urls.py网址.py

urlpatterns=[
    path("success/", views.success, name="success")
    ...
]

success.html:成功.html:

<body>
    <h1> The form has been successfully submitted </h1>
</body>

暂无
暂无

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

相关问题 此字段是必需的。 ImageField django 错误 - This field is required. Error with ImageField django 这是必填栏。 Django的 - This field is required. Django 这是必填栏。 Django上的ImageField和FileField出错 - This field is required. Error with ImageField and FileField on Django 带有jquery-fileupload ui的Django引发错误,显示“此字段是必需的。” - Django with jquery-fileupload ui throws error with “This field is required.” DJANGO API POST :“此字段是必需的。” - DJANGO API POST : "This field is required." {&quot;user&quot;:[&quot;此字段是必需的。&quot;]} 在 Django REST 框架中 - {"user":["This field is required."]} in Django REST Framework Django Rest 框架错误:{'user': [ErrorDetail(string='This field is required.', code='required')]} - Django Rest Framework error: {'user': [ErrorDetail(string='This field is required.', code='required')]} 在Django中,我如何更改“此字段是必需的。”到“名称是必需的”? - In Django, how do i change “This field is required.” to “Name is required”? 如何在 Django REST 中引发错误/返回 {&quot;foo&quot;:[&quot;This field is required.&quot;]} 响应 - How to raise an error / return a {"foo":["This field is required."]} response in Django REST 我收到“此字段为必填项”。 使用 Django ModelForm 时网页加载错误 - I am getting “This field is required.” error on load of webpage when using the Django ModelForm
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM