Reputation:
In one of my Django models, I override the save function. I do this to get the user's username. But that keeps failing.
this is what i did:
def save(self, *args, **kwargs):
self.slug = slugify('%s' % (self.question))
if not self.id:
self.publish_date = datetime.datetime.now()
self.publisher = self.request.user
self.modification_date = datetime.datetime.now()
self.modifier = self.request.user
super(Faq, self).save(*args, **kwargs) # Call the "real" save() method
This fails with: 'Faq' object has no attribute 'request'
Thanks.
Upvotes: 0
Views: 157
Reputation: 599490
If this is for use within the Admin app, as you say in your answer to Jake, then you shouldn't override the model save method at all. Instead, you should override the save_model
method of the ModelAdmin
class.
See the original code in django.contrib.admin.options
- you'll see that it's already passed the request
object. So all you need to do is to assign the publisher
there:
def save_model(self, request, obj, form, change):
obj.slug = slugify('%s' % (obj.question))
if not obj.id:
obj.publish_date = datetime.datetime.now()
obj.publisher = request.user
obj.modification_date = datetime.datetime.now()
obj.modifier = request.user
obj.save()
Upvotes: 2
Reputation: 7207
You'll need to pass the request into the save method since it doesn't exist in that context automatically.
def save(self, request, *args, **kwargs):
self.slug = slugify('%s' % (self.question))
if not self.id:
self.publish_date = datetime.datetime.now()
self.publisher = request.user
self.modification_date = datetime.datetime.now()
self.modifier = self.request.user
super(Faq, self).save(*args, **kwargs) # Call the "real" save() method
Usage...
my_faq = Faq()
my_faq.save(request)
Upvotes: 1
Reputation: 13141
request
is only passed to views, not model methods so you will have to set the publisher
in a view.
I would remove the line self.modifier = self.request.user
from here and set modifier = request.user
at the same time as you set question
which I assume you are doing in a view.
Then you can change self.publisher = self.request.user
to self.publisher = self.modifier
Hope that helps.
Upvotes: 1