First of all I would like to say that I am extremely new to Django and Python.
I am writing an application using Django 2.0. I have two inheritances to the user: the patient and responsible. A patient needs a user to exist and a responsible needs a patient to exist. A responsible may have several patients but one patient may only have one responsible.
However I am having the following problem: A patient can not be responsible for himself and currently this happens. How can I stop this from happening?
patient model:
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient',
on_delete=models.CASCADE, unique=True)
(...)
responsible model:
class Responsible(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
limit_choices_to=Q(patient=None))
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
As you can see I'm using the "limit_choices_to" but it causes all users who are patients are not listed in the time I create a new responsible.
I managed to solve this as follows:
In my responsible model i added the following lines:
def clean(self):
if self.user == self.patient.user:
raise ValidationError(_("A patient can not be responsible for himself"))
So now it is no longer possible for a patient to be responsible for himself.
Related
I have a custom group model like this:
class MyGroup(models.Model):
name = models.CharField(max_length=200,null=True,blank=False,default="Group name")
members = models.ManyToManyField(get_user_model(), blank=True, related_name="grpmembers")
created_by = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING, null=True, blank=False, related_name="createdby+")
created_at = models.DateTimeField(editable=False)
It works, it's fine, I override the save method in django admin so the created_by will point to the logged in user on save.
Problem #1
Even if you are the creator of the group, you can select yourself to either be in- or be removed from the group which kinda looks silly. I'm thinking of solving this by saying the user can view the group if they're in members or created_by.
Problem #2
Custom permission. I want to have some permissions, like:
Can view the group: which means the user is either the creator or is in the members list
Can edit the group: which means the user is the creator(can edit their own) or is staff(can edit anyone's stuff) or is superuser(root)
I can write it down and imagine how it would work, but I have no idea how to implement these.
I've found some ways, like creating a Meta and defining permissions there and also making the permissions as def(/functions), but how could I access the currently logged in user?
Like okay let's say I do
def can_view_group(self):
r1 = self.filter(members=req.user) # where req.uset is not accessible bc we're in models.py
, but how do I tell the permission to check the currently logged in user?
The problem is doing all the logic in models.
Over problem 1 you need to verify user is not owner before allow to leave in the views.py.
Over the problem 2 are 2 solutions, or you move can_view_group to views.py, or you define that in models as:
def can_view_group(self, user):
#all the logic
And you pass the user from views.py
I am trying to implement a notification page on my website in Django. But I have a problem that how can I send the same notification to multiple users.
let suppose I have to send it to just one user.
then I can create a model of notification with
noti = models.TextField()
user= models.foreignkey
is_seen = models.bool
so this is just a sample
but the the problem is this how i can send this notification to selected multiple users
one important is that is_seen is compulsory for each user
I hope you will understand
I think it depends how this data will grow in future. Because if all of your notifications go to multiple users, you can have a Notification model with ManyToMany relation with User. Something like following
class Notification(models.Model):
message = models.TextField()
users = models.ManyToMany(User, through='UserNotification')
class UserNotification(model.Model):
user = models.ForeignKey(User)
notification = models.ForeignKey(Notification)
is_seen = models.BooleanField()
But other question is if you want to build something like the one you shared, that is also fine. I don't think so there's an issue of adding same message for multiple users. This is more flexible in my opinion as compared to M2M relation. You can extend this in future easily as your application will grow.
class Notification(model.Model):
message = models.TextField()
user = models.ForeignKey(User)
is_seen = models.BooleanField)
Another case can be if you want to have more relations and if there's need of adding more information related to notification. This gives more room for improvement in future in terms of storing information.
class Notification(model.Model):
message = models.TextField()
class UserNotification(model.Model):
user = models.ForeignKey(User)
notification = models.ForeignKey(Notification)
is_seen = models.BooleanField()
I'm working on a project using Python(3.7) and Django(2.1) in which I need to build a relationship between users and organizations.
I'm using the default Django User model and a profile model to add extra information to users.
Many users can join an organization and an Organization can have many members, a user can create an Organization, these behaviors I need to implement, according to my understanding we need to build a ManyToMany relationship for Organizations model, but don know how to use this relationship to display the information, e.g display a user's organizations on his profile page.
Here are my models:
class Organization(models.Model):
name = models.CharField(max_length=255, blank=False)
users = models.ManyToManyField(User, related_name='members', null=True)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')
goals = MultiSelectField(choices=goals_choices, default='')
def __str__(self):
return f'{self.user.username} Profile'
You can get all organizations of a particular user by:
my_user.members.all()
If you want to access from profile:
my_profile.user.members.all()
But I would suggest to remove related_name or rename it. If you remove it you can access all user organizations as:
my_user.organization_set.all()
my_profile.user.organization_set.all()
For organization you can get all users by:
my_org.users.all()
I have a live web-based chat app made in Django. Users can form groups where other users can congregate, leave messages (called replies) and photos. The url every user visits to access a group is:
url(r'^group/(?P<pk>\d+)/reply/$', auth(GroupView.as_view()), name="group_reply"),
where pk is group.pk.
My question is: how can I get a list (or set) of all distinct users who accessed a certain group's URL in the last 5 mins? Essentially, I'm trying to calculate the number of unique recent visitors for each group. I can't seem to wrap my head around how to do this, though I guess sessions information could help? (I'm using django user_sessions in this project, which
"makes session objects a first class citizen like other ORM objects"
).
In case required, the model behind a group is:
class Group(models.Model):
topic = models.TextField(validators=[MaxLengthValidator(200)], null=True)
rules = models.TextField(validators=[MaxLengthValidator(500)], null=True)
owner = models.ForeignKey(User)
private = models.CharField(max_length=50, default=0)
category = models.CharField(choices=TYPE, default=1, max_length=25)
created_at = models.DateTimeField(auto_now_add=True)
And the model behind posting a reply in each group is:
class Reply(models.Model):
text = models.TextField(validators=[MaxLengthValidator(500)])
which_group = models.ForeignKey(Group)
writer = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to=upload_pic_to_location, null=True, blank=True )
And User is a vanilla django.contrib.auth user.
You don't have anything that is collecting the data you need. If you want to record visits to a page, you will need to build a model to do that; a simple one with FKs to User (for the visitor) and Group (for the group being visited), plus a timestamp, should be enough. Then your GroupView can make an entry in that table every time a user visits.
The queryset I've constructed is incorrectly leaving out some items. I have three models in Django:
class Case(models.Model):
agents = models.ManyToManyField('UserProfile', related_name='agent_of', blank=True, null=True)
organization = models.ForeignKey(Organization, related_name='case_org')
class UserProfile(models.Model):
name = models.CharField(max_length=40)
user = models.ForeignKey(User, unique=True, related_name='user_profile')
organization = models.ForeignKey(Organization, related_name='org_members', blank=True, null=True)
class Organization(models.Model):
name = models.CharField(max_length=75)
I'm trying to build a list of unassigned cases. That is, cases that the current user is not an agent on, including cases that have no agents at all assigned to them. Here's my query:
Case.objects.filter(
organization=request.user.user_profile.get().organization.id).exclude
(Q(agents__user=request.user))
This works fine for cases with other agents (UserProfile model) assigned to them. But it does not return cases with NO agent assigned to them. I'm pretty sure this has to do with the fact that cases with no agent assigned to them have no row in the intermediate table connecting UserProfiles and Cases.
So in other words if I have these cases:
Case/Agents
Case1: Tom, Steve
Case2: Steve
Case3: Jane
Case4: Nobody
My query will return Case2 and Case3, but not Case4. Trying to get that Case4 included.
Sorry if this is not very clear, any help is appreciated.
The question is a bit unclear but does this query not work to get all cases that aren't assigned to that user?
Case.objects.exclude(agents=request.user)
If you are trying to get cases belonging to user's organization AND not assigned to him OR NOT unassigned to anybody this should work.
Case.objects.filter(Q(organization=organization)|Q(agents=None)).exclude(agents=request.user)