【问题标题】:Django form, request.post and initialDjango 表单、request.post 和初始
【发布时间】:2012-02-18 03:49:25
【问题描述】:

我有一个 django 表单,我需要为验证目的设置一个值,该值不是作为标准 Post 请求的一部分传入的。

在我的代码中,我目前有这样的内容:

if request.method == 'POST':
        postform = CreatePostForm(request.POST, request.FILES, initial={'post_type':post.post_type})

        if postform.is_valid():
                .....

值 post_type 是一个选择,其值类似于“QUE”

我遇到的问题是这似乎无效。有没有人对如何在验证发生之前将 post_type 值添加到 CreatePostForm 类有任何建议。

请注意,我不想在表单上公开此值,因此不能将其作为帖子的一部分。

【问题讨论】:

  • 'post_type' 是表单上的一个字段吗?如果您至少可以发布您的 CreatePostForm 的字段会有所帮助,这样我们就知道正在运行什么类型的验证。

标签: django forms validation post


【解决方案1】:

一种方法是让它成为你在实例化它时作为参数提交的表单类上的一个属性:

class CreatePostForm(forms.Form/ModelForm):
    def __init__(self, post_type, *args, **kwargs):
        super(CreatePostForm, self).__init__(*args, **kwargs)
        self.post_type = post_type

postform = CreatePostForm(post_type=post.post_type, request.POST, request.FILES)

希望对你有所帮助。

【讨论】:

  • 对我不起作用...您是否错过了 __init__() 中的 self 参数?
  • 呸,你是对的。 init 中的第一个参数应该是 self.
  • 只是出于兴趣,为什么不能把它从 kwargs 中拉出来呢?似乎没有,但我很好奇为什么:)
  • 你可以。你只需要做:post_type = kwargs.pop('post_type', None)之前调用super()
猜你喜欢
  • 1970-01-01
  • 2019-04-04
  • 2010-12-31
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多