验证 Django 中的唯一字段

发布于 11-02 00:19 字数 1315 浏览 3 评论 0原文

我不知道我是否以正确的方式解决这个问题。预期的结果是拥有一个仅显示名称描述的表单。用户提交表单后,我想将当前用户添加为 owner 并检查是否已有具有相同 nameuser 的条目。如果有,我想返回有错误的表格。如果没有,我想保存状态

我的模型:

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 无法使用它code> 函数,因此不能用于检查 nameowner 是否唯一。

I don't know if I'm approaching the problem in the right way. The intended outcome is to have a form that displays only name and description. Once the user submits the form I want to add the current user as owner and check if there's already an entry that has the same name and user. If there is, I want to return the form with errors. If not, I want to save Status.

My model:

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

My View:

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

I have tried numerous things, but I keep running into the problem that if I add owner to the object separately then it isn't available to the model's clean function and therefore can't be used to check if name and owner are unique.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灼痛2024-11-09 00:19:20

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

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

forms.py:views.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

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。

Several ways to do this:

for example, passing in the user (owner) to the form:

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

Also look at setting initial data depending on your form setup and consider using a ModelForm.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文