Unique Fields返回表单提交的详细信息视图

时间:2014-10-18 20:33:09

标签: python django

当我提交表单时,我的字段有一个独特的设置,所以我明白了:

  

具有此全名,国家和出生日期的人已存在

如何让它将我发送到现有的详细信息视图?

class Person(models.Model):
full_name = models.CharField(
    max_length=50,
    )
country = models.ForeignKey(
    Country,
    default='FIXED',
    )

date_of_birth = models.DateField(
    null=True,
    )
def __unicode__(self):
    return self.full_name

class Meta:
    unique_together = (("full_name", "country", "date_of_birth"),)

@models.permalink
def get_absolute_url(self):
        return ("checker:detail", (), {
            "pk": self.pk
        })

Views.py

class PersonTest(CreateView):
    model = Person


class PersonTestDetail(DetailView):
    model = Person

2 个答案:

答案 0 :(得分:0)

如果要重定向到DetailView现有对象,在尝试保存新对象时,应该覆盖ModelForm类中的clean方法,如下所示:

class YourForm(forms.ModelForm):
    class Meta:
        model = Person

    def clean(self):
        cleaned_data = self.cleaned_data

        full_name = cleaned_data.get("full_name")
        country = cleaned_data.get("country")
        date_of_birth = cleaned_data.get("date_of_birth")

        if Person.objects.filter(full_name=full_name, country=country, date_of_birth=date_of_birth).count() > 0:
            del cleaned_data["full_name"]
            del cleaned_data["country"]
            del cleaned_data["date_of_birth"]

            person_pk = Person.objects.get(full_name=full_name, country=country, date_of_birth=date_of_birth).pk

            return HttpResponseRedirect(reverse('checker:detail', args=[person_pk]))

        return cleaned_data

然后更新您的CreateView:

class PersonTest(CreateView):
    model = Person
    form_class = YourForm

答案 1 :(得分:0)

这是我想出的自己的灵魂

class PersonTest(CreateView):
    model = Person

    def form_invalid(self, form):
        try:
            person = Person.objects.get(full_name=form.cleaned_data['full_name'], date_of_birth=form.cleaned_data['date_of_birth'], country=form.cleaned_data['country'])
            return HttpResponseRedirect(reverse('checker:detail', kwargs={'pk': person.id}))
        except:
            return super(ModelFormMixin, self).form_invalid(form)   
相关问题