displaying a user tasks - python

model.py
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __unicode__(self):
return self.user.username
class Task(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
titre = models.CharField(max_length=100)
date = models.DateField()
objectif = models.CharField(max_length=1000)
theme = models.CharField(max_length=20)
views.py
tasks = Task.objects.filter()
return render_to_response('home.html',{'tasks':tasks})
the problem is it display all the tasks in the table but i want to display just the tasks of the user who is logged in
how can i do that

You just need to filter by the user on request.user
tasks = Task.objects.filter(username=request.user)

Your view function (which you aren't fully displaying) has a request parameter. This parameter can be used to retrieve the current request's user. You should then use that to filter the tasks:
def the_view(request):
# ....
tasks = Task.objects.filter(username=request.user)
return render_to_response('home.html',{'tasks':tasks})

Task.objects.filter(username=request.user)

Related

Django-Extra-Views: Inlines child model gets author none. How do I set it the same as the parent?

I have been spinning my wheels on this issue for a day or two. I have django web application that has 3 models
users/models.py:
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
# Create your models here.
class ExtendedUser(models.Model):
user=models.OneToOneField(User,null=True, on_delete=models.CASCADE)
def full_name(self):
return (self.user.get_full_name())
def __str__(self):
return self.user.get_full_name()
#receiver(post_save, sender=User)
def create_or_update_user_extendeduser(sender, instance, created, **kwargs):
if created:
ExtendedUser.objects.create(user=instance)
instance.extendeduser.save()
playground/models.py:
class Customer(models.Model):
def __str__(self):
return self.Customer_Name
Customer_Name = models.CharField(max_length=100)
SFDC_Customer_Record_Number = models.IntegerField(default='')
Zone = models.CharField(max_length=50, default='')
Government = models.BooleanField(default=False)
date_posted = models.DateTimeField(default=timezone.now)
customerauthor = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser)
def get_absolute_url(self):
return reverse('playground-home')
class Vue_Quote(models.Model):
def __str__(self):
return self.Quote_Name
Quote_Name = models.CharField(max_length=100)
SFDC_Golden_Opp_ID = models.IntegerField()
Vue_System_Count = models.IntegerField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser,blank=True,null=True)
Quote_Type = models.CharField(max_length=100)
Customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, default='')
def get_absolute_url(self):
return reverse('quote-detail',kwargs={'pk': self.pk})
I am using the 3rd party application django-extra-views to create a single form which allows a user to create a customer and quote at the same time. Views.py:
class QuoteInline(InlineFormSetFactory):
model = Vue_Quote
fields = ['Quote_Name','SFDC_Golden_Opp_ID','Vue_System_Count','Quote_Type',]
factory_kwargs = {'extra':1}
class CreateQuoteInlinesView(CreateWithInlinesView):
model = Customer
inlines = [QuoteInline]
fields = ['Customer_Name','SFDC_Customer_Record_Number','Zone','Government']
template_name= 'quote_and_customer.html'
def forms_valid(self, form, inlines):
form.instance.customerauthor = ExtendedUser.objects.get(user=self.request.user)
return super().forms_valid(form,inlines)
All of this is working great except for that I am not able to save the author for the Vue_Quote model...I always get "None":
Image of Vue_Quote.author = None from my form
I have tried a wide range of solutions but cannot seem to solve this and I am finding very little documentation on django-extra-views to support my finding a solution.
Any assistance is greatly appreciated!
Welp, I've looked at the source code and tried to figure it out.. It's really abstract and a lot of inheritance
This would be my best guess:
def forms_valid(self, form, inlines):
user = ExtendedUser.objects.get(user=self.request.user)
form.instance.customerauthor = user
for i in inlines:
i.instance.author = user
i.save()
return super().forms_valid(form,inlines)
Or if you wanted to also define the Customer field in this forms_valid you could do it after the super call
You could try something like this:
def forms_valid(self, form, inlines):
user = ExtendedUser.objects.get(user=self.request.user)
form.instance.customerauthor = user
customerObj = super().forms_valid(form,inlines)
for i in inlines:
i.instance.author = user
i.instance.Customer = customerObj
i.save()
return customerObj

Django ManytoMany field remains empty after .add() method called

