I am implementing a likes system for my post. I have used a ManyToManyField in my model.
models.py
class MarketingMaestro (models.Model):
product_title = models.CharField(max_length=250)
total_value = models.IntegerField()
branding_video = models.CharField(max_length=300)
likes = models.ManyToManyField(User, related_name='likes', blank=True)
In this I get all the list of the users, and if someone likes the post it is updated in the field. But when I am trying to implement the logic where if the user has already liked the post he/she will be able to see the dislike button only.
While doing so I am fetching all the values from the db and checking particular likes field but it is showing error 'QuerySet' object has no attribute 'likes'
It is giving me error on the line
if marking_maestro.likes.filter(id=request.user.id).exists():
I tried printing the value but is it returning just the queryset <QuerySet [<MarketingMaestro: MarketingMaestro object (1)>]> and if i print the product_title using (marking_maestro.product_title) but then I get the error saying 'QuerySet' object has no attribute 'product_title'
-views.py
def brand(request):
# fetching all the projects
marking_maestro = MarketingMaestro.objects.all()
is_liked = False
print(marking_maestro)
if marking_maestro.likes.filter(id=request.user.id).exists():
is_liked = True
# fetching the votes
emailID = request.user.email
context = {
'is_liked' : is_liked
}
return render(request, 'brand.html', {'marking_maestro' : marking_maestro}, context)
for performing queries like marking_maestro.likes.filter(id=request.user.id).exists(): or marking_maestro.product_title you need to first get an object of MarketingMaestro.
Here, only mistake you are doing is that, you are performing queries on QuerySet rather than MarketingMaestro object.
So what you need to do is
marking_maestro = MarketingMaestro.objects.first()
(here I've taken first to just illustrate the concept, you can take whatevet the object you want)
and then perform whatever the queries you want to.
Related
I'm trying to create a 'saved post' feature on a website. I'm struggling with how to create a query that I can use to populate my HTML template with posts.
Here are my models:
class User(AbstractUser):
pass
class Post(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=500)
class SavedPost(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey (User, on_delete=models.CASCADE, null=True)
My .views looks like this
def savedpostsview(request):
posts = Post.objects.all
savedposts = posts.savedpost_set(user = request.user)
return render(request, "posts/savedposts.html",{
'savedposts': savedposts
})
Right now I'm getting the error "'function' object has no attribute 'savedpost_set'".
I know I'm getting something wrong syntactically, but I've been reading documentation forever and can't figure out what it is for the life of me. Does anybody have any insight into what I'm doing wrong?
first of all here Post.objects.all all() is a function and thats why error is "'function' object has no attribute 'savedpost_set'"
You should call Post.objects.all() this will return queryset.
Then You are trying to reverse query on queryset which not possible and will throw error.
All you want is this Post.objects.filter(savedpost__user=request.user)
I am building a BlogApp and I was working on a feature and I am stuck on a error.
operator does not exist: character varying = integer
LINE 1: ...d" = "taggit_tag"."id") WHERE "taggit_tag"."name" IN (SELECT...
I am trying to retrieve all the comments commented by user from Tags which were used in comment's post.
When I access the comments then it is keep showing that error when i access the variable in template.
models.py
class Post(models.Model):
post_user = models.ForeignKey(User, on_delete=models.CASCADE)
post_title = models.CharField(max_length=30)
tags = models.TaggableManager()
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post_of = models.ForeignKey(Post, on_delete=models.CASCADE)
views.py
class page(request):
tagQuery = Tag.objects.filter(post__comment__user=request.user)
#this is showing error
subquery = Comment.objects.filter(post_of__tags__name__in=tagQuery)
context = {'subquery':subquery}
return render(request, 'page.html', context)
It was showing
The QuerySet value for an exact lookup must be limited to one result using slicing.
So i used __in but then it keep showing that error.
Any help would be much Appreciated. Thank You
Rather than filtering according to queryset itself, you need to filter according to values of certain field:
class page(request):
tagQuery = Tag.objects.filter(post__comment__user=request.user)
subquery = Comment.objects.filter(post_of__tags__name__in=tagQuery.values_list('name'))
context = {'subquery':subquery}
return render(request, 'page.html', context)
I am trying to add a condition to my notification to check if a user's total number of likes for all the posts related to him and send a notification if reached a certain number. I have filtered the total likes by the post author but I keep receiving AttributeError: 'Like' object has no attribute 'filter'
To summarize here is the post model
class Post(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='author')
num_likes = models.IntegerField(default=0, verbose_name='No. of Likes')
likes = models.ManyToManyField(User, related_name='liked', blank=True)
Here is the likes model
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
value = models.CharField(choices=LIKE_CHOICES,
default='Like', max_length=8)
def like_progress(sender, instance, *args, **kwargs):
like = instance.filter(post__author=Post.author).count()
post = like.post
sender = like.user
if like == 12:
notify = Notification(post=post, sender=sender,
user=post.author, notification_type=3)
notify.save()
post_save.connect(Like.like_progress, sender=Like)
My Question: How to fix this error?
The problem is you are calling a Model's function on an instance. I recommend you read about the Django queries.
Basically that error happens because the filter() function can be used from a model's manager or an existing queryset, and you are using it from an instance of the model.
Here's a quick example to make it clearer:
This is a queryset, you can get one by using a model's manager aka the objects attribute.
from myapp.models import MyModel
queryset = MyModel.objects.filter(my_attribute=True)
The resulting queryset can be further filtered
queryset2 = queryset.filter(some_other_attribute=False)
Now to put it simple, a queryset can be seem as a list of instances. In this example from the MyModel's model and you can get any instance from the queryset or iterate the queryset and go through all the instances.
instance_1 = queryset2.first()
instance_2 = queryset2.last()
# or
for instance in queryset2:
print('This is an instance', instance)
Instances do not have the same filter() functionality as a manager or a queryset as they are a single element that cannot be filtered further.
So this this will raise an AttributeError
try:
instance_1.filter(my_attribute=False)
except AttributeError:
pritn("This won't work!")
So getting to your example, the correct way to do it should look something like this:
def like_progress(sender, instance, created=None, *args, **kwargs):
# You may want to stop this if the objects was updated and not created.
if not created:
return
# get all likes from the author
qs_likes = Like.objects.filter(post__author=instance.author)
likes_count = qs_likes.count()
# You can get the post and the sender from the current instance
post = instance.post
sender = instance.user
if likes_count == 12:
notify = Notification.objects.create(post=post, sender=sender,
user=post.author, notification_type=3)
On a side note, you should not be connecting Model's functions the signals as they do receive different arguments in different order. So just define like_progress outside the model.
like = instance.filter(post__author=Post.author).count()
You should use filter this way:
like = Like.objects.filter(post__author=post.author).count()
#note that it should be post.author not Post.author
This will eliminate your current errors, but I doubt you can achieve what you want. I guess what you are trying to do is whenever there is a like instance saved, you want to count the number of conts that the post.author received, and if the like-count is 12, you send a notification.
But the like_progress is a method, are you going to call it by like.like_progress?
I have a list model that uses User as foreign key twice.
The 1st is as ForeignKey to the creator. And 2nd as ManyToManyField for users for that list
class TodoList(models.Model):
creator = models.ForeignKey(User, default=1,related_name='created_by')
list_users = models.ManyToManyField(User,related_name='list_users')
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=10, blank=True, null=True)
status = models.SlugField(choices=STATUS_CHOICES, default='active', max_length=10)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
What I want to do is:
Get the users for the list.
Get the list for the logged in user.
Here is my code for #1:
todolist = get_object_or_404(TodoList, slug=list_slug)
users = todolist.list_users
The first line works fine. But when I get the list_users it will return auth.User.None even though the list has 3 users added to it through admin.
Here is my code for #2:
user = request.user
user_todo_lists = user.todolist.all()
The page will send an:
AttributeError: 'User' object has no attribute 'todolist'
but when I rename the list_users to user. It will work just fine. What could be the problem?
Regarding your first problem, you probably want todolist.list_users.all(). (That is, you want a QuerySet, not a Manager.)
Regarding your second problem, I'm not sure which relation you're actually trying to get at, but in either case you need to use the attribute defined by related_name. (That is, user.created_by.all() or user.list_users.all().)
I'm new to Django and I'm in the process of converting a PHP project into Python etc.
I'm trying to do something super simple, but I keep getting the following error:
AttributeError at /news/1/
'QuerySet' object has no attribute 'slug'
Here is my most of my Model to help explain:
class Article(models.Model):
title = models.CharField(max_length=200)
STATUS_CHOICES = ((1,'Published'), (2,'Hidden'), (3,'Draft'))
status = models.IntegerField(choices=STATUS_CHOICES,default=3)
pub_date = models.DateField('date published')
tags = TaggableManager()
header_width = models.IntegerField(default=1,blank=True,null=True)
header_height = models.IntegerField(default=1,blank=True,null=True)
header = models.ImageField(upload_to='news/',width_field='header_width',height_field='header_height',blank=True,null=True)
header_filter = models.BooleanField('Enable filter',default=1)
excerpt = HTMLField(blank=True)
body = HTMLField(blank=True)
custom_link_text = models.CharField(max_length=20,default="Read More")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
slug = AutoSlugField(unique=True,max_length=200,populate_from='db_slug',default="",slugify=return_value)
def __str__(self):
return self.title
Im currently just testing to pull through the slug, so my view method currently looks like this:
def detail_redirect(request, pk):
a = Article.objects.all().filter(pk=pk)
return HttpResponse(a.slug)
# return redirect('news:detail',args=(a.slug,pk))
The plan is for this method to redirect to another URL in my application. It queries the DB via the primary key and fetches the Slug, which I then pass on to the redirect shortcut.
It seems to be something that should just work, but it's not. It's really frustrating. The object i query appears to return ok. Because of my __str__ method it returns the title. But any other attributes throw and error. Could it be todo with visibility such as being private or protected?
I'm hoping it's something simple I'm missing. Let me know if you require more code/detail to help explain.
Thanks for taking the time to look at my question.
filter always returns a queryset, which is a list-like object potentially consisting of many items. Querysets do not have model attributes, only their members do. You should use get instead:
a = Article.objects.get(pk=pk)
(Note you don't need all(), in either version of the code.)