Answer the question
In order to leave comments, you need to log in
How to automatically indicate the author of the entry?
There is a model:
class Request(models.Model):
**
usercreated = models.ForeignKey(User, blank=True, null=True)
Answer the question
In order to leave comments, you need to log in
Here is the solution that helped me. Thanks to all!
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
if isinstance(instance, Request):
if(not instance.usercreated):
instance.usercreated = request.user
instance.save()
You can catch the user in the middleware and then get him from there when saving
In my projects for a long time I did this:
1. Model with all common fields for audit:
models.py
class Audit(models.Model):
"""
A common class for auditing the models' instances.
"""
created_by = models.ForeignKey(
User,
related_name='%(app_label)s_%(class)s_created_related',
verbose_name=_(u'Создал'),
on_delete=models.SET_NULL,
blank=True, null=True)
changed_by = models.ForeignKey(
User,
related_name='%(app_label)s_%(class)s_changed_related',
verbose_name=_(u'Изменил'),
on_delete=models.SET_NULL,
blank=True, null=True)
created = models.DateTimeField(
_(u'Дата создания'), auto_now_add=True)
changed = models.DateTimeField(
_(u'Дата изменения'), auto_now=True)
class Meta:
abstract = True
admin.py
class AuditAdmin(admin.ModelAdmin):
"""
Admin class for audit fields
"""
readonly_fields = (
'created_by',
'changed_by',
'created',
'changed')
fieldsets_preset = (
_(u'Прочее'), {
'fields': (
'created_by',
'created',
'changed_by',
'changed'
)
})
actions_on_top = True
def save_model(self, request, obj, form, change):
if not change:
obj.created_by = request.user
obj.changed_by = request.user
obj.save()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question