I'm using django to create a signup platform where students can signup to weekly classes.
Each class is a django model called ClassCards which has a ManytoMany relation to User model called signed_up_student that represents all the users signed up for that class as seen below
class ClassCards(models.Model):
content = models.CharField(max_length=100, default = '')
date = models.DateField(blank=True, null = True)
time = models.TimeField(blank=True,null=True)
signed_up_students = models.ManyToManyField(User,blank=True)
full = models.BooleanField(default = False)
max_students = models.IntegerField(default=4)
teacher = models.CharField(max_length=100, default='Adi')
I would like to add a subscription option that will automatically sign up subscribed students to this weeks class. Here is my Subscription model:
class Subscriptions(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null =True)
day = models.CharField(max_length=100, choices=day_choices, null=True)
time = models.TimeField(blank=True, null=True)
num_of_times_used = models.IntegerField(default=0)
cap = models.IntegerField(default=52)
active = models.BooleanField(default= True)
expirey_date = models.DateField()
date_created = models.DateField(default = timezone.now)
To accomplish this I have created a post_save signal:
#receiver(post_save,sender=ClassCards)
def apply_subsciptions(sender,instance,created, **kwargs):
if created:
subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"),
time=instance.time)
for s in subs:
instance.signed_up_students.add(s.user)
print(instance.signed_up_students.get())
The code runs properly when a ClassCards is saved without throwing any errors and the print statement prints the relevant User However when I look on the admin page, I see that there are no users in the signed_up_students field.
I Would like to understand why this isn't working as desired which should adding that user to the ManytoMany field and what is the best practice for automatically updated a ManytoMany fields.
a little modification to the class ClassCards
class ClassCards(models.Model):
signed_up_students = models.ManyToManyField(User, symmetrical=False, related_name="student_cards_students_has", blank=True)
def signed_students_list(self):
return self.signed_up_students.all()
def cards_asigned_to_student_list(self):
return self.student_cards_students_has.all()
def assign_student(self, user):
self.signed_up_students.add(user)
def unsign_user(self, user):
self.signed_up_students.remove(user)
now in the signals
#receiver(post_save,sender=ClassCards)
def apply_subsciptions(sender,instance,created, **kwargs):
if created:
subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"),time=instance.time)
for s in subs:
instance.assign_student(s.user)
instance.save()
print(instance.signed_students_list())
print(instance.cards_asigned_to_student_list())

How can I check whether a person is included in a model to make a Job/Post

