Django:如何在验证之前将数据添加到ModelForm子类中? [英] Django: How do I add data to a ModelForm subclass before validation?

查看:29
本文介绍了Django:如何在验证之前将数据添加到ModelForm子类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为Django中表单验证的一部分,我想检查用户上次发布信息的时间.

As part of a form validation in Django, I want to check when a user last made a post.

我看过关于stackoverflow的问题,该问题似乎可以解决此问题,并且最初使用了已接受的答案

I've had a look at this, and this question on stackoverflow, which appear to address this issue, and initially used the accepted answer here. Essentially the process at the moment has been to add the request.user object during the

def form_valid(self, form):

CreateView子类的

方法.但是,这不允许在表单验证期间使用用户变量.

method of the CreateView subclass. However, this doesn't allow the user variable to be used during form validation.

由于我想在验证期间访问用户变量,因为自上次发布以来的检查时间在逻辑上是验证,所以我需要将用户变量更早地注入表单.

Since I want to access the user variable during validation, as the check on time since last post is logically validation, I need the user variable injected to the form earlier.

我尝试更改get_initial()方法:

I've tried altering the get_initial() method:

def get_initial(self):
    initial = super(ArticleCreateView, self).get_initial()
    initial['user'] = self.request.user
    return initial

这成功地在初始字典中设置了['user']键,但这从未使它通过清理过程,清理过程仅处理['data']字典中的内容,并删除了所有内容.我已将用户故意从表单显示中排除,但这似乎也将其从清理过程和验证中删除.

This successfully sets the ['user'] key in the initial dictionary, but this never makes it through the cleaning process, which deals only with the stuff in the ['data'] dictionary, and removes anything in initial. I've deliberately excluded user from the form display, but this appears to also remove it from the cleaning process and validation.

是重写Form的 init ()方法和视图的get_initial()方法的正确方法,将"user"放入初始,然后拉动表单从首字母到表格中的其他信息都来自 init ()?

Is the correct way to do this to override the init() method of the Form, and the get_initial() method of the view, putting 'user' into initial, and then the form pulling the extra information from initial into the form at init()?

我希望将request.user传递给表单,然后可以在整个表单范围内的clean()方法中对其进行访问以进行额外的检查,这相当于验证.

I'm looking to pass the request.user to the form, and then I can access it within the form-wide clean() method to do the additional checks, which amount to validation.

def clean(self):
    super(ArticleForm, self).clean()
    **check whether user has posted recently, if so, raise ValidationError**
    return self.cleaned_data

J

推荐答案

我目前解决此问题的方法是将验证保留在表单中,并将其余业务逻辑保留在视图中.因此,我完成了以下操作:

The way I've solved this at the moment is to keep validation within the form, and the rest of the business logic in the view. Consequently, I've done the following:

在视图中:

def get_initial(self):
    initial = super(MyCreateView, self).get_initial()
    initial['user'] = self.request.user
    return initial

采用以下形式:

def __init__(self, *args, **kwargs):
    self.user = kwargs['initial']['user']
    super(MyObjectForm, self).__init__(self, *args, **kwargs)

def clean(self):
    # Clean all the submitted data
    super(MyObjectForm, self).clean()

    # Validate that the user submitted > n time ago
    profile = self.user.get_profile()

    if datetime.now() - profile.lastpost < timedelta(hours=1)
        raise forms.ValidationError("Need to wait longer than n=1 hours")
    else:
        self.cleaned_data['user'] = self.user

    return self.cleaned_data

哪种方法可行-该解决方案中没有我没有发现的缺陷吗?

Which seems to work - are there any flaws I haven't seen with this solution?

这篇关于Django:如何在验证之前将数据添加到ModelForm子类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