Reputation: 107
I have a project with 3 groups of user who are admin, prof, and student. I want all my users to be able to send messages to each other privately. For example if I want a teacher to send a message to a student or admin, how should I proceed? Do I need to create a new model or I just need to add a mailbox field to my models.
that's my models
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from phonenumber_field.modelfields import PhoneNumberField
class Prof(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
location = models.CharField(max_length=150)
date_of_birth = models.DateField(null=True, blank=True)
phone = PhoneNumberField(blank=True)
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
speciality = models.CharField(max_length=150)
location = models.CharField(max_length=150)
date_of_birth = models.DateField(null=True, blank=True)
phone = PhoneNumberField(blank=True)
here is how I register my 3 types of users with django signals
from django.db.models.signals import post_save
from django.contrib.auth.models import Group
from django.dispatch import receiver
from .models import Prof, Student
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def admin_profil(sender, instance, created, **kwargs):
if created and instance.is_superuser:
group = Group.objects.get(name='admin')
instance.groups.add(group)
@receiver(post_save, sender=Prof)
def prof_profil(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name='prof')
instance.user.groups.add(group)
@receiver(post_save, sender=Student)
def student_profil(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name='student')
instance.user.groups.add(group)
precision: i register my admin with the command line createsuperuser and the others user by forms
Upvotes: 0
Views: 460
Reputation: 169388
For example if I want a teacher to send a message to a student or admin, how should I proceed?
Since you already (prudently enough) have separated the role-specific fields from your users, your Message model can look like
class Message(models.Model):
recipient = models.ForeignKey(User, related_name='messages_received')
sender = models.ForeignKey(User, related_name='messages_sent')
# ... other messagey fields
Then a view can request messages for the current user with e.g. Message.objects.filter(recipient=request.user)
or similar.
Upvotes: 1