Displaying sum of time by project by user using Django - python

I am a student new to programming. I am working on a project to create a timekeeping function. I want to be able to display the total time a user worked on a project. I have been able to display the total time for a user, and the total time for a project.
class User(models.Model):
class Project(models.Model):
title = models.CharField(max_length=255)
start_date = models.DateField()
end_date = models.DateField()
done = models.BooleanField(default=False)
created_by = models.ForeignKey(User, related_name ='made_by', on_delete=models.CASCADE)
projects_working_on = models.ManyToManyField(User, related_name = "projects_assigned_to")
class Timekeeper(models.Model):
clock_in = models.DateTimeField(null=True)
clock_out = models.DateTimeField(null=True)
total_time = models.DurationField(null=True, blank=True)
entire_time = models.FloatField(null=True)
is_working = models.BooleanField(default=False)
users_time = models.ForeignKey(User, related_name="time_of_user", on_delete=models.CASCADE)
proj_time = models.ForeignKey(Project, related_name = 'time_of_project', on_delete=models.CASCADE)
Here is is clockout function:
def clockout(request, proj_id):
user = User.objects.get(id=request.session['userid'])
now = datetime.now(timezone.utc)
this_proj = Project.objects.get(id = proj_id)
this_time = user.time_of_user.last()
time = this_time.users_time
this_time.clock_out = now
this_time.is_working = False
newtime = user.time_of_user.filter(proj_time=proj_id).aggregate(Sum('total_time'))
# this_time.total_time_two = newtime
this_time.save()
Timekeeper.objects.update(total_time=F('clock_out') - F('clock_in'))
Timekeeper.objects.update(entire_time=F('total_time'))
Timekeeper.objects.update(total_time_two=newtime)
# Timekeeper.objects.update(entire_time=user.time_of_user.filter(proj_time=proj_id).aggregate(Sum"(F('total_time')")
return redirect('/dashboard/view/'+str(proj_id))
The entire_time field exists solely for another function to iterate through and find the time of all of the fields for a particular user, or project. I can't seem to get a sum of the total_times (or entire_times) of 1 user for a particular project. Any help is greatly appreciated.

Responding to my own post, I found a workable solution: Not the most elegant though.
class Timekeeper(models.Model):
clock_in = models.TimeField(null=True)
clock_out = models.TimeField(null=True)
total_time = models.FloatField(null=True, blank=True)
entire_time = models.FloatField(null=True)
user_total_time = models.FloatField(null=True, blank=True)
user_project_total_time = models.FloatField(null=True, blank=True)
is_working = models.BooleanField(default=False)
users_time = models.ForeignKey(User, related_name="time_of_user", on_delete=models.CASCADE)
proj_time = models.ForeignKey(Project, related_name = 'time_of_project', on_delete=models.CASCADE)
In views.py
def clockout(request, proj_id):
user = User.objects.get(id=request.session['userid'])
this_time = user.time_of_user.last()
total_time_of_user = 0
total_time_of_user_project = 0
for i in user.time_of_user.all():
total_time_of_user += i.total_time
this_time.user_total_time = total_time_of_user
this_time.save()
for x in user.time_of_user.filter(proj_time=proj_id).all():
total_time_of_user_project += x.total_time
this_time.user_project_total_time = total_time_of_user_project
this_time.save()
This creates 2 new attributes to the Timekeeper model.

Related

Comparing Between datetime field in django

