python Django 表单在唯一字段上的验证失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/526457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:18:36  来源:igfitidea点击:

Django form fails validation on a unique field

pythondjango

提问by Andrei Taranchenko

I have a simple model that is defined as:

我有一个简单的模型,定义为:

class Article(models.Model):
    slug  = models.SlugField(max_length=50,  unique=True)
    title = models.CharField(max_length=100, unique=False)

and the form:

和形式:

class ArticleForm(ModelForm):
    class Meta:
       model = Article

The validation here fails when I try to update an existing row:

当我尝试更新现有行时,此处的验证失败:

 if request.method == 'POST':
     form = ArticleForm(request.POST)

     if form.is_valid(): # POOF
         form.save()

Creating a new entry is fine, however, when I try to update any of these fields, the validation no longer passes.

创建一个新条目很好,但是,当我尝试更新这些字段中的任何一个时,验证不再通过。

The "errors" property had nothing, but I dropped into the debugger and deep within the Django guts I saw this:

“errors”属性没有任何内容,但我进入调试器并深入 Django 胆量,我看到了这一点:

slug: "Article with this None already exists"

slug:“带有此 None 的文章已经存在”

So it looks like is_valid() fails on a unique value check, but all I want to do is updatethe row.

所以看起来 is_valid() 在唯一值检查中失败,但我想要做的就是更新行。

I can't just do:

我不能只做:

form.save(force_update=True)

... because the form will fail on validation.

...因为表单将在验证时失败。

This looks like something very simple, but I just can't figure it out.

这看起来很简单,但我就是想不通。

I am running Django 1.0.2

我正在运行 Django 1.0.2

What croaks is BaseModelForm.validate_unique() which is called on form initialization.

什么是在表单初始化时调用的 BaseModelForm.validate_unique() 。

回答by Johan

I don't think you are actually updating an existing article, but instead creating a new one, presumably with more or less the same content, especially the slug, and thus you will get an error. It is a bit strange that you don't get better error reporting, but also I do not know what the rest of your view looks like.

我不认为您实际上是在更新现有文章,而是创建了一篇新文章,大概内容或多或少相同,尤其是 slug,因此您会得到错误。你没有得到更好的错误报告,这有点奇怪,但我也不知道你的视图的其余部分是什么样的。

What if you where to try something along these lines (I have included a bit more of a possible view function, change it to fit your needs); I haven't actually tested my code, so I am sure I've made at least one mistake, but you should at least get the general idea:

如果您可以按照这些方式尝试一些东西怎么办(我已经包含了更多可能的视图函数,请对其进行更改以满足您的需要);我还没有真正测试过我的代码,所以我确定我至少犯了一个错误,但你至少应该得到一个大致的想法:

def article_update(request, id):
   article = get_objects_or_404(Article, pk=id)

   if request.method == 'POST':
      form = ArticleForm(request.POST, instance=article)

      if form.is_valid():
         form.save()

         return HttpResponseRedirect(to-some-suitable-url)

   else:
      form = ArticleForm(instance=article)

   return render_to_response('article_update.html', { 'form': form })

The thing is, as taurean noted, you should instantiate your model form with the object you wish to update, otherwise you will get a new one.

事情是,正如 taurean 指出的,你应该用你想要更新的对象实例化你的模型表单,否则你会得到一个新的。

回答by mcwong

I was also searching for a way to update an existing record, even tried form.save(force_update=True)but received errors?? Finally by trial & error managed to update existing record. Below codes tested working. Hope this helps...

我也在寻找一种更新现有记录的方法,甚至尝试过form.save(force_update=True)但收到错误?最后通过反复试验设法更新现有记录。下面的代码测试工作。希望这可以帮助...

models.py from djangobook

来自 djangobook 的 models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)

    last_name = models.CharField(max_length=40)

    email = models.EmailField(blank=True, verbose_name='e-mail')

    objects = models.Manager()

    sel_objects=AuthorManager()

    def __unicode__(self):
        return self.first_name+' '+ self.last_name

class AuthorForm(ModelForm):
    class Meta:
        model = Author


# views.py
# add new record

def authorcontact(request):

    if request.method == 'POST':

        form = AuthorForm(request.POST)

        if form.is_valid():

            form.save()

            return HttpResponseRedirect('/contact/created')

    else:

        form = AuthorForm()

    return render_to_response('author_form.html', {'form': form})

update existing record

更新现有记录

def authorcontactupd(request,id):

    if request.method == 'POST':

        a=Author.objects.get(pk=int(id))

        form = AuthorForm(request.POST, instance=a)

        if form.is_valid():

            form.save()

            return HttpResponseRedirect('/contact/created')

    else:
        a=Author.objects.get(pk=int(id))

        form = AuthorForm(instance=a)

    return render_to_response('author_form.html', {'form': form})

回答by simplyharsh

All i can guess is that you are getting an object to fill a form, and trying to save it again.

我所能猜测的是,您正在获取一个对象来填写表单,并尝试再次保存它。

Try using a ModelForm, and intantiate it with desired object.

尝试使用 ModelForm,并用所需的对象对其进行初始化。

回答by Soviut

It appears that your SlugField is returning None and because a null/blank slug already exists somewhere in the database, its giving an 'already exists' error. It seems like your slug field isn't saving correctly at all.

看来您的 SlugField 正在返回 None 并且因为空/空白 slug 已经存在于数据库中的某处,它给出了一个“已经存在”的错误。似乎您的 slug 字段根本没有正确保存。