54π
β
If an individual field needs to be unique, then you just add 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)
If you want a combination of fields to be unique, you need 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"]
π€Mike DeSimone
3π
The unique_together also suggested is the best way, but if thatβs not appropriate for your needs, you can handle it in your formβs clean method. eg
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
π€Steve Jalim
- [Django]-Why won't Django use IPython?
- [Django]-Django character set with MySQL weirdness
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
0π
I think injecting a Jquery/JS code to hide the save button would be a good idea.
Create a custom_validate.js file like below and place it in directory static(static file directory)
if (!$) {
$ = django.jQuery;
}
$( document ).ready(function() {
$("[name=_save]").click(function() {
$("[name=_save]").css("visibility", "hidden");
});
});
And in admin.py, add the below code.
class CustomDataForm(forms.ModelForm):
class Meta:
model = GetData
class GetDataAdmin(admin.ModelAdmin):
# ....
.....
form = CustomDataForm
class Media:
js = ('/static/custom_validate.js', )
π€SuperNova
- [Django]-How to pass django rest framework response to html?
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
0π
I ran into this problem myself as well, unique_together
seems to work nicely.
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"]
π€mck
- [Django]-CORS error while consuming calling REST API with React
- [Django]-Serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
- [Django]-Django error: got multiple values for keyword argument
Source:stackexchange.com