Matching data from two functions in django context? - python

I'm struggling with matching contexts in my django project. I want to insert a .annotate() queryset, perfectly in just a set variable.
I know it sounds weird but it's the best as I can describe it.
I tried using .filter(), as it makes sense to me logically, but it doesn't quite work.
my views.py
from django.shortcuts import render
from django.db.models import Count
from django.db.models import Sum
from .models import Offer_general
from .models import Offer_details
import datetime
# Create your views here.
def offer_general_list(request):
#queryset = Offer_general.objects.filter(status=1).order_by('-id')
context = {}
context["data"] = Offer_general.objects.filter(status=1).order_by('-id')#stuff from Offer_general
context["test"] = Offer_details.objects.values('fk_offer_general_id').annotate(sum=Sum('fk_offer_general_id'))
return render(request, "index_offers.html", context)
def offer_general_details(request):
context = {}
context["data"] = Offer_details.objects.all()
return render(request, "offer_detail.html", context)
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
STATUS = (
(0,"Inactive"),
(1,"Active")
)
class Offer_type(models.Model):
type = models.TextField()
class Meta:
ordering = ['-type']
def __str__(self):
return self.type
class Offer_general(models.Model):
offer_name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
status = models.IntegerField(choices=STATUS, default=0)
type = models.ForeignKey(Offer_type, on_delete= models.PROTECT)
class Meta:
ordering = ['-id']
def __str__(self):
return self.offer_name
class Offer_localization(models.Model):
localization = models.TextField()
class Meta:
ordering = ['-localization']
def __str__(self):
return self.localization
class Offer_details(models.Model):
slug = models.SlugField(max_length=200, unique=True)
localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole")
fk_offer_general_id = models.ForeignKey(Offer_general, on_delete= models.PROTECT)
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
requirements = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-id']
def __str__(self):
return self.slug
TL;DR, i want the sum() returned in context["test"] to be nicely loopable, with id being equal to fk_offer_general_id.
The problem is shown in the following image:(I dont have reputation to post image :()
https://ibb.co/XtpkKpC

Related

Check if user is in the manager column in order to create a post/task

I'm learning in DJango and I have learned alot of stuff from the documentation and also in StackOverflow. Right now, I'm kinda stuck and I just want to know who can I check in a class based view, if the user is in the manager column in job model/ It can also be in the manager model that's fine too.
I tried using UserPassesTestMixinin order to check if user is part of it but I'm getting an error of Generic detail view createjob must be called with either an object pk or a slug in the URLconf.
I just need someone to point me to the right direction or give me a hint.I also tried, this:
class createjob (LoginRequiredMixin,CreateView):
model = Job
fields = ['member','title', 'description', 'file']
def form_valid(self,form):
form.instance.manager=self.request.user
return super().form_valid(form)
But it's giving me an error of Cannot assign "<SimpleLazyObject: <User: edlabra>>": "Job.manager" must be a "Manager" instance.
Here's my views.py:
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, CreateView
from .models import Job, Member
from profiles.models import User
from django.contrib.auth.decorators import login_required
# Create your views here.
class jobs(LoginRequiredMixin,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)
class createdjobs(LoginRequiredMixin,ListView):
model = Job
template_name = 'users/manager_jobs.html'
context_object_name = 'jobs'
def get_queryset(self):
return Job.objects.filter(manager__manager=self.request.user)
class teamview(LoginRequiredMixin,ListView):
model = Member
template_name = 'users/manage_team.html'
context_object_name = 'members'
def get_queryset(self):
return Member.objects.filter(manager__manager=self.request.user)
class createjob (LoginRequiredMixin,UserPassesTestMixin,CreateView):
model = Job
fields = ['member','title', 'description', 'file']
def test_func(self):
job=self.get_object()
if self.request.user == Job.manager:
return True
return False
Models.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.ForeignKey(Manager, on_delete=models.CASCADE)
member = models.ForeignKey(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
assign user from manager table.
def form_valid(self,form):
form.instance.manager=Manager.objects.get(manager=self.request.user)
return super().form_valid(form)

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)

Python Django - Count objects based on owner that is the user

I have users who listed their textbook.
I need to count objects in Textbook model and display total count in the side menu.
Here is my Model
from django.db import models
from django.http import HttpResponse
from django.urls import reverse
from django.contrib.auth.models import User
from django.utils.functional import cached_property
class Textbooks(models.Model):
owner = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True)
title = models.CharField(max_length=1000)
isbn = models.CharField(max_length=20)
author = models.CharField(max_length=250)
edition = models.CharField(max_length=50)
rrp = models.CharField(max_length=30)
about = models.TextField(max_length=1000, null=True)
textbook_image = models.FileField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('textbooks:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
I used Custom template tag
class CustomTag(template.Node):
def render(self, context):
context['my_custom_tag_context'] = Textbooks.objects.filter(owner=self.user.request).count()
return ''
#register.tag(name='get_custom_tag')
def get_custom_tag(parser, token):
return CustomTag()
enter image description here
AttributeError at /
'CustomTag' object has no attribute 'user'. It seems that i cant use filter in template tag.
is there any other way i can filter them and show the count by owner who is logged in?
Here is what i intend to have.
enter image description here
You have to change below line in...
user = context['request'].user
context['my_custom_tag_context'] = Textbooks.objects.filter(owner=user).count()
instead of
context['my_custom_tag_context'] = Textbooks.objects.filter(owner=self.user.request).count()
You can get user from request.

Django two ForeignKey from same model

In Pegawai model, I need two ForeignKeys to:
Jabatan model
unit_kerja field of Jabatan model
How to apply these for my Pegawai model? Only the first one worked.
Here is my models.py:
from django.db import models
from django.urls import reverse
# Create your models here.
class UnitKerja(models.Model):
nama_unit_kerja = models.CharField(max_length=100)
def get_absolute_url(self):
return reverse("users:unitkerja")
def __str__(self):
return self.nama_unit_kerja
class Jabatan(models.Model):
nama_jabatan = models.CharField(max_length=100)
level_jabatan = models.IntegerField()
unit_kerja = models.ForeignKey(UnitKerja, on_delete=models.CASCADE, blank=True, null=True)
def get_absolute_url(self):
return reverse("users:jabatan")
def __str__(self):
return self.nama_jabatan
class Pegawai(models.Model):
nip = models.CharField(max_length=100, unique=True)
nama_pegawai = models.CharField(max_length=100)
alamat = models.CharField(max_length=255)
jabatan = models.ForeignKey(Jabatan, on_delete=models.CASCADE)
#this line#
unit_kerja = models.ForeignKey(Jabatan.unit_kerja, on_delete=models.CASCADE, blank=True, null=True)
def get_absolute_url(self):
return reverse("users:pegawai")
def __str__(self):
return self.pegawai
There is no such thing as a foreign key to a field, but you don't need it anyway. You can always access the UnitKerja instance by using multiple traversal, for example:
my_unit_kerja = my_pegawai.jabatan.unit_kerja
Or you can have a helper property, if the above is too much work:
class Pegawai(models.Model):
...
#property
def unit_kerja(self):
return self.jabatan.unit_kerja
and then simply use
my_pegawai.unit_kerja

Order post by date

I've created a list of post and now I want order this list by date of publishing. If I use order_by(-post_publishing_date) in the view the shell show me this error:
NameError: name 'post_publishing_date' is not defined
models.py
class PostModel(models.Model):
post_title = models.CharField(max_length=70)
post_short_description = models.TextField(max_length=200)
post_contents = models.TextField()
post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True)
post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE, related_name="connected_author")
post_keyconcept = models.ManyToManyField(KeyConceptModel, related_name="connected_keyconcept")
slug = models.SlugField(verbose_name="Slug", unique="True")
post_highlighted = models.BooleanField(default=False)
def __str__(self):
return self.post_title
def get_absolute_url(self):
return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
views.py
class SinglePostGDV(DetailView):
model = PostModel
template_name = "manuscriptus_post_detail.html"
class ListPostGDV(ListView):
model = PostModel
template_name = "manuscriptus_home.html"
queryset = PostModel.objects.filter().order_by(-post_publishing_date)
urls.py
urlpatterns = [
path("it/blog/", ListPostGDV.as_view(), name="homeManuscriptusView"),
path("it/blog/<slug:slug>/", SinglePostGDV.as_view(), name="singlepostManuscriptusView"),
]
What I did wrong?
Ad hoc ordering
Well Python is correct. There is no identifier post_publishing_date, you pass the name of the column through a string, so:
class ListPostGDV(ListView):
model = PostModel
template_name = "manuscriptus_home.html"
queryset = PostModel.objects.filter().order_by('-post_publishing_date')
Define an inherent ordering on the model
Note that you can also give a model an "inherent" ordering in the Meta class:
class PostModel(models.Model):
post_title = models.CharField(max_length=70)
post_short_description = models.TextField(max_length=200)
post_contents = models.TextField()
post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True)
post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE, related_name="connected_author")
post_keyconcept = models.ManyToManyField(KeyConceptModel, related_name="connected_keyconcept")
slug = models.SlugField(verbose_name="Slug", unique="True")
post_highlighted = models.BooleanField(default=False)
def __str__(self):
return self.post_title
def get_absolute_url(self):
return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug})
class Meta:
ordering = ['-post_publishing_date']
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
If you do this, all queries to this model will implicitly be ordered by -post_publishing_date. So this means that you can not "forget" to order the objects properly.
So then you do not have to order it in the views. You can of course only define one such "inherent" ordering, and it is not clear if you want to use one here.
order_by argument should be string:
queryset = PostModel.objects.filter().order_by('-post_publishing_date')

Categories