Display all Employees with present and absent status - django

I Have Two models
User Model and DailyPresent model with user as foreign_key in DailyPresent model.
class DailyPresentReport(models.Model):
PRESENT = 'present'
ABSENT = 'absent'
ON_LEAVE = 'on_leave'
PRESENT_CHOICES = (
(PRESENT, 'Present'),
(ABSENT, 'Absent'),
(ON_LEAVE, 'On Leave'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='daily_present_report')
present = models.CharField(max_length=10, choices=PRESENT_CHOICES, default=ABSENT)
punch_in = models.DateTimeField(null=True, blank=True)
punch_out = models.DateTimeField(null=True, blank=True)
date = models.DateField(null=True, blank=True)
work_time = models.DurationField(null=True, blank=True)
class Meta:
ordering = ['id']
def __str__(self):
return f'{str(self.user)}: {self.present}'
If User logs in then he is automatically made present
but when user doesn't login nothing happens.
Now I want to display a table with all users with Present and Absent Fields.
Please help me.. Thanks in advance

you can use Q module, processing the combination of "or" conditions when searching:
from django.db.models.query_utils import Q
dailyPresents = DailyPresentReport.objects.filter(Q(present="PRESENT") |
Q(present="ABSENT"))
or use .exclude to exclude the On Leave:
dailyPresents = DailyPresentReport.objects.exclude(present="ON_LEAVE")

Related

show related fields in django admin panel

I have 3 django models. Requirement Model has its own fields. RequirementImage and RequirementDOc models have Requirement as foreign key in them which are used for multiple image and multiple document upload. In admin ,I want to show the Requirement along with the images and documents related to requirement. How can i show it in admin panel.
i want to show a view where i can list all fields of Requirement and RequirementImages and RequirementDocs together.
Below is the exact code of models.
class Requirement(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length = 5000)
mobile = models.CharField(max_length=15, null=True, blank=True)
email = models.EmailField(null=True, blank=True)
city = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class RequirementImage(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True, validators=[
FileMimeValidator()
], upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/images")
class RequirementDoc(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
requirement_file = models.FileField(null=True, blank=True, upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/docs")
Python version is 3.7.12 and django version is 3.2.14
in models.py
from django.utils.safestring import mark_safe
class RequirementImage(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True, validators=[
FileMimeValidator()
], upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/images")
def photo_tag(self):
return mark_safe('<img src="/your_path/{0}">'.format(self.image))
photo_tag.short_description = 'Photo of prescription'
photo_tag.allow_tags = True
and when you want to use it in admin
list_display = ('get_photo')
def get_photo(self, obj):
return obj.photo.photo_tag()
get_photo.short_description = 'Photo of prescription'
This is the right answer.we need to use TabularInline.
class RequirementImageInline(admin.TabularInline):
model = RequirementImage
fields = ['image']
extra = 1
class RequirementDocInline(admin.TabularInline):
model = RequirementDoc
fields = ['requirement_file']
extra = 1
class RequirementAdmin(admin.ModelAdmin):
inlines = [RequirementImageInline,RequirementDocInline]
Reference: https://stackoverflow.com/a/74233744/1388835

how to filter objects by a specific choice

I have model like this:
class ScientificInfo(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_approved = models.CharField(max_length=64, choices=(('0', 'yes'), ('1', 'no')), blank=True)
is_interviewed = models.BooleanField(default=False)
how can I filter this model by is_approved field which is a choicefield? I wrote this line but doesnt work
approved = ScientificInfo.objects.filter(is_approved__in='0').all()
Using the exact field lookup would probably make more sense here:
approved = ScientificInfo.objects.filter(is_approved__exact='0').all()
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#exact
Put values inside () as
approved = ScientificInfo.objects.filter(is_approved__in=('0')).all()

How to search for objects in the Django User model

I have a Profile model:
from django.contrib.auth.models import User
class Profile(models.Model):
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.DateField(null=True, blank=True)
bio = models.TextField(blank=True, max_length=1000)
location = models.CharField(max_length=100, blank=True)
...
And a search contacts view:
class SearchContactsView(ListView):
model = Profile
template_name = 'users/contact_search.html'
context_object_name = 'qs'
def get_queryset(self):
q1 = self.request.GET.get('contact_name')
q2 = self.request.GET.get('contact_location')
if q1 or q2:
return Profile.objects.filter(Q(first_name__icontains=q1) |
Q(last_name__icontains=q1),
location__icontains=q2)
return Profile.objects.all()
It is working fine but I would like to be able to search for contacts via the user field as well. Does anyone know a way to do that?
EDIT my user's username's are created by them when they sign up to the site and are currently uneditable. They are displayed on the admin page via a dropdown since they are a OneToOneField. I think my issue is that django recognises them only as an IntegerField('pk') but I need to somehow cast them as a string value. Am I right in thinking that, and if so how can this be achieved?
You can add to your template to allow user to input user_username and save that username to q3:
q3 = self.request.GET.get('user_username')
After that you can adjust your If condition accordingly, then change your return to something like:
Profile.objects.filter(Q(first_name__icontains=q1) |
Q(last_name__icontains=q1),
location__icontains=q2,
user__username=q3)

Django merge two QuerySets

I want to merge these two QuerySets. HotkeyAndPrefix do not have entries for every Collection in all_collections. This means len(all_collections) >= len(all_collections_hotkeys_and_prefixes). How can i merge these two QuerySets? If there is no entrie found for a Collection in HotkeyAndPrefix I want hotkey = None, prefix=None. Can I achieve this in one query?
models.py:
class Collection(models.Model):
creator = models.ForeignKey(User, blank=True, null=True)
...
class HotkeyAndPrefix(models.Model):
user = models.ForeignKey(User, null=True)
assigned_collection = models.ForeignKey(Collection, null=True)
hotkey = models.CharField(max_length=1, blank=True, null=True)
prefix = models.CharField(max_length=20, blank=True, null=True)
class Meta:
unique_together = ('user', 'assigned_collection')
view.py
admin = User.objects.filter(username='admin')[0]
all_collections = Collection.objects.filter(creator=admin)
current_user = request.user
all_collections_hotkeys_and_prefixes = HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user)
You need to use exclude() query. You can take the list of values which are in the
HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user) queryset
using
all_collections_hotkeys_and_prefixes_values = all_collections_hotkeys_and_prefixes.values_list('assigned_collection',flat=True)
and you can filter out the value, not in the all_collections_hotkeys_and_prefixes_values with one more query
all_collections_hotkeys_and_prefixes_excluded = all_collections.exclude(pk__in=all_collections_hotkeys_and_prefixes_values)
now you have two querysets, one of collection for which a user has hotkey/prefix and another for which the user doesn't

Django generic foreign key reverse filter

I have a model called "Comments" which uses a generic foreign key:
class CommentManager(models.Manager):
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
"""
ct = ContentType.objects.get_for_model(model)
qs = self.get_query_set().filter(content_type=ct)
if isinstance(model, models.Model):
qs = qs.filter(object_pk=force_text(model._get_pk_val()))
return qs
class Comment(models.Model):
"""
A user comment about some object.
"""
status = models.CharField(max_length=12, blank=True, null=True)
sub_status = models.CharField(max_length=500, blank=True, null=True)
comment = models.TextField()
content_type = models.ForeignKey(
ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField(_('object ID'))
content_object = generic.GenericForeignKey(ct_field="content_type",
fk_field="object_pk")
One of the things you can put comments on are Tickets:
class Ticket(CommonModel):
type = models.ForeignKey(TicketType)
priority = models.PositiveSmallIntegerField()
status = models.ForeignKey(TicketStatus)
access_serial_number = models.PositiveSmallIntegerField(null=True)
parent = models.ForeignKey('self', null=True, related_name='child')
submitted = models.DateTimeField()
I do a lot of filtering of Tickets - in the past all I did with Comments on Tickets is that when I displayed a Ticket, I used Comments.objects.for_model(ticket) to find all the Comments for it. But now what I want to do is find Tickets that have a specific text in the comment. There is no comment_set or equivalent with GenericForeignKey.
This is what I've come up with, but it's pretty horrible:
comment_ticket_ids = [int(c.object_pk) for c in Comment.objects.for_model(Ticket).filter(comment__icontains='error')]
tickets = Ticket.filter(status=open_status, id__in=comment_ticket_ids)
There must be a better way.
Perhaps you could add something using .extra() to help. Instead of
comment_ticket_ids = [int(c.object_pk) for c in Comment.objects.for_model(Ticket).filter(comment__icontains='error')]
tickets = Ticket.filter(status=open_status, id__in=comment_ticket_ids)
You could attach the field id_wanted:
extra_select = {
'id_wanted': 'CASE WHEN (SELECT COUNT(*) FROM tickets WHERE comments something) > 0 THEN TRUE ELSE FALSE END'
}
Then filter for tickets with the extra select:
tickets = Tickets.objects.filter(ticket__status=open_status, id_wanted__isnull=False).extra(extra_select)
It's not fully clear to me why you can't have a FKey relationship between these two models.