0

所以我有一个模型表格 - 这是 django令人难以置信的不直观的模型编辑过程,如果有人有一个可靠的“白痴”教程,我很想听听它!

手头的问题是向 modelForm 字段添加/设置一个值,以便它显示在 html 中。

所以,我的视图逻辑中有这段代码:

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()

这被称为“获取”。所以,在这里,我要么是想展示一个预先完成的表格,要么是一个新的表格!

深入 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

我在哪里获得一个帖子对象,检查它是否属于活动用户,然后为其附加一个新值 - “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 字段,以便我始终知道给定帖子附加到哪个故事!现在,我知道可能有其他方法可以做到这一点 - 我可能能够以某种方式将外键添加为“隐藏”?这是受欢迎的,请告诉我如何!但是我现在真的很想将外键作为隐藏字段,所以请随意提出不同的方式,但也可以回答外键作为隐藏模型表单的问题!

有了上面的所有代码,我想我可以在 html 中使用它(因为我的表单绝对被称为“表单”):

{% for hidden in form.hidden_fields %}
    {{ hidden.errors }}
    {{ hidden }}
{% endfor %}

甚至

{{ form.storyId }}

但这不起作用!storyId 永远不会显示为设定值。

这里发生了什么?

4

1 回答 1

1

您是否尝试过将其传递给构造函数?

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    self.story_id = kwargs.pop('story_id', None)
    super(PostForm, self).__init__(*args, **kwargs)
    self.fields['storyId'].initial = self.story_id
于 2012-06-01T15:30:48.037 回答