验证Django中的唯一字段

时间:2011-04-17 00:15:36

标签: django unique save

我不知道我是否正在以正确的方式解决问题。目标结果是使表单仅显示namedescription。用户提交表单后,我想将当前用户添加为owner,并检查是否已存在具有相同nameuser的条目。如果有,我想返回有错误的表单。如果没有,我想保存Status

我的模特:

class Status(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    owner = models.ForeignKey(User)
    active = models.BooleanField(default=True)

    class Meta:
        unique_together = ('name','owner')

我的观点:

def settings_status(request):
    status_form = StatusForm()

    if request.method == 'POST':
        status_form = StatusForm(request.POST)
            if status_form.is_valid():
                new_status = Status()
                new_status.name = status_form.cleaned_data['name']
                new_status.description = status_form.cleaned_data['description']
                new_status.owner = request.user
                new_status.save()

    return render_to_response('base/settings_status.html',{
        'status_form'           :       status_form,
}, context_instance=RequestContext(request))

我尝试了很多东西,但是我一直遇到这样的问题:如果我将owner分别添加到对象中,那么模型的clean函数就无法使用它,因此不能用于检查nameowner是否唯一。

1 个答案:

答案 0 :(得分:5)

有几种方法可以做到这一点:

例如,将用户(所有者)传递给表单:

forms.py:

class StatusForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user','')
        super(StatusForm, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.CharField(label='Name')
        self.fields['description'] = CharField(label='Description', widget=forms.Textarea)

    def clean(self):
        cleaned_data = self.cleaned_data
        name = cleaned_data.get('name')

        if Status.objects.filter(name=name, owner=self.user).exists():
            self._errors['name'] self.error_class(['Status with this name exists'])  

        return cleaned_data

views.py:

def settings_status(request):

    if request.method == 'POST':
        status_form = StatusForm(request.POST, user=request.user)
            if status_form.is_valid():
                new_status = Status()
                new_status.name = status_form.cleaned_data['name']
                new_status.description = status_form.cleaned_data['description']
                new_status.owner = request.user
                new_status.save()
    else:
        status_form = StatusForm(user=request.user)

    context = {'status_form':status_form,}

    return render_to_response('base/settings_status.html', context,
                context_instance=RequestContext(request))

另请参阅根据表单设置设置初始数据,并考虑使用ModelForm。