I have a model named Assignment in my project
This is how the Assignment model looks like
class Assignment(models.Model):
user = models.ForeignKey(
Teacher, on_delete=models.CASCADE, related_name='assignments')
unique_code = models.CharField(max_length=11, default=assignment_uniqe_id)
title = models.CharField(max_length=250)
deadline = models.DateTimeField()
created_at = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
subject = models.ForeignKey(
All_Subject, on_delete=models.CASCADE, related_name='assignment_subject')
classes = models.ManyToManyField(Classes)
submitted_by = models.ManyToManyField(Student, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return str(self.user) + " : " + self.title
And I want to check weather if the current date is greater then the deadline.
Please help me out

(Django) How to assign unique values to each user for something linked by ForeignKey?

My group project for school has us building a school management system. I have the following models:
Student:
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
User.is_student = True
enrolled_courses = models.ManyToManyField(Session, blank=True)
def __str__(self):
return f'{self.user.last_name}, {self.user.first_name}'
Session:
class Session(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
course_date_start = models.DateTimeField()
course_date_end = models.DateTimeField()
def session_id(self):
new_session_date = self.course_date_start.strftime('%Y')
return f'{new_session_date}{self.course.number}{self.pk}'
def __str__(self):
return f'{self.course.number} - {self.course.title} - {self.session_id()}'
Assignment:
class Assignment(models.Model):
session_link = models.ForeignKey(Session, on_delete=models.CASCADE)
created_date = models.DateTimeField(default=timezone.now)
due_date = models.DateField()
title = models.CharField(max_length=50)
total_points = models.IntegerField()
points_earned = models.IntegerField(blank=True, null=True)
objective = models.TextField()
def __str__(self):
return self.title
The problem right now is if I save one value of points_earned to a user, it saves that value to all, since they're linked by the FK.
What's the best way to handle it so each Student can have their own score for each assignment?
If you want each Student to have their own score for each assignment,then a solution would be to have a table to keep track of the score with those two models as foreign keys.
Use https://docs.djangoproject.com/en/3.1/topics/db/models/#intermediary-manytomany
class StudentAssignment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE)
points_earned = models.IntegerField(blank=True, null=True)

What is the difference between the fields associated with choice and to in the django model?

What is the difference between the fields associated with choice and to in the django model?
eg what is the difference between frontal and number_of_rooms field
What is the difference between defining choice and creating a model and defining the domain of another model?
thanks in advance
#django models.py
class Advertise(models.Model):
owner = models.ForeignKey(to="advertise.User", on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=100)
description = models.TextField(max_length=500)
price = models.PositiveIntegerField(default=0)
square_meter = models.PositiveIntegerField(default=0)
number_of_rooms = models.PositiveIntegerField(choices=NumberOfRoomsChoices.CHOICES)
building_age = models.PositiveIntegerField(choices=NumberOfBuildingAgeChoices.CHOICES)
floor = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOOR_CHOICES)
number_of_floors = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOORS_CHOICES)
number_of_bathrooms = models.PositiveIntegerField(choices=NumberOfBathroomsChoices.CHOICES)
heating = models.PositiveIntegerField(choices=HeatingChoices.CHOICES)
balcony_exists = models.BooleanField(default=False)
using_status = models.PositiveIntegerField(choices=UsingStatusChoices.CHOICES)
fee = models.PositiveIntegerField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status = models.PositiveIntegerField(choices=AdvertiseStatusChocies.CHOICES)
visibility = models.PositiveIntegerField(choices=AdvertiseVisibilityChoices.CHOICES)
# collections
frontal = models.ManyToManyField(to="advertise.Frontal")
interior_feature = models.ManyToManyField(to="advertise.InteriorFeature")
exterior_feature = models.ManyToManyField(to="advertise.ExteriorFeature")
locality = models.ManyToManyField(to="advertise.Locality")
transportation = models.ManyToManyField(to="advertise.Transportation")
landscape = models.ManyToManyField(to="advertise.Landscape")
sutiable_for_disabled =models.ManyToManyField(to="advertise.SuitableForDisabled")
def __str__(self):
return f"{self.title}"

How to implement a class based view when using django- finite state machine in django

