简体   繁体   English

Django form.is_valid() 返回 false

[英]Django form.is_valid() returning false

I am trying to update an instance from Author table, But form.is_valid returning false always.我正在尝试从 Author 表中更新一个实例,但 form.is_valid 总是返回 false。

I have added enctype="multipart/form-data" in the template form, In the views im getting files also, but form is not validating.我在模板表单中添加了 enctype="multipart/form-data" ,在视图中我也在获取文件,但表单没有验证。

Am I missing anything?我错过了什么吗?

This is views section.这是视图部分。

def update(request,something,id):
something=str(something).lower()
if something=='author':
    author=Author_model.objects.get(id=id)
    if request.method=='GET':
        return render(request,'update_author.html',{'author':author})
    else:
        form = Author_form(request.POST, request.FILES,instance=author)
        print('form.is_valid()',form.is_valid())
        if form.is_valid():
            image_path = author.image_document.path
            if os.path.exists(image_path):
                os.remove(image_path)
            form.save()
        return redirect('http://127.0.0.1:8000/bookdb/author/')

This is a template.这是一个模板。

<form action="" method="post" enctype="multipart/form-data">
        <center>
            <h2>Update Author</h2><hr>
            <table>
                <tr>
                    <td>Solutation </td>
                    <td>: <select name="" id="">
                        <option value="{{author.solutaion}}">{{author.solutaion}}</option>
                        <option value="Mr">Mr</option>
                        <option value="Ms">Ms</option>
                        <option value="Dr">Dr</option>
                    </select></td>
                </tr>
                <tr><td >Name </td>
                <td>: <input type="text" value="{{author.name}}"></td></tr>
                <tr>
                    <td>Email </td>
                    <td>: <input type="email" value="{{author.email}}"></td>
                </tr>
                <tr>
                    <td>Headshot {{author.headshot}}</td>
                    <td><img src="{{author.headshot.url}}" alt="Image not found" width="100" height="60"></td>
                    <td>: <input type="file"></td>
                </tr>
            </table><br>
            <button type="submit">Submit</button>
        </center>
        {%csrf_token%}
    </form>

Author Form:作者表格:

class Author_form(ModelForm):
required_css_class='required'
class Meta:
    model=Author_model
    fields='__all__'

Author model:作者 model:

class Author_model(models.Model):
solutaion=models.CharField(max_length=10)
name=models.CharField(max_length=30)
email=models.EmailField(blank=True)
headshot=models.ImageField(upload_to='imgs')
def __str__(self):
    return self.name

Urls.py网址.py

from django.contrib import admin
from django.urls import path
from model_app import views as v
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('bookdb/<something>/',v.show_something),
    path('publishers/<name>/',v.a_publisher),
    path('publishers/<name>/<id>/',v.req_cols),
    path('books/',v.books),
    path('books/<name>/',v.book),
    path('book_one/<title>/',v.book_one),
    path('book_with_publisher/<title>/<pub>/',v.book_with_publisher),
    path('Add/<someone>/',v.user_form),
    path('delete/<something>/<id>/',v.delete_item),
    path('update/<something>/<id>/',v.update)
]
urlpatterns += staticfiles_urlpatterns()

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

You have customize your form inputs so they can not match with your form fields in server-side!您已经自定义了form inputs ,因此它们无法与服务器端的form fields匹配!
So form_valid() is always False .所以form_valid()总是False
I update your template:我更新你的模板:

  <form action="" method="post" enctype="multipart/form-data">
            <center>
                <h2>Update Author</h2><hr>
                <table>
                    <tr>
                        <td>Solutation </td>
                        <td>: <select name="solutaion" id="" >
                            <option value="{{author.solutaion}}">{{author.solutaion}}</option>
                            <option value="Mr">Mr</option>
                            <option value="Ms">Ms</option>
                            <option value="Dr">Dr</option>
                        </select></td>
                    </tr>
                    <tr><td >Name </td>
                    <td>: <input type="text" value="{{author.name}}" name="name"></td></tr>
                    <tr>
                        <td>Email </td>
                        <td>: <input type="email" value="{{author.email}}" name="email"></td>
                    </tr>
                    <tr>
                        <td>Headshot {{author.headshot}}</td>
                        <td><img src="{{author.headshot.url}}" alt="Image not found" width="100" height="60"></td>
                        <td>: <input type="file" name="headshot"></td>
                    </tr>
                </table><br>
                <button type="submit">Submit</button>
            </center>
            {%csrf_token%}
        </form>

Also take a look at your browser DevTools in order to make sure their values before you get a request.还要查看您的浏览器DevTools ,以便在收到请求之前确定它们的值。

Since you are using custom html so you need to set name attributes of your html according to the field name of your model.由于您使用的是自定义 html,因此您需要根据htmlfield名称设置 html 的name属性。 So form.is_valid() always returns False if the name attribute is different or have not mentioned.因此,如果name属性不同或未提及, form.is_valid()总是返回False

<form action="/update/author/{{author.id}}" method="post" enctype="multipart/form-data"> #<--- Here I set `author` in place of `something` add values accordingly
    <center>
        <h2>Update Author</h2><hr>
        <table>
            <tr>
                <td>Solutation </td>
                <td>: <select name="solutaion" id="">
                    <option value="{{author.solutaion}}">{{author.solutaion}}</option>
                    <option value="Mr">Mr</option>
                    <option value="Ms">Ms</option>
                    <option value="Dr">Dr</option>
                </select></td>
            </tr>
            <tr><td >Name </td>
            <td>: <input type="text" name="name" value="{{author.name}}"></td></tr>
            <tr>
                <td>Email </td>
                <td>: <input type="email" name="email" value="{{author.email}}"></td>
            </tr>
            <tr>
                <td>Headshot {{author.headshot}}</td>
                <td><img src="{{author.headshot.url}}" alt="Image not found" width="100" height="60"></td>
                <td>: <input type="file" name="headshot"></td>
            </tr>
        </table><br>
        <button type="submit">Submit</button>
    </center>
    {%csrf_token%}
</form>

Could you show your form class?您能出示您的表格 class 吗? In the case the problem is with form validation, it's important to share.如果问题出在表单验证上,那么分享很重要。

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

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