如何将request.user传递给模型的cleankey unique_together validation的clean方法?

时间:2014-12-09 06:12:09

标签: django forms validation unique

我尝试运行验证,其中用户无法两次输入相同的name_field,但输入相同名称的其他用户不会干扰。 我尝试使用" unique_together =(("用户名"," name_field"))"但是当用户输入两次相同的值时,服务器会生成完整性错误,而不是在表单字段旁边显示警告消息。

然后我尝试覆盖模型中的clean()方法,如果我只检查" field_name"像这样:

def clean(self):
    existing = self.__class__.objects.filter(
                            name_field=self.name_field).count()
    if existing > 0:
        raise ValidationError({'name_field':self.username })

但是在检查用户名值时遇到了麻烦,例如:

def clean(self):
    existing = self.__class__.objects.filter(
                            username=self.username,  ###This part crashes!!! (username not found)
                            name_field=self.name_field).count()
    if existing > 0:
        raise ValidationError({'name_field':self.username })

我猜测是因为它不是表单中的实际字段,在调用clean()期间它不存在。所以我的问题是我是否正确地为这类问题进行了验证?我如何通过或在哪里可以从模型清理方法中找到当前用户的值(希望以安全的方式在不向表单添加字段的情况下)?

views.py

def add_stuff(request):
    if request.user.is_authenticated():
        form = addStuff(request.POST or None)
        if request.method == 'POST':
            if form.is_valid():
                sub_form = form.save(commit=False)
                sub_form.username = request.user
                sub_form.save()
                return redirect('../somewhere_else/')

forms.py

class addStuff(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(addStuff, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
                                'name_field',
                                'type_field',
                       ButtonHolder(
                                Submit('Save', 'Save')
                                   ),
        )

    class Meta:
        model = UserStuff
        fields = ('name_field',
                  'type_field',
                 )

models.py

class UserStuff(models.Model):
    username                         = models.ForeignKey(User)
    name_field                       = models.CharField(max_length=24, blank=False,null=False)
    type_field                       = models.CharField(max_length=24, blank=True,null=True)

    def clean(self):
        existing = self.__class__.objects.filter(
                                username=self.username,  ###This part crashes!!! (username not found)
                                name_field=self.name_field).count()
        if existing > 0:
            raise ValidationError({'name_field':self.username })

    def __unicode__(self):
        return "%s For User: \"%s\" " % (self.name_field, self.username)

    class Meta:
        managed = True
        db_table = 'my_db_table'
        unique_together = (("username","name_field"))

感谢您的任何见解!

1 个答案:

答案 0 :(得分:0)

我现在正在从表单而不是模型运行干净覆盖(由Daniel推荐)。这解决了一系列问题,现在我有一个工作概念:

models.py

class UserStuff(models.Model):
    username                         = models.ForeignKey(User)
    name_field                       = models.CharField(max_length=24, blank=False,null=False)
    type_field                       = models.CharField(max_length=24, blank=True,null=True)

    def clean(self):
        existing = self.__class__.objects.filter(
                                username=self.username,  ###This part crashes!!! (username not found)
                                name_field=self.name_field).count()
        if existing > 0:
            raise ValidationError({'name_field':self.username })

    def __unicode__(self):
        return "%s For User: \"%s\" " % (self.name_field, self.username)

    class Meta:
        managed = True
        db_table = 'my_db_table'

forms.py

class addStuff(forms.ModelForm):  
    def __init__(self, *args, **kwargs):
        super(addStuff, self).__init__(*args, **kwargs)
        initial = kwargs.pop('initial')
        self.username = initial['user']
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
                                'name_field',
                                'type_field',
                       ButtonHolder(
                                Submit('Save', 'Save')
                                   ),
        )
    def clean(self):
        cleaned_data = super(addStuff, self).clean()
        name_field = self.cleaned_data['name_field']
        obj = UserStuff.objects.filter(username_id=self.username.id,
                                       name_field=name_field,
                                      )
        if len(obj) > 0:
            raise ValidationError({'name_field': 
                  "This name already exists!" }  ) 
        return cleaned_data
    class Meta:
        model = UserStuff
        fields = ('name_field',
                  'type_field',
                 )

views.py

def add_stuff(request):
    if request.user.is_authenticated():
        form = addStuff(request.POST or None,
                        initial={'user':request.user})
        if request.method == 'POST':
            if form.is_valid():
                sub_form = form.save(commit=False)
                sub_form.username = request.user
                sub_form.save()
                return redirect('../somewhere_else/')
祝你好运!