Reputation: 45
Explanation
I have an extension of my model in eiysTblModels because we are using inspectdb option of django manage.py. Since it overwrites the models.py,we do not touch models.py, instead write our extensions to eiysTblModels.
Problem
Anyway, when I call edit_group function, it sets the slug and dates correctly as specified but it overwrites the other fields such as is_active, isapproved etc to NULL, which are initially set to 1.
vieys.py
def edit_group(request,group_id):
groupinfo = request.POST
group = eiysTblGroup(id = group_id )
group.name = groupinfo.get('group-name','')
group.save()
eiysTblModels.py
class eiysTblGroup(TblGroup):
class Meta:
proxy = True
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
if not self.id:
self.date_created = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.isactive = 1
self.date_last_modified = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
super(TblGroup, self).save(*args, **kwargs)
models.py
class TblGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=250, blank=True)
date_created = models.DateTimeField(blank=True, null=True)
date_last_modified = models.DateTimeField(blank=True, null=True)
creator = models.ForeignKey(AuthUser, blank=True, null=True)
group_photo_url = models.CharField(max_length=250, blank=True)
isactive = models.IntegerField(blank=True, null=True)
slug = models.CharField(max_length=250, blank=True)
code = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tbl_group'
Summary
Basically, what I need is to automatically update date_last_modified, date_created and slug when I save them, and do NOT update any other part to NULL.
Upvotes: 0
Views: 373
Reputation: 45
Obviously, my erroneous part is this in view:
group = eiysTblGroup(id = group_id )
I'm not sure how I made such a silly mistake. The correct form should be:
group = eiysTblGroup.objects.get(id = group_id )
Then it works correctly...
Upvotes: 1
Reputation: 3940
I believe the answer for your question can be found here:
Automatic creation date for django model form objects?
You want to use those, because Django can set creation and modification dates for you automatically without any additional interactions needed.
models.DateTimeField(auto_now_add=True)
models.DateTimeField(auto_now=True)
As for the slug, shorten your save()
method to:
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(eiysTblGroup, self).save(*args, **kwargs)
Upvotes: 0