I am making a leave process where an applicant will apply for leave and the leave will be queued so that the approver will either approve or reject the leave application. I came across django-fsm and drf-fsm-transitions and I thought of implementing this kind of work flow. I am using django 1.11 + python3 + django_rest_framework to build my API.
In the django app I have imported from django_fsm import transition, FSMIntegerField to models.py.
Leave Class
class Leave(models.Model):
LEAVE_STATUS_CREATED = 0
LEAVE_STATUS_APPLIED = 1
LEAVE_STATUS_APPROVED = 2
LEAVE_STATUS_REJECTED = 3
LEAVE_STATUS_PENDING = 4
LEAVE_STATUS_COMPLETE = 5
LEAVE_STATUS_CHOICES = (
(LEAVE_STATUS_CREATED, 'created'),
(LEAVE_STATUS_APPLIED, 'applied'),
(LEAVE_STATUS_APPROVED, 'approved'),
(LEAVE_STATUS_REJECTED, 'rejected'),
(LEAVE_STATUS_PENDING, 'pending'),
(LEAVE_STATUS_COMPLETE, 'complete'),
)
leave_id = models.AutoField(primary_key=True)
applicant = models.ForeignKey(
Employee, related_name='applicant', on_delete=models.CASCADE, null=True)
approver = models.ForeignKey(
Employee, related_name='approver', on_delete=models.CASCADE, null=True)
applied_on = models.DateTimeField(auto_now_add=True)
responded_on = models.DateTimeField(auto_now=True, null=True)
leave_type = models.ForeignKey(LeaveType, null=True)
approved = models.BooleanField(default=False)
rejected = models.BooleanField(default=False)
start_date = models.DateField()
return_date = models.DateField()
leave_status = FSMIntegerField(
choices=LEAVE_STATUS_CHOICES, default=LEAVE_STATUS_CREATED, protected=True)
comment = models.TextField(max_length=200)
leave_subject = models.CharField(max_length=40)
leave_reason = models.TextField(max_length=200)
total_days = models.IntegerField(null=True)
Transition
I have then implemented the following transitions in the leave class:
#transition(field=leave_status, source=LEAVE_STATUS_CREATED, target=LEAVE_STATUS_APPLIED)
def apply(self, comment):
self.applicant = applicant
self.leave_type = leave_type
self.start_date = start_date
self.return_date = return_date
self.leave_subject = leave_subject
self.leave_reason = leave_reason
print("Apply %s Leave").format(self.comment)
#transition(field=leave_status, source=LEAVE_STATUS_APPLIED, target=LEAVE_STATUS_APPROVED)
def approve(self, approver, responded_on, comment):
self.approver = approver
self.responded_on = responded_on
self.comment = comment
print("approve the leave")
#transition(field=leave_status, source=[LEAVE_STATUS_CREATED, LEAVE_STATUS_APPLIED], target=LEAVE_STATUS_REJECTED)
def reject(self, approver, responded_on, comment):
self.approver = approver
self.responded_on = responded_on
self.comment = comment
print("rejected leave ")
Then in the views I imported from drf_fsm_transitions.viewset_mixins import get_viewset_transition_action_mixin
Which I am getting the following logs when I run the server:
transitions = instance.get_all_status_transitions()
AttributeError: 'Leave' object has no attribute 'get_all_status_transitions'
Here is how my view class looks like:
class LeaveViewSet(
get_viewset_transition_action_mixin(Leave),
viewsets.ModelViewSet):
queryset = Leave.objects.all()
How to implement a class based view when using django-fsm in django

Django Query Filter Menu

