Below is my models.py
.
class Report(models.Model):
company_name = models.CharField(max_length = 40, default = "-")
favorite = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='Fav', related_name='favorite_reports')
def __str__(self):
return self.company_name
class Fav(models.Model) :
report = models.ForeignKey(Report, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='favs_users')
class Meta:
unique_together = ('report', 'user')
def __str__(self) :
return '%s likes %s'%(self.user.username, self.report.company_name[:10])
Below is views.py
def post(self, request, pk) :
t = Report.objects.get(id = pk)
fav = Fav(user=request.user, report=t)
try:
fav.save() # In case of duplicate key
print(request.user.favorite_reports) #home.Report.None
print('t =', t.favorite) # t = auth.User.None
print('fav =',fav.report, fav.user) # fav = untitle hello1
print('uesr =',request.user, request.user.favorite_reports,request.user.favs_users) #uesr = hello1 home.Report.None home.Fav.None
except IntegrityError as e:
pass
return redirect('home:homepage')
I want to show different button color to user whether user fav some report or not. So I checked request.user.favorite_reports
and request.user.favs_users
after I save Fav
but it return home.Report.None home.Fav.None
But When I print fav.report, fav.user
It returns well. Why this happened?
How can I check user
Fav
some report
in template
?
like {% if report.company_name in user.favorite_reports %}
But It dosen't works.
CodePudding user response:
You should call request.user.favorite_reports.all()