how to output data from a linked table in django? - python

I have a built-in User table and a Note table associated with it by key.
class Note(models.Model):
header = models.CharField(max_length=100)
note_text = models.TextField()
data = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py.
I tried different ways, don't know how to do that.

Hope this answer finds you well ...
First, you already have a user object in your request. But, still you want to filter out notes for other users too, then do
get_user = User.objects.get(id=id) # For any random user
get_user = request.user # For authenticated user
After getting the user, you simply filter it with the Note model like this ...
get_notes = Note.objects.filter(user=get_user)
You are good to go!

Related

How to check if user is in many to many model django

i am trying to do permission for user where i defined my model like this
class UserInstances(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True,unique=False)
instance_name = models.CharField(max_length=150)
instance_size = models.PositiveIntegerField(default=0)
instance_objects = models.PositiveIntegerField(default=0)
instance_map = models.TextField()
instance_permission = models.ManyToManyField(User,related_name='instance_permission')
def __str__(self):
return f"{self.instance_name} instance for {self.user}"
API code
user = Token.objects.get(key=request.auth)
if UserInstances.objects.get(id=2).instance_permission.exists(user) :// for demonstration
print("access granted")
Can you tell me how to check if user exist or not in many to many field object
you can use
.values_list('{your field}', flat=True)
and then use
in python methode
or you can append users id in a list and then use
in python methode like this:
users = UserInstances.objects.get(id=2).instance_permission.all()
usres_list_id = []
for user in users:
usres_list_id.append(user.id)
if user_instance.id in users_id_list:
#do somethong
Many-to-many relationships can be queried using lookups across relationships, please refer to the Django documentation here.
Long story short, you can filter the UserInstances model and query for the users in instance_permission, i.e. using instance_permission__in.

same notification to multiple selected users in django

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()

Django; How to filter and make objects distinct

I'm creating a project using Django and I'm wondering how I can make objects distinct. Now I am creating message box part and what I want to do is show up user names who the user have been contacting. My current way is like this
models.py
class Message(models.Model):
''''''
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='myself')
someone = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='someone')
views.py
def inbox(request):
'''See messages history'''
messages = Message.objects.filter(user=request.user).distinct('someone')
notification = Message.objects.filter(someone=request.user).distinct('user')
return render(request, 'campus_feed/inbox.html', {'messages': messages})
So what I want to do is list the users who is contacting me or I contacted and I don't want to show up the same name multiple times but I cannot come up with good way to filter them. Anyone who can give me tips?
If you want users, you should request users.
User.objects.filter(Q(myself__someone=request.user) | Q(someone__user=request.user))
This gives you all users who are either the "someone" in a message from the current user, or the "user" in a message to the current user. Since you are querying users directly, the is no possibility of duplicates.

How to put two different model's uuid and id in a same url?

I have two different model linked by a ForeignKey one contains a certain uuid and the other has a certain id. I'd like to be able to put these in the same URL.
Here's the models.py :
class Creation(models.Model):
...
uuid = models.UUIDField(default=uuid.uuid4, unique=True)
class User(models.Model):
...
creation = models.ForeignKey(Creation, null=True)
Here's what the URL pattern should look like :
url(r'^edit/(?P<id>\d+)/(?P<uuid>[^/]+)/$', views.edit, name='edit'),
Views.py
def edit(request, id, uuid):
user_uuid = User.objects.filter(id=id)
user = get_object_or_404(User, id=id, uuid=user_uuid.creation.uuid)
As you can see the view function doesn't make any sense since I don't see how what I'm trying to do should work but the User should be the id in the URL and the Creation should be the uuid since each user can have many Creations.
How can I achieve this?
Your question is quite hard to understand, but I think what you want is:
user = User.objects.get(id=id)
creation = user.creation_set.filter(uuid=uuid)
Note of course though that since uuid is unique, there's no need to use the User ID in the query at all; you could drop it from the URL altogether, use just the uuid to get the Creation, then get the user via creation.user.

Filter user in django and add to a existing group

I am new to Django and I have failing on a task now for a while. I have searched in the Django docs and here for some questions but there nothing is working for me.
Here is my view:
def user_accept(request):
if request.method == 'POST':
username = AddUser.objects.filter(owner=request.user).get().user_request
group_name = Projects.objects.filter(user=request.user).get().group_url
group = Group.objects.get(name=group_name)
group.user_set.add(username)
delete_user = AddUser.objects.filter(user_request=username)
delete_user.delete()
Here is my model:
class AddUser(models.Model):
owner = models.ForeignKey(User)
title = models.CharField(max_length=20, default='', blank=True)
user_request = models.CharField(max_length=30, default='')
answer = models.BooleanField(default=False)
AddUser model is used for users to request access to a specific project. So when a user is requesting a project, data is saved to the AddUser model.
The user field is set to the "owner" of the project so I can filter every project with a proper owner.
If the owner decides to accept the request my user_accept view is executed. Here is the problem, when I try to add the username into the group, I get the following error:
invalid literal for int() with base 10: 'myusername'
I have tried to convert the username with int(username) and tried to get the username's user_id but nothing seems to work... I think it have something to do how I filter my objects but I don't get it.
So thanks a lot for your time, and have a happy new year!
You need the user id or the user object itself to add a user with group.user_set.add.
You can either retrieve the user object from the username, provided usernames are unique and add that:
user = User.objects.get(username=user_request)
group.user_set.add(user)
Or change your AddUser model to store the requester's id via a OneToOne field or ForeignKey instead of username.
Django default groups doesn't allow you to add username into it.
You have to add User objects.
Try
add_user_object = AddUser.objects.filter(owner=request.user).get()
group.user_set.add(add_user_object.owner)

Categories