I want to build a similar, but significantly simpler User list page with a query filter menu:
Player List from nhl.com
User can apply individual filters, or chain them. I prefer AJAX, but am happy to start off an 'apply filters' submit button.
Current look
class User(AbstractBaseUser):
id = models.AutoField(primary_key=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
modified = models.DateTimeField(auto_now=True, null=True, blank=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(verbose_name='email address', max_length=255, unique=True, )
date_of_birth = models.DateField('date of birth', null=True)
avatar = models.ImageField('profile picture', upload_to='static/images/avatars/', null=True, blank=True)
logline = models.CharField(max_length=100, blank=True)
driving = models.BooleanField(default=False)
license_class = models.IntegerField(blank=True, null=True, choices=LICENSE_CHOICES)
vehicle = models.CharField(max_length=100, blank=True)
show = models.ForeignKey(Show, on_delete=models.CASCADE, null=True, blank=True)
links = ArrayField(models.URLField(max_length=100, blank=True, null=True), blank=True, null=True)
focus = ArrayField(models.CharField(max_length=50, null=True, choices=FOCUS_CHOICES), blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
call_preference = ArrayField(models.CharField(max_length=90, choices=FOCUS_CHOICES, null=True), blank=True, null=True)
blocked = models.ManyToManyField('self', related_name='blocked', blank=True)
qualified_positions = ArrayField(models.CharField(max_length=50, choices=FOCUS_CHOICES, null=True), null=True, blank=True)
years = models.IntegerField(default=1)
trade = ArrayField(
models.CharField(max_length=50, choices=TRADE_CHOICES),
null = True,
blank = True
)
member = models.BooleanField(default=False)
available = models.BooleanField(default=False)
available_from = models.DateField(null=True, blank=True)
available_to = models.DateField(null=True, blank=True)
range = DateRangeField(null=True, blank=True)
objects = UserManager()
Filters:
- Available - BooleanField, if available on date specified
- Position - CharField choices, can pick 1
- Trade - BooleanField choices, can pick multiple
- Member - Is member of selected union
Currently have generic ListView, and UserManager() full of recently typed and untested queries that likely need much work.
def base_get(self, start_date, **kwargs):
#user = kwargs.pop('user')
rightthefucktoday = datetime.date.today()
rightthefucktomorrow = datetime.date.today() + datetime.timedelta(days=1)
f = []
if start_date and 'end_date' in kwargs: ## is user.range contains the range of dates
diff = kwargs.pop('end_date') - start_date
date_range = []
for i in range(diff.days + 1):
date_range.append(start_date + datetime.timedelta(days=i))
f = self.filter(range_range=(date_range)).order_by('years', 'member')#.exclude(user=user)
return f
elif start_date and not 'end_date' in kwargs:
## if end date isn't specified
if start_date == rightthefucktomorrow:
f = self.filter(available=True).order_by('years', 'member').exclude(available_to=rightthefucktoday) ## if the date specified is tomorrow
return f
else:
f = self.filter(range_contains = start_date).order_by('years', 'member')#.exclude(user=user) # if date specified is not tomorrow
return f
else: ## no date specified, which is impssible
f = self.filter(available=True).order_by('years', 'member')#.exclude(user=user) #return if available
return f
def get_by_position(self, position):
u = self.filter(qualified_positions_contains=position)
return u
def get_by_trade(self, *args):
shit = []
for i in args:
shit.append(i)
c = self.filter(trade_contains=shit)
return c
def get_by_union(self, union): ## input must be "IATSE 891", "IATSE 669", or "ACFC 2020"
return self.filter(union__union__exact_=union)
def get_by_member(self):
return self.filter(member=True) ##if only members
def master_query(self, start_date, *args, **kwargs): ## args must be trade details TODO: Test, and build test cases
f, u, c, k = []
if 'end_date' in kwargs: f = self.base_get(start_date, kwargs.pop('end_date'))
else: f = self.base_get(start_date)
it = f
if 'position' in kwargs: u = self.get_by_position(kwargs.pop('position')); it = it | u
if 'union' in kwargs: c = self.get_by_union(kwargs.pop('union')); it = it | c
if args.count() != 0: k = self.get_by_trade(args); it = it | k
if 'member' in kwargs: you = self.get_by_member(); it = it | you
return it
If someone could nudge me in the right direction as far as handling the template and view properly - I'd love you forever
Thank you
One way to apply filters is by using GET parameters. (The parts after the '?' in URLs [e.g. https://search.yahoo.com/search?p=test+search]). So create a form in your template with method='GET' and handle the GET parameters via self.request.GET (I think you have to enable the RequestContextProcessor for this).

Categories

Resources