だから私はモデルフォームを持っています-これはdjangoの信じられないほど直感的でないモデルの編集プロセスのためのものです、そして誰かがしっかりした「ばかのための」チュートリアルを持っているなら、私はそれについて聞きたがっています!
当面の問題は、htmlに表示されるようにmodelFormフィールドに値を追加/設定することです。
だから、私は私のビューロジックにこのコードを持っています:
class EditSaveModel(View):
def get(self,request,id=None):
form = self.getForm(request,id)
return self.renderTheForm(form,request)
def getForm(self,request,id):
if id:
return self.idHelper(request,id)
return PostForm()
これは「get」で呼び出されます。それで、ここで、私は事前に完成したフォームまたは新しいフォームを表示したいと思っています!
idHelperへのドリル:
def idHelper(self,request,id):
thePost = get_object_or_404(Post, pk=id)
if thePost.story.user != request.user:
return HttpResponseForbidden(render_to_response('errors/403.html'))
postForm = PostForm(instance=thePost)
postForm.fields.storyId.value = thePost.story.id **ANY NUMBER OF COMBOS HAVE BEEN TRIED!
return postForm
ここで、postオブジェクトを取得し、それがアクティブユーザーに属していることを確認してから、それに新しい値( "storyId")を付加します。
私も上記を試しました:
postForm.storyId.value = thePost.story.id
しかし、postFormには設定するstoryId値がないことがわかります。
と:
postForm.storyId = thePost.story.id
ただし、これは実際にはstoryIdを設定しません。つまり、htmlには値がありません。
私のPostForm定義を見てみましょう:
class PostForm(forms.ModelForm):
storyId = forms.IntegerField(required=True, widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(PostForm, self).__init__(*args, **kwargs)
class Meta:
model = Post
ordering = ['create_date']
fields = ('post',)
#some validation here!
#associates the new post with the story, and checks that the user adding the post also owns that story
def clean(self):
cleaned_data = super(PostForm, self).clean()
storyId = self.cleaned_data.get('storyId')
storyArray = Story.objects.filter(id=storyId,user=self.request.user.id)
if not len(storyArray): #eh, this means if self.story is empty.
raise forms.ValidationError('Whoops, something went wrong with the story you\'re using . Please try again')
self.story = storyArray[0]
return cleaned_data
そうですね、これは明らかですか?夏に向けて:
PostFormに非表示のstoryIdフィールドを添付して、特定の投稿がどのストーリーに添付されているかを常に把握できるようにします。今、私はこれを行う他の方法があるかもしれないことを知っています-私はどういうわけか「隠された」として外部キーを追加することができるかもしれませんか?それは大歓迎です、方法を教えてください!しかし、私は本当に今すぐ外部キーを非表示フィールドにしたいので、別の方法を自由に提案するだけでなく、非表示modelFormの質問として外部キーにも答えてください!
上記のすべてのコードで、私はこれをhtmlに含めることができると想像します(私のフォームは間違いなく「フォーム」と呼ばれているため):
{% for hidden in form.hidden_fields %}
{{ hidden.errors }}
{{ hidden }}
{% endfor %}
あるいは
{{ form.storyId }}
しかし、これは機能しません!storyIdが設定値として表示されることはありません。
ここで何が起こっているのですか?