hello i have StoreCheckout model and i override save and clean method but conditions in override methods not work.
class StoreCheckout(models.Model):
store = models.ForeignKey(
to=Store,
on_delete=models.CASCADE,
limit_choices_to={
'is_confirm': True
},
)
pay_date = models.DateTimeField()
amount = models.PositiveBigIntegerField()
bank_number = models.PositiveBigIntegerField(validators=[bank_number_validate])
def __str__(self):
return self.store.name
def save(self, *args, **kwargs):
if not self.bank_number:
self.bank_number = self.store.bank_number
if not self.pay_date:
self.pay_date = datetime.now()
super(StoreCheckout, self).save(*args, **kwargs)
def clean(self, *args, **kwargs):
if not settings.MIN_CHECKOUT <= self.store.wallet <= settings.MAX_CHECKOUT:
raise ValidationError(
f'amount of your store must between {settings.MIN_CHECKOUT} and {settings.MAX_CHECKOUT} toman'
)
super(StoreCheckout, self).save(*args, **kwargs)
Related
I have model and i want to add my custom function, and when i create object this function call automatically.
this is my model and test function. it's only for testing
i want when i create Like object after call test function
class LikeManager(models.Manager):
def create(self, *args, **kwargs):
decrease = kwargs.pop("decrease")
new_like = self.model(**kwargs)
new_like.save(decrease=decrease)
return new_like
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question"))
objects = LikeManager()
#this function (not printing)
#property
def test(self):
print("Testing")
return 1
def save(self, decrease, *args, **kwargs):
if not self.pk:
if decrease:
self.question.save()
else:
self.question.point += 1
self.question.save()
return super(Like, self).save(*args, **kwargs)
who can help me?
If you want to run the test function when a like object is created why don't you just put the test function inside of the save function?
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question"))
objects = LikeManager()
def save(self, decrease, *args, **kwargs):
def test(self):
print("Testing")
return 1
if not self.pk:
if decrease:
self.question.save()
else:
self.question.point += 1
self.question.save()
return super(Like, self).save(*args, **kwargs)
Otherwise, you need to call the test function every time after you
create an object ( e.g.:
a = Like.objects.create(user=request.user,question=q)
a.test()
)
I have a problem with django app and POSTGRESQL database with the slug field.
Error:
value too long for type character varying(1)
I test my app with sqlite database and everything works fine, but my app does not work in postgresql database. Any ideas why this is the case?
Test 1:
class MyModel(models.Model):
name = models.CharField(max_length=254)
slug_name = models.SlugField(max_length=254)
def save(self, *args, **kwargs):
self.slug_name = slugify(self.name)
super(MyModel, self).save(*args, **kwargs)
Test 2:
class MyModel(models.Model):
name = models.TextField(max_length=500)
slug_name = models.SlugField(max_length=500)
def save(self, *args, **kwargs):
self.slug_name = slugify(self.name)
super(MyModel, self).save(*args, **kwargs)
Test 3:
class MyModel(models.Model):
name = models.TextField()
slug_name = models.SlugField()
def save(self, *args, **kwargs):
self.slug_name = slugify(self.name)
super(MyModel, self).save(*args, **kwargs)
You're trying to insert a value with more that one character into a field specified as character varying(1). SQLite3 will allow this (see https://sqlite.org/datatype3.html) but PostgreSQL will give an error - i.e., it enforces that you have specified the maximum length as 1.
I have a problem about Delete Object after savings Django
I have model Like:
class Reaction(models.Model):
REACT_TYPES = (
(LIKE, 'Like'),
(LOVE, 'Love'),
)
user = models.ForeignKey(User)
react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE')
How can I write a save():
When saving, it should remove the available object with THE SAME user and react_type or create one if object doesn't exists.
def save(self, force_insert=False, force_update=False, *args, **kwargs):
user = Reaction.objects.filter(user=self.user)
react_type = Reaction.objects.filter(user=self.react_type)
# Model delete if exist
if self.id.exists() & self.react_type.exists() :
self.Reaction.delete()
# Model create if not exist
else :
self.Reaction.create()
Fix with #dirkgroten solution:
class ReactionManager(models.Manager):
def save(self, force_insert=False, force_update=False, *args, **kwargs):
similars = Reaction.objects.filter(user=self.user, react_type=self.react_type)
if similars.exists():
print ('exist')
similars.delete()
else:
print ('Not exist')
similars.create()
super(Reaction, self).save(*args, **kwargs)
Please check this code. It may help you:
def save(self, force_insert=False, force_update=False, *args, **kwargs):
similars, created = Reaction.objects.get_or_create(user=self.user, react_type=self.react_type)
if not created:
print ('exist')
similars.delete()
super(Reaction, self).save(*args, **kwargs)
This code will work ok.
def save(self, force_insert=False, force_update=False, *args, **kwargs):
similars = Reaction.objects.filter(user=self.user, content_type=self.content_type, object_id=self.object_id)
if similars.exists():
similars.delete()
similars.update(user=self.user, react_type=self.react_type)
else :
similars.update(user=self.user, react_type=self.react_type)
super(Reaction, self).save(*args, **kwargs)
I am building a custom tags plugin for django-wiki using django-taggit to save tags. I cannot save the form with .save_m2m as it says in the django-taggit docs. The tags can be saved in the admin but not through the fronted form because I cant save with .save_m2m(). I get the following error even after the form has been saved. Any help would be appreciated.
type object 'SidebarForm' has no attribute 'save_m2m'
wiki_plugins.py
class TagPlugin(BasePlugin):
slug = settings.SLUG
sidebar = {
'headline': _('Tags'),
'icon_class': 'fa-picture-o',
'template': 'sidebar.html',
'form_class': forms.SidebarForm,
'get_form_kwargs': (lambda a: {'instance': models.Tag(article=a)})
}
models.py
class TagRevision(RevisionPluginRevision):
def can_write(self, user):
if not settings.ANONYMOUS and (not user or user.is_anonymous()):
return False
return RevisionPlugin.can_write(self, user)
def can_delete(self, user):
return self.can_write(user)
class Meta:
verbose_name = _('tag')
verbose_name_plural = _('tags')
db_table = 'wiki__plugins_tags_tag' # Matches label of upcoming 0.1 release
if settings.APP_LABEL:
app_label = settings.APP_LABEL
def __str__(self):
if self.current_revision:
return ugettext('Tag: %s') % self.current_revision.tagrevision
else:
return ugettext('Current revision not set!!')
#python_2_unicode_compatible
class TagRevision(RevisionPluginRevision):
tags = TaggableManager()
def inherit_predecessor(self, tag):
"""
Inherit certain properties from predecessor because it's very
convenient. Remember to always call this method before
setting properties :)"""
predecessor = tag.current_revision.tagrevision
self.plugin = predecessor.plugin
self.deleted = predecessor.deleted
self.locked = predecessor.locked
self.tag = predecessor.tag
if not skip_image_file:
try:
self.tags = predecessor.tags
except IOError:
self.tags = None
class Meta:
verbose_name = _('tag revision')
verbose_name_plural = _('tag revisions')
# Matches label of upcoming 0.1 release
db_table = 'wiki_plugins_tags_tagrevision'
if settings.APP_LABEL:
app_label = settings.APP_LABEL
ordering = ('-created',)
def __str__(self):
return ugettext('Tag Revsion: %d') % self.revision_number
forms.py
from wiki_plugins_tags import models
class SidebarForm(PluginSidebarFormMixin):
def __init__(self, article, request, *args, **kwargs):
self.article = article
self.request = request
super(SidebarForm, self).__init__(*args, **kwargs)
self.fields['tags'].required = True
def save(self, *args, **kwargs):
if not self.instance.id:
tagged = models.Tag()
tagged.article = self.article
kwargs['commit'] = False
revision = super(SidebarForm, self).save(*args, **kwargs)
revision.set_from_request(self.request)
tagged.add_revision(self.instance, save=True)
return revision
return super(SidebarForm, self).save(*args, **kwargs)
class Meta:
model = models.TagRevision
fields = ('tags',)
class RevisionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.tags = kwargs.pop('tags')
self.request = kwargs.pop('request')
super(RevisionForm, self).__init__(*args, **kwargs)
self.fields['tags'].required = True
def save(self, *args, **kwargs):
if not self.instance.id:
kwargs['commit'] = False
revision = super(RevisionForm, self).save(*args, **kwargs)
revision.inherit_predecessor(self.tags, skip_image_file=True)
revision.deleted = False # Restore automatically if deleted
revision.set_from_request(self.request)
self.tags.add_revision(self.instance, save=True)
return revision
return super(RevisionForm, self).save(*args, **kwargs)
class Meta:
model = models.TagRevision
fields = ('tags',)
I need some help with an issue.
I have three models, Reference, Relation ans Circuit. Relation is an inline of the first one. Circuit and Relation are related. What I have to do is:
- I'm in Reference 1 and I have selected some Circuits inside my Relation1 to RelationN.
- When I save, I need to save Relation1 to RelationN, and other RelationFirst (created when the Reference model is saved) who must contain all the Circuits that exist in the other Relations of that Reference.
The code that I have right now, who doesn't do it, is:
class Reference(models.Model):
title = models.CharField(max_length=200, verbose_name = _('title'))
def __unicode__(self):
return u"\n %s" %(self.title)
def save(self, force_insert=False, force_update=False, *args, **kwargs):
is_new = self.id is None
super(Reference, self).save(force_insert, force_update, *args, **kwargs)
if is_new:
Relation.objects.create(reference=self, first = True)
relation = Relation.objects.get(reference=self, first = True)
circuit = Circuit.objects.get(name = '0')
relation.circuit.add(circuit)
class Relation(models.Model):
first = models.BooleanField()
reference = models.ForeignKey(Reference)
circuit = models.ManyToManyField('Circuit', verbose_name = _('Circuits'), null=True, blank=True, related_name = 'relation_circuit')
def __unicode__(self):
return u"%s" %(self.reference)
def save(self, force_insert=False, force_update=False, *args, **kwargs):
relation1 = Relation.objects.get(reference=self.reference, first = True)
super(Relation, self).save(force_insert, force_update, *args, **kwargs)
for circ in self.circuits:
circuit = Circuit.objects.get(pk = circ)
relation1.circuit.add(circuit)
Any help? Because I can't iterate the ManyToManyRelatedField, and I don't know how to do it. Thank you very much!
You should do it that way:
for circ in self.circuit.all():