django like integration not working - python

I want to integrate like model in my app. Then this Q/A really helped me to start over it.
class Like(models.Model):
user = models.ManyToManyField(User, related_name='likes')
article = models.ForeignKey(Article)
created = models.DateTimeField(auto_now_add=True)
total_likes = models.IntegerField(default=0)
But later i found one problem
Cannot resolve keyword 'slug' into field. Choices are: content, creation_date, id, like, title, user, user_id
Well now started question what is really slug field here ? in name="{{ article_slug }}". Well nothing printed in html page [name=""] And then i found
slug = request.POST.get('slug', None)
article = get_object_or_404(Article, slug=slug)
liked, created = Like.objects.create(article=article)
this code is causing above issue.So i changed the code to slug=slug ==> content=slug then this time i am getting different error..
<p>No Article matches the given query.</p>
Ah .. this time i got it.. Now i changed to name="{{ id }}" .. hm nothing happened same error..
silly me.. definitely i am missing something really very simple. Anybody got it?

get_object_or_404 works with a specific, unique field that is specified on the model.
Therefore ensure that the slug field is specified on your Article model class. Example:
class Article(models.Model):
slug = models.SlugField(max_length=50)
# remaining fields

Related

Cannot access object.id in postgreSQL with django app deployed to Heroku (internal server error 500)

I deployed a Django blog app to Heroku and having problem accessing the objects through the objects' id.
When Debug=True in settings.py, everything works fine.
And even when Debug=False, there is no other problem such as static files issue, things are working fine. I searched many articles but most of them are about static files issues, not same as my situation.
First, My models.py:
class Post(models.Model):
title = models.CharField(verbose_name='TITLE', max_length=120)
slug = models.SlugField(verbose_name='SLUG', unique=True, allow_unicode=True, max_length=120)
content = RichTextUploadingField(verbose_name='POST CONTENT')
create_date = models.DateTimeField(verbose_name='Created date', auto_now_add=True)
author = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
class Bookmark(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(verbose_name='SLUG', unique=True, allow_unicode=True, max_length=100)
address = models.URLField(verbose_name='url', unique=True)
description = models.CharField(max_length=256)
category = models.ForeignKey(BookmarkCategory, on_delete=models.CASCADE, null=True, blank=True)
And in the urls.py:
path('post/<int:id>/', views.PostDetailView.as_view(), name='post_detail'),
path('bookmark/<int:id>/update/', views.BookmarkUpdateView.as_view(), name='bookmark_update'),
The problem occurs when I try to access my Post or Bookmark object in the templates using id, like:
{% url 'myblog:post_detail' post.id %}
or
{% url 'myblog:bookmark_update' bookmark.id %}
What I'm expecting is the DetailView or UpdateView of the objects, but instead I have internal server error (my 500.html shows up.)I tried int:pk instead of int:id too, but just same error.
Again, things are totally fine when Debug=True, and also everything else works fine even when Debug=False.There are several archiveViews based on the Post model and searching function, etc..they are all working.
So I tried changing the urls.py like:
path('post/<slug>/', views.PostDetailView.as_view(), name='post_detail'),
path('bookmark/<slug>/update/', views.BookmarkUpdateView.as_view(), name='bookmark_update'),
And then it just works! I can see the views I requested using slugs from the templates. Problem occurs only when I try to access the objects using the objects' ID.
So I suppose there is some problem with postgreSQL, possibly some problem with the way it stores objects' ID (maybe because ID is not explicitly defined in the models.py?), because when I worked with SQLite3 locally, there was no problem accessing through objects' ID.
For now I can just avoid the problem using slug instead of int:id but I want to use int:id because slug-based URLs are a bit too redundant.
Please anybody can help identifying what the problem is and what the solution may be?

django url without pk

I have been trying for too long now to get my urls working with my simple models and view. There is something I am definitely not understanding.
I wish to create a url similar to:
.../department/team,
where I do not use the PK of department object but the name instead.
My model looks like:
class Department(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return 'Department: ' + self.name
class Hold(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
my view looks like (UPDATED):
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'departments_list'
def get_queryset(self):
return Department.objects.all()
class DepartmentView(generic.DetailView):
model = Department
template_name="depdetail.html"
slug_field = "name"
slug_url_kwarg = "name"
my url looks the following: UPDATED
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<name>', views.DepartmentView.as_view(), name='depdetail')
]
and finally my html:
<h1> Hello there {{ object.name }} student</h1> </br>
<b> Choose your team:<b> </br>
however i keep getting page not found or must be slug or pk..
I hope someone can help me out so I can wrap my head around this.
UPDATED
It works now :) Thank you for the replies.
By default Django will look for a pk or a slug field when you use a DetailView. You must override get_object() method to change this behaviour:
get_object() looks for a pk_url_kwarg argument in the arguments to the view; if this argument is found, this method performs a primary-key based lookup using that value. If this argument is not found, it looks for a slug_url_kwarg argument, and performs a slug lookup using the slug_field.
That being said, your approach has other problems. It is always better to use a slug instead of a name for other reasons. For example, name is not guaranteed to be unique and also it may have characters which are not URL safe. See this question for a detailed discussion on how to use slug fields.

Challenging django queryset construction

I have a Django app where users log in, set various topics, and then leave comments under the said topics. The following models reflect this rudimentary set up:
class Topic(models.Model):
topic_text = models.TextField()
submitted_on = models.DateTimeField(auto_now_add=True)
class Comment(models.Model):
comment_text = models.TextField()
which_topic = models.ForeignKey(Topic)
submitted_by = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now_add=True)
For each user, I am trying to get all topics where any one of the most recent 5 comments were written by the user. In other words, if a user has not commented among a topic's most recent 5 comments, the topic will be excluded from the queryset.
So how do I go about forming this queryset? Btw I was going to show you what I've tried, but it's woefully inadequate and obviously wrong. Can someone please help?
I haven't tested it, but a subquery should work. Something like this:
Topic.objects.filter(
comment__submitted_by__in=Comment.objects.values(
'submitted_by'
).order_by(
'-submitted_on'
).limit(5),
submitted_by=user
)
(Add .prefetch_related('comment_set') if you plan to access the comments.)

