Re: Add user to authors on model save in admin form
I do not think having Author = model.ManyToMany will work.
On Friday, April 19, 2013 12:22:02 PM UTC-4, Laurent GARTNER wrote:
Hi,
I'm in trouble with model admin.
I've create a CMS with Django and I try to add the last article editor, but it doesn't work if the user don't add his name in the field.
In model.py
class Article(models.Model):
…
author = models.ManyToManyField(User, verbose_name=u"auteur", null=True, blank=True)
author_text = models.CharField(u'auteurs', null=True, blank=True, max_lenght=254)
Note: author keeps real "author" of the aritcle, author_text is editable to show another "author"
def save(self, *args, **kwargs):
# Si author_text est vide, le remplir avec l'auteur
if not self.author_text and self.id:
author_text = list()
for author in self.author.all():
if author.first_name or author.last_name:
author_name = " ".join([author.last_name, author.first_name]) else:
author_name = author.username author_text.append(author_
name) self.author_text = ", ".join(author_text)
In admin.py
def save_model(self, request, obj, form, change):
# Première sauvegarde pour attribuer un ID indispensable à un M2M
obj.save()
super(ArticleAdmin, self).save_model(request, obj, form, change)
# Ajout de l'auteur à la liste
if not request.user in obj.author.all() or obj.author.all() == None:
obj.author.add(request.user)
obj.save()
When I create a new article in admin site, author_text gets author username (as I expect with my save model), but author stay empty ! If I look at the article during "save_model", author get the user, but after "save", author is null (as in form).
How can I force author field to record the last author ? can I update admin form with a default author value ?
Thanks for the answer
Garthh
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home