Home > Mobile >  Django Create separate copy of a model every time a user signs up
Django Create separate copy of a model every time a user signs up

Time:10-21

So, I am really new to Django. I was working around an app as a part of an assignment which requires me to build a webapp with login functionality, Further the admin, shall create few tasks that will be common to all the users. So here is the model that would contain all the tasks and will be controlled by the admin:

from django.db import models

# Create your models here.
class applib(models.Model):
  status_code=[
    ('C','Completed'),
    ('P','Pending'),
  ]
  title = models.CharField(max_length=50)
  status=models.CharField(max_length=2,choices=status_code)
  point = models.IntegerField()
  category= models.CharField(max_length=50)
  subcat = models.CharField(max_length=50)
  applink = models.CharField(max_length=100)
  def __str__(self):
      return self.title

Now I have worked around the login functionality, and I want that upon each login a copy of this model is attached to the user so that the user can has his own set of tasks. He should be able to keep track of these tasks and do the tasks independently. How do I do this without creating separate task models for each user. I know there would be a really simple explanation and solution but all I know write now is I want to inherit the tasks from the main model for each user upon user creation.

Thank you.

CodePudding user response:

You need to add a user field to you AppLib (change classname to CamelCase).

class AppLib(models.Model):
    ...
    user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="tasks")
    ...

This way, in the admin panel, you can assign tasks to a specific user

if you want to assign a task to a set of users:

from django.contrib.auth import get_user_model
...

class AppLib(models.Model):
    ...
    users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="tasks")
    ...
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # only fetch users that are active
        users = list(get_user_model()._default_manager.filter(
            is_active=True).values_list("pk", flat=True))
        self.users.add(*users)
   

in admin.py:

from django.contrib.auth import get_user_model
from django.contrib import admin
from <model_module> import AppLib

@admin.register(AppLib)
class AppLib(admin.ModelAdmin):
    ...
    def save_related(self, request, form, formsets, change):
        super().save_related(request, form, formsets, change)
        users = list(get_user_model()._default_manager.filter(
            is_active=True).values_list("pk", flat=True))
        form.instance.users.add(*users)

Read More about this logic here

  • Related