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)
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'm about to make a simple webshop, and are currently working on my add to cart button.
When I click the add to cart button right now, it returns an error as follows:
FieldError at /add-to-cart/box-1/
Exception Value:
Cannot resolve keyword 'ordered' into field. Choices are: box, box_id, id, order, quantity, title
Related Code
views.py:
def add_to_cart(request, slug):
# Get the item from the slug via get_object_or_404 method
box = get_object_or_404(Box, slug=slug)
# Check if the user have an order
order_box = OrderBox.objects.create(box=box)
order_qs = OrderBox.objects.filter(user=request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
# Check if order item is in the order
if order.box.filter(box__slug=box.slug).exists():
order_box.quantity += 1
order_box.save()
else:
ordered_date = timezone.now()
order = Order.objects.create(user=request.user, ordered_date=ordered_date)
order.items.add(order_box)
return redirect('webshop:shop-box', slug=slug)
models.py
class Order(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
items = models.ManyToManyField(OrderBox)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
I've been searching around, and can find different questions on this topic, however I can't understand what the issue is.
I'd much appreciate some help to figure out where I've mistaken, thank you!
It looks like OrderBox does not have a field called ordered (or user for that matter), your Order model does. So without knowing too much about your project, you either need to create a queryset for your Order model instead of OrderBox or filter your OrderBox queryset by their related Order models (if they are related, it appears so from the available fields listed in the error message). If this is the case, you could
try OrderBox.objects.filter(order__user=request.user, order__ordered=False)
I'm trying to create a view that allows one to see all blog posts written by a particular author. Here's the URL pattern I'm using:
url(r'^user/(?P<username>[\w-]+)/$', views.user_articles, name="user_articles"),
And here's my view:
def user_articles(request, username):
articles = Article.objects.filter(author=username).order_by('-date')
return render(request, "articles/article_list.html", {'articles': articles})
This is returning the error:
ValueError at /articles/user/danny/
invalid literal for int() with base 10: 'danny'
Editing to add model as well:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
body = HTMLField('Body')
date = models.DateTimeField(auto_now_add=True)
thumb = models.ImageField(default="keys.jpg", blank=True)
author = models.ForeignKey(User, default=None)
danny is a valid username, and it should be a string, not an integer, so I'm not sure what's going wrong here. Any ideas?
Considering author, which is a ForeignKey to auth.User .
Your query should be
Article.objects.filter(author__username=username)
instead of ...Article.objects.filter(author=username)
Post your model but I assume the association between models, is a Foreign Key. So 'author' on your model Article is likely an ID and not a string. So instead of the username 'danny' try retrieving 'danny's ID.
I'm developing a social platform and currently coding the like functionality for user posts. However, I can't seem to make it work. These are my Models.py:
class Post(models.Model):
user = models.ForeignKey(User)
posted = models.DateTimeField(auto_now_add=True)
content = models.CharField(max_length=150)
picturefile = models.ImageField(upload_to="post_content", blank=True)
class Like(models.Model):
user = models.ForeignKey(User, null=True)
post = models.ForeignKey(Post, null=True)
I pass the post ID through my url as 'post_id', and then in my views:
def liking(request, post_id):
newlike = Like.objects.create()
newlike.post = post_id
newlike.user = request.user
newlike.save()
return redirect(reverse('dashboard'))
However, it returns the following error:
Cannot assign "'47'": "Like.post" must be a "Post" instance.
Does anyone knows what I'm missing or doing wrong?
You are passing newlike.post a number (integer field) while it is expecting a Post instance.
This sould work:
from django.http.shortcuts import get_object_or_404
def liking(request, post_id):
post = get_object_or_404(Post, id=post_id)
newlike = Like.objects.create(user=request.user, post=post)
return redirect(reverse('dashboard'))
Note 1: Better use the handy shortcut get_object_or_404 in order to raise a 404 error when the specific Post does not exist.
Note 2: By calling objects.create will automatically save into the db and return an instance!
newlike.post should be a Post object, not an int.
You need to find post by id first:
post = Post.objects.get(pk=post_id)
newlike.post = post
or, if you don't want to do this lookup:
newlike.post_id = post_id
Models:
class Patient(models.Model):
patientID = models.CharField(max_length=200, unique=True, help_text='Insert PatientID')
birth_date = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD')
gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED')
class Examination(models.Model):
number_of_examination = models.IntegerField()
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
date_of_examination = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD')
class GeneralData(models.Model):
examination = models.ForeignKey(Examination, on_delete=models.CASCADE)
height = models.FloatField(default='-', help_text= '[m] not [cm]! ')
weight = models.FloatField(default='-', help_text= '[kg]')
aha_classification = models.IntegerField(choices=AHA_CHOICES, default=0)
My Problem:
I don't know how to query the general data object with the number of examination = 1 for one special patient. I want to display the object on the detail page of the patient. I can query on the Examination class without problems. But then I just don't know how to query the generaldata object. The detail page loads only the Patient model. Due to this I have to query from the Patient model over the Examination model to the Generaldata model right? Or is it possible to load other models in the template? Thanks for your help!
Got it!
Added to my DetailView:
def DetailView(generic.DetailView):
model = Patient
template_name = 'app/detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(DetailView, self).get_context_data(**kwargs)
# Add in a QuerySet
context['FirstGeneral'] = GeneralData.objects.filter(examination__number_of_examination=1, examination__patient=get_object_or_404(Patient, pk=self.kwargs.get('pk')))
return context
"The detail page loads only the Patient model (...) is it possible to load other models in the template ?"
You don't "load" models "in the template", you pass them (or any other object you want) to the template's context - most often from your view code but actually from whereever you want to render a template. And yes of course you can pass just whatever you want, populating the template context is up to you.
The query which will work is:
Generaldata.objects.filter(examination__number_of_examination=1, examination__patient=Testpatient)
but this is in the wrong order.
Why is it "in the wrong order" ??? And if that query works what prevents you from using it ?
NB : if you're using generic DetailView, adding extra context is documented here