I have created a School System-like system, that creates a job and sends them to employees/users. I'm almost done making this system however I can't seem to know what do to check if the user is included in the manager model that I created to create a job.
Also, how can a user just see all their job that was assigned to them. All I know is to use objects.allbut that might only seem to show all of the jobs that was posted, I just want the user to see the job included to them.
Here is my model.py:
from django.db import models
from profiles.models import User
# Create your models here.
class Points (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
points = models.IntegerField(default=0, null=False)
def __str__(self):
return self.user.username
class Profile (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username}Profile'
class Manager (models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
manager = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Member (models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
member = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Job (models.Model):
manager = models.OneToOneField(Manager, on_delete=models.CASCADE)
member = models.OneToOneField(Member, on_delete=models.CASCADE)
title = models.CharField(max_length=30, blank=False, null=False)
description = models.TextField()
datePosted = models.DateTimeField (auto_now = True)
file = models.FileField(null=True, blank=True,upload_to='job_files')
def __str__(self):
return self.title
And Views.py:
from django.shortcuts import render
from django.views.generic import ListView, CreateView
from .models import Job
from profiles.models import User
# Create your views here.
class jobs(ListView):
model = Job
template_name = 'users/user_jobs.html'
context_object_name = 'jobs'
class createjob (CreateView):
model = Job
fields = ['member','title', 'description', 'file']
How can I proceed?
Use get_queryset to filter job by user
Ex:
class jobs(ListView):
model = Job
template_name = 'users/user_jobs.html'
context_object_name = 'jobs'
def get_queryset(self):
return Job.objects.filter(member__member=self.request.user)

How to count the number of queries in a queryset that has been filtered and append that number as an attribute to another model?

I'm new with Python and Django. I have three models Post, Vote and VoteModel:
class Post(VoteModel, models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=150)
description = models.TextField(max_length=3000)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
class Vote(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE)
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
vote_choice = models.PositiveSmallIntegerField(default=0) #0 - none, 1 - yes, 2 - no
date = models.DateTimeField(auto_now_add=True)
class VoteModel(models.Model):
num_vote_yes = models.IntegerField(default=0, db_index=True)
num_vote_no = models.IntegerField(default=0, db_index=True)
class Meta:
abstract = True
Now, I want to calculate the total number of yes and no votes for each post. I do it like this:
yes_votes = Vote.objects.filter(post=post_instance, vote_choice=1).count()
I want to save the yes_votes number in the abstract VoteModel class num_vote_yes attribute. How?
I want to access num_vote_yes and num_vote_no by post_instance.num_vote_yes and post_instance.num_vote_no.
Certainly, every time I create a new instance of a Vote class I want the num_vote_yes and num_vote_no to be automatically updated. How?
Been struggling for a long time now but I learned a lot! The time has come to outreach! Thanks!
If you want access num_vote_yes and num_vote_no just by the post instance, you can just put these two fields on your Post model. Also you do not need a Abstract model. If you can accept to use relation name to access these two fields, you can create a VoteStat model and have a One-to-one relationships with Post.
For auto update vote stat info, you can use post_save signal, when you save vote model, then udpate your vote relative post stat info.
Here is demo example which just put these stat fields in post model you can refer, please note the F expression in the post save function, which can avoid race condition when udpate vote stat info (Of course, you can use transaction.atomic and select_to_update to implement this).
Note these links just for django 2.2, you can switch to your used version.
from django.db import models
from django.db.models import F
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Post(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=150)
description = models.TextField(max_length=3000)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
# stat info
num_vote_yes = models.IntegerField(default=0)
num_vote_no = models.IntegerField(default=0)
class Vote(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE)
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
vote_choice = models.PositiveSmallIntegerField(default=0) # 0 - none, 1 - yes, 2 - no
date = models.DateTimeField(auto_now_add=True)
#receiver(post_save, sender=Vote)
def update_post_vote_stat(sender, instance, created, **kwargs):
if created:
post = instance.post
if instance.vote_choice == 1:
post.num_vote_yes = F('num_vote_yes') + 1
post.save(update_fields=['num_vote_yes'])
elif instance.vote_choice == 2:
post.num_vote_no = F('num_vote_no') + 1
post.save(update_fields=['num_vote_no'])
else:
pass

Django Many-to-Many Relation or One-to-Many relation

i have this tables in my django :
class User(models.Model):
username = models.CharField(max_length=40)
class Photo(models.Model):
publish_by = models.ForeignKey(User)
name = models.CharField(max_length=40)
desc = models.CharField(max_length=40)
User could publish Phtotos , and they can like Photos .but i don't know how to write the like in the phtoto , should i use one to many or many to many ?
and how could i get the Users that like a Photo .
thanks for help .
UPDATE
In the end I decided to use a many to many with a through model because I also wanted to record the time. The models I have settled on are these
class User(models.Model):
username = models.CharField(max_length=40)
class Photo(Model):
author = models.ForeignKey(User, related_name='%(class)ss')
publish_time = models.DateTimeField(default=datetime.datetime.now)
liked_by = models.ManyToManyField(User, related_name="likes",through='PhotoLike',)
def like(self, user):
liked, created = PhotoLike.objects.get_or_create(photo=self,user=user)
return liked
def save(self, *args, **kwargs):
super(Photo, self).save(*args, **kwargs)
class Meta:
app_label = 'meinv'
class PhotoLike(models.Model):
user = models.ForeignKey(User)
photo = models.ForeignKey(Photo)
like_time = models.DateTimeField(default=datetime.datetime.now)
class Meta:
app_label = 'meinv'
You just need to think about how photos are liked.
Can a user like many photos?
Can many photos be liked by the one user?
Then it is a many to many.
You would implement it like this
class Photo(models.Model):
publish_by = models.ForeignKey(User)
name = models.CharField(max_length=40)
desc = models.CharField(max_length=40)
liked_by = models.ManyToManyField(User, related_name="likes")
Then, it works like this, you can add likes to a photo by
photoInstance.liked_by.add(user)
Access the likes of a photo this way
photoInstance.liked_by.all()
To get all the photos a user liked
user.likes.all()
class Like(models.Model):
user = models.ForeignKey(User)
photo = models.ForeignKey(Photo)

Categories