2

我有几个具有类似 validate_unique 覆盖的模型,如在这个问题中。这是在models.py中:

class TeachingGroup(models.Model):
    cohort = models.ForeignKey(Cohort)
    name = models.CharField(max_length=26)
    slug = models.CharField(max_length=30, editable=False)

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

    def validate_unique(self, exclude = None):
        from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
        slugfodder = u'%s %s' % (self.cohort.year_group.shortname, self.name)
        self.slug = slugify(slugfodder)
        options = dict(slug = self.slug, cohort__year_group__school = self.cohort.year_group.school)
        hits = TeachingGroup.objects.exclude(pk=self.pk).filter(**options)
        if hits.exists():
            template = """The name is used for database lookups,
                and '{0}' is too similar to '{1}', as both become
                '{2}' in your web browser's address bar."""
            message = template.format(self.name, hits[0].name, self.slug)
            raise ValidationError({NON_FIELD_ERRORS: [message]})
        super(TeachingGroup, self).validate_unique(exclude=exclude)

我没有足够的声誉在那里发表评论,但似乎通过super在末尾添加该行我并没有绕过模型的Meta: unique_together验证。

为简洁起见,我没有包含我的模型结构,但所有上述验证在管理站点中都可以正常工作,用于更改现有对象(当我将名称设置为足够相似以使 slug 相同时会显示错误)以及添加新对象。

在呈现的网页中,我在更改现有记录时按预期收到错误消息,但奇怪的是从表单添加新对象(没有实例)时没有。相反,我得到了一系列错误,最终导致:

File "models.py" in validate_unique
  125.         slugfodder = u'%s %s' % (self.cohort.year_group.shortname, self.name)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py" in __get__
  301.                 raise self.field.rel.to.DoesNotExist

在 pdb 中:

-> slugfodder = u'%s %s' % (self.cohort.year_group.shortname, self.name)
(Pdb) self
*** DoesNotExist:

那么管理站点如何管理验证“自我”?我的验证需要做类似的事情save(commit = False)吗?

我当然可以添加更多细节,但我认为相关的是这里。

4

1 回答 1

0

好吧,这里没有功劳:我有一些愚蠢的视图函数,我知道它们不是很干,而且如前所述,结果是愚蠢的。

我迄今为止的标准views.py条目:

def edit_object(request, slug=None):
    try:
        obj = MyModel.objects.get(name=slug)
        if request.method == 'POST':
            if request.POST.get('delete'):
                obj.delete()
                return redirect(list_objects)
            form = MyModelForm(request.POST, request=request, instance=obj)
            if form.is_valid():
                form.save()
                return redirect(list_objects)
        else:
            form = MyModelForm(request=request, instance=obj)
    except MyModel.DoesNotExist:
        if request.method == 'POST':
            form = MyModelForm(request.POST, request=request)
            if form.is_valid():
                form.save()
                return redirect(list_objects)
        else:
            form = MyModelForm(request=request)
    return render_to_response('edit_objects.html', locals(), context_instance=RequestContext(request))

我的新观点.py

def edit_object(request, slug=None):
    if slug:
        options = dict(name = slug)
        obj = get_object_or_404(MyModel, **options)
    else:
        obj = MyModel()
    if request.method == 'POST':
        if request.POST.get('delete'):
            obj.delete()
            return redirect(list_objects)
        form = MyModelForm(request.POST, request=request, instance=obj)
        if form.is_valid():
            form.save()
            return redirect(list_objects)
    else:
        form = MyModelForm(instance=obj, request=request)
    return render_to_response('edit_objects.html', locals(), context_instance=RequestContext(request))

我仍然有一个问题,其中行:

obj = MyModel()

使用 validate_unique 创建错误,但我越来越近了。我用过:

obj = Cohort(year_group = theschool.yeargroup_set.all()[:1].get())

这很丑陋,当没有这样的队列时会抛出异常。

于 2012-04-13T11:30:01.680 回答