django is_valid()は、フォームを送信するときにValueErrorをスローします。理由がわかりません

StackOverflow https://stackoverflow.com/questions/5370874

質問

次のコードは、モデルに基づいてフォームを作成します。 Post. 。私が直面している問題は、フォームが検証されず、与えることです ValueError それ データは検証しませんでした 削除した場合 if post_form.is_valid(): 小切手。

ただし、以下に示すようにコードを保持している場合、つまり、 if post_form.is_valid(): チェックしてから、常に失敗します else ブロックが実行されます。

私のモデルでは、Djangoの認証のforeignkeyであるユーザーを保存しようとしていました。

どんな助けも感謝します。ありがとう。

#----------------------------Model-------------------------------------- 
class Post (models.Model): 
    name = models.CharField(max_length=1000, help_text="required, name of the post") 
    user = models.ForeignKey(User, unique=False, help_text="user this post belongs to") 

    def __unicode__(self): 
        return self.name 

class PostForm(ModelForm): 
    class Meta: 
            model = Post 
#----------------------------./Model--------------------------------------

#----------------------------View-------------------------------------- 
@login_required 
def create_post (request): 
    if request.method == 'POST': 
        post_form = PostForm(request.POST) 
        if post_form.is_valid(): 
            post.save() 
            return render_to_response('home.html') 
        else: 
            return HttpResponse('not working') 
    else: 
        post_form = PostForm() 
        return render_to_response('create.html', {'post_form':post_form }) 
#----------------------------./View--------------------------------------

#----------------------------./Template--------------------------------------
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>home</title>
</head>
<body>
<form method="POST" action='.'>{% csrf_token %}
    <p>{{post_form.name.label_tag}}</p>
    <p>{{post_form.name}}</p>
        <p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>
#----------------------------./Template--------------------------------------
役に立ちましたか?

解決

他の投稿では、自動的に挿入しようとしていました user フィールド、それはおそらくあなたが持っていないことを意味します user テンプレートに表示されるフィールド。

とにかくユーザーを挿入する予定がある場合は、それを除外してください。

class PostForm(ModelForm): 
    class Meta: 
            model = Post 
            exclude = ('user',) # exclude this

if request.method == 'POST': 
    post_form = PostForm(request.POST) 
    if post_form.is_valid(): 
        post = post.save(commit=False) 
        post.user = request.user
        post.save()  # now post has a user, and can actually be saved.
        return render_to_response('home.html') 

他のヒント

フォームが有効ではないため、無効に表示されません。おそらく、フォームを提出した人は、必要なフィールドに記入しなかったでしょう。の値を表示する場合 form.errors あなたはその理由がわかります。

あるいは、テンプレートを表示していないため、推測する必要がありますが、テンプレート自体に必要なすべてのフィールドを含めていないため、フォームが有効になることはありません。

最初を削除します else そのhttpresponseを備えた条項。その後、ビューはデフォルトでフォームを再度表示し、エラーが完了します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top