在模特中:
class Getdata(models.Model):
title = models.CharField(max_length=255)
state = models.CharField(max_length=2, choices=STATE, default="0")
name = models.ForeignKey(School)
created_by = models.ForeignKey(profile)
def __unicode__(self):
return self.id()
在模板中:
<form>
<input type="submit" value="save the data" />
</form>
如果用户点击保存按钮并且上述数据保存在表格中,如何避免重复,即如果用户再次点击相同的提交按钮,则不应该有相同值的另一个条目。或者它是否必须在视图中处理?
答案 0 :(得分:28)
如果单个字段必须是唯一的,那么您只需添加unique=True
:
class Getdata(models.Model):
title = models.CharField(max_length=255, unique=True)
state = models.CharField(max_length=2, choices=STATE, default="0")
name = models.ForeignKey(School)
created_by = models.ForeignKey(profile)
如果您希望字段组合是唯一的,则需要unique_together:
class Getdata(models.Model):
title = models.CharField(max_length=255)
state = models.CharField(max_length=2, choices=STATE, default="0")
name = models.ForeignKey(School)
created_by = models.ForeignKey(profile)
class Meta:
unique_together = ["title", "state", "name"]
答案 1 :(得分:2)
unique_together也建议是最好的方法,但如果这不适合您的需求,您可以使用表单的干净方法处理它。例如
def clean(self):
try:
Getdata.objects.get(title=self.cleaned_data['title'],
state=self.cleaned_data['state'],
name=self.cleaned_data['name'],
created_by=self.cleaned_data['created_by'] )
#if we get this far, we have an exact match for this form's data
raise forms.ValidationError("Exists already!")
except Getdata.DoesNotExist:
#because we didn't get a match
pass
return self.cleaned_data
答案 2 :(得分:1)
我认为注入一个Jquery / JS代码来隐藏保存按钮是个好主意。
创建如下所示的custom_validate.js文件并将其放在目录static(静态文件目录)中
if (!$) {
$ = django.jQuery;
}
$( document ).ready(function() {
$("[name=_save]").click(function() {
$("[name=_save]").css("visibility", "hidden");
});
});
在admin.py中,添加以下代码。
class CustomDataForm(forms.ModelForm):
class Meta:
model = GetData
class GetDataAdmin(admin.ModelAdmin):
# ....
.....
form = CustomDataForm
class Media:
js = ('/static/custom_validate.js', )