django - get latest object with model method in template

I have a model with method.
class Book(models.Model):
title = models.TextField()
class Review(models.Model):
content = models.TextField()
book = models.ForeignKey(Book,related_name="book_reviews")
def lastreview(self):
return self.objects.order_by('-id')[:1]
but once I use this method in template
{{book.book_reviews.lastreview.content}}
it is showing nothing..
what am i missing here?
I believe you are trying to retrieve the latest review of a book (which was not clear from your question). The related reviews for a book can be accessed by book.book_reviews. It is a QuerySet rather than a single Review object, hence {{ book.book_reviews.lastreview }} will fail.
I would recommend moving the lastreview method directly under Book, like:
class Book(models.Model):
title = models.TextField()
def lastreview(self):
try:
return self.book_reviews.order_by('-id')[0]
except IndexError:
return None
Now you can access the latest review of a book in your template by
{{ book.lastreview.content }}
Note: I recommend adding a DateTimeField to Review, as finding the latest review based on id can be misleading. For e.g., someone can edit an old review and it will not be shown as the latest.

Django ManyToMany Template Questions

Good Morning All,
I've been a PHP programmer for quite some time, but I've felt the need to move more towards the Python direction and what's better than playing around with Django.
While in the process, I'm come to a stopping point where I know there is an easy solution, but I'm just missing it - How do I display manytomany relationships in a Django Template?
My Django Model: (most of the fields have been removed)
class Category(models.Model):
name = models.CharField(max_length=125)
slug = models.SlugField()
categories = models.ManyToManyField(Category, blank=True, null=True)
class Recipe(models.Model):
title = models.CharField('Title', max_length=250)
slug = models.SlugField()
class Photo(models.Model):
recipe = models.ForeignKey(Recipe)
image = models.ImageField(upload_to="images/recipes", blank=True)
So, there is the basic models I'm using in my application called "recipes."
With that said, there are two questions I'm looking for answers on:
How would I go about displaying the categories for a recipe on it's details page?
How would I go about displaying the image for the recipe on it's details page?
If I go into the Python shell, and input the following, I do get a result:
>>> photos = Photo.objects.filter(recipe=1)
>>> photos
[<Photo: Awesome Pasta>]
>>> for photo in photos:
... print "Photo: %s" % photo.logo
...
Photo: images/recipes/2550298482_46729d51af__.jpg
But when I try something like the following in my template, I get an error saying "Invalid block tag: 'photo.image'."
{% for photo in photos %}
{% photo.image %}
{% endfor %}
Although, even if that did work, the ID is still hard coded into the view, how would you go about having this dynamic for each recipe?
Details Page View.py snippet:
def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = Photo.objects.filter(recipe=1)
return render_to_response('recipes/recipes_detail.html', {'p': p, 'photos': photos})
Thanks in advance for the help and understanding for what is probably a very simple question to all of you!
UPDATE: When removing the additional fields in the models, I forgot the categories field for the Recipes model.
From what I can see, I think you've got a small syntax error:
{% photo.image %}
should instead be:
{{ photo.image }}
The {% %} notation is used for django template tags. Variables, on the other hand, are expressed with the {{ }} notation.
To make it dynamic, you can take advantage of the fact that your Photo model has a foreign key to Recipe. This means that there will be a reverse relation from the Recipe instance you've loaded using the slug back to the set of photos:
def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = p.photo_set.all()
Hopefully that will work for you. Glad to see you're enjoying working with Django!

Categories