我具有以下Model,ModelForm和View:
class Clinic(models.Model):
clinicid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=60)
label = models.SlugField(max_length=25)
# logo =
email = models.EmailField(max_length=50, default='')
mobile = models.CharField(max_length=15, default='')
alternate = models.CharField(max_length=15, default='', blank=True)
about = models.CharField(max_length=250, blank=True)
state = models.CharField(max_length=25)
city = models.CharField(max_length=35)
locality = models.CharField(max_length=35)
pincode = models.IntegerField(default=0)
address = models.TextField(max_length=80, default='', blank=True)
website = models.URLField(blank=True)
class ClinicMetaForm(ModelForm):
class Meta:
model = Clinic
fields = [
'name',
'label',
'email',
'mobile',
'alternate',
'about',
'state',
'city',
'locality',
'pincode',
'address',
'website'
]
unique_together = ["name", "mobile", "email"]
def newclinic(request):
if request.method == 'POST':
print('New clinic setup')
form = ClinicMetaForm(request.POST)
form.save()
msg = "Successfully saved new clinic"
print(msg)
else:
form = ClinicMetaForm()
msg=''
return render(request, 'clinic/newclinic.html', {'form': form, 'msg': msg})
问题是,即使我使用的是unique_together,提交相同的数据时,我也会保存重复的条目。为什么会这样呢?我该如何避免呢?
答案 0 :(得分:0)
您应该移动unique_together进行建模。
而且,如果您想在表单中添加一些逻辑,只需覆盖validate_unique
def validate_unique(self):
#your logic here
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError, e:
self._update_errors(e.message_dict)