2014-10-18 69 views
0

當我提交我的表單我有一個獨特的設置爲我的領域,所以我得到這樣的:唯一字段返回詳細視圖提交

擁有這個全名,國家和出生日期已經存在

如何將它發送給現存的詳細視圖?

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 
+0

什麼,什麼時候「用戶」進入這個? @DanielRoseman – JamesJGarner 2014-10-18 20:47:19

+0

人,不管。重點在於你正在使用創建一個新視圖的視圖,然後抱怨你正在獲得唯一性錯誤。只是不要創建一個新的。 – 2014-10-18 20:50:30

+0

但是,如果它不存在,我希望它創建對象?如果我不應該使用CreateView,我應該使用什麼? @DanielRoseman – JamesJGarner 2014-10-18 20:52:01

回答

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

如果你想重定向到的DetailView現有的對象,而試圖保存新的對象,你應該重寫清潔方法在你的ModelForm類,像這樣:

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 
相關問題