How can I create on the fly a Auth Group when creating another object from Admin site?

StackOverflow https://stackoverflow.com/questions/15809726

  •  01-04-2022
  •  | 
  •  

Pergunta

  • I have a model which create some kind of object (let's say a Course).
  • I add new objects from the admin front-end

When I create an object, I would like to automatically create a Auth Group with a certain name (not important, but the name of the group must be the same that a created object field).

Is it possible? I have read something about Admin actions, but haven't found anything clear.

Foi útil?

Solução

You can easily create a group by doing the following:

from django.contrib.auth.models import Group

newgroup = Group.objects.create(name=course.name)

You can put this code in your models like this (or maybe create a custom model manager):

from django.contrib.auth.models import User, Group

class Course(models.Model):
    name = models.CharField(max_length=100)

    @classmethod
    def create(course, name):
        newcourse = course(title=name)

        # create the group for the course
        newgroup = Group.objects.create(name=newcourse.name)

        return newcourse

Then, you can create your course:

course = Course.create(name="Django: The Web framework for perfectionists with deadlines")

Outras dicas

Daniel it seems a good approximation. I have managed a solution as well overriding the method save_model for the model CourseAdmin, inside the admin.py. Thanks a lot, your implementation seems cleaner!

Here is what I have done:

----- admin.py -----

from django.contrib.auth.models import Group

class CourseAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        g = Group(name=obj.code)
        g.save()
        obj.save() # Without this line the object is not saved into the Course model!

admin.site.register(CourseAdmin)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top