我更改了模型的结构,不得不删除并重置数据库以应用迁移。这样做是在停止工作之前保存对象的方式。
我尝试通过使用form.instance而不是self.object来更改方法,但是什么也没发生。我不确定这是否取决于我使用的方法,还是我更改了数据库中的某些内容。我是Django的新手,非常感谢您提供一些建议。
views.py
class SearchCreate(CreateView):
model = Search
form_class = SearchForm
template_name = 'home.html'
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.uuid = self.object.depPlace1 + '&' + self.object.depPlace2 + '&' + str(self.object.depDate) + '&' + str(self.object.retDate)
if not Search.objects.filter(uuid=self.object.uuid, user=self.object.user).exists():
self.object.save()
return super(SearchCreate, self).form_valid(form)
def get_success_url(self):
uuid = self.object.uuid
return reverse('results', kwargs={'uuid': uuid})
models.py
class Search(models.Model):
depPlace1 = models.CharField(max_length=10)
depPlace2 = models.CharField(max_length=10)
depDate = models.DateField()
retDate = models.DateField()
user = models.ForeignKey(User, on_delete = models.CASCADE)
uuid = models.CharField(primary_key=True, max_length=200, default="SEARCH")
range1 = models.IntegerField(blank=True, null=True)
range2 = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.uuid
class SearchForm(forms.ModelForm):
def clean(self):
cleaned_data = super(SearchForm, self).clean()
range1 = cleaned_data.get('range1' or None)
range2 = cleaned_data.get('range2' or None)
val.clean_integer(self, range1, 'range1')
val.clean_integer(self, range2, 'range2')
return cleaned_data
class Meta:
model = Search
unique_together = (('user', 'uuid'),)
labels = {
'depPlace1' : 'Departure 1',
'depPlace2' : 'Departure 2',
'depDate' : 'Outbound',
'retDate' : 'Inbound',
'range1' : 'Max Price 1',
'range2' : 'Max Price 2'
}
widgets = {
'depDate': forms.DateInput(attrs={'class':'datepicker'}),
'retDate': forms.DateInput(attrs={'class':'datepicker'})
}
fields = ['depPlace1', 'depPlace2', 'depDate', 'retDate', 'range1', 'range2']