Django URL in template with slug in it - python

I'm trying to link to a blog post but it has a slug in it, and i'm not sure how to pass it in. I've looked online but I didn't apparently understand the answers since I haven't found a solution yet.
I'm trying to do like the following in my template href="{% url 'blog_detail' post.categories.5 slug=blender-task-name post.14 %}", but it gives me the following exception: Could not parse the remainder: '-task-name' from 'blender-task-name'
post.categories.5 because i'm trying to access category with id 5
and post.14 because it's the post with the id 14
This is how the object i'm trying to link to looks like
URLS.py:
urlpatterns = [
path("", views.blog_index, name="blog_index"),
path("<category>/<slug>/<int:pk>/", views.blog_detail, name="blog_detail"),
path('<category>/', views.blog_category, name='blog_category'),
]
Models.py:
class Category(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Post(models.Model):
slug = models.SlugField(max_length = 250, null = True, blank = True)
title = models.CharField(max_length = 250, default="Blog Post")
body = models.TextField()
created_on = models.DateTimeField(null=True)
last_modified = models.DateTimeField(null=True)
categories = models.ForeignKey('Category', related_name='posts', default="2", unique=False, on_delete=models.CASCADE)
class Comment(models.Model):
author = models.CharField(max_length=60)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE)

Related

Django filter by category

i want to see specific category wise post,
i created category app and blog app.i want show top 5 or 10 post in home.html.that's why i need 4 specific category.
but i can't filter(category) from post model.i cant access category because i created it another app..
i want to filter by category.
model.py for category
class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True)
category_name = models.CharField(max_length=50,unique=True)
slug = models.SlugField(allow_unicode=True,max_length=100,unique=True)
description =models.TextField(max_length=300,blank=True)
cat_image = models.ImageField(upload_to = 'photo/categories',blank = True)
created_at = models.DateTimeField(auto_now_add=True)
model.py for blog
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True, max_length=250, null=True, blank=True)
subtitle = models.CharField(max_length=255, blank=True)
heder_image = models.ImageField(null=False,blank=True,upload_to="images/")
heder_image_url = models.CharField(null=True,blank=True,max_length=200)
heder_image_Under_line = models.TextField(null=True,default="image")
# author = models.ForeignKey(Profile, on_delete=models.PROTECT)
author = models.ForeignKey(User, on_delete=models.CASCADE)
updated_on = models.DateTimeField(auto_now= True)
created_on = models.DateTimeField(auto_now_add=True)
body = RichTextField(max_length=100000)
status = models.IntegerField(choices=STATUS, default=0)
meta_description = models.TextField(max_length=300, blank=True,default='')
category = models.ForeignKey(Category,on_delete= models.CASCADE)
views.py
def home(request):
category = Category.objects.all().filter(parent=None)
post_by_category = Post.objects.filter(published=True).order_by('-created_on')#filter by category name
slider = Post.objects.filter(slider=True).order_by('-created_on')
context = {
'category':category,
'post_by_category':post_by_category,
'slider':slider,
'counter':Counter,
}
return render(request,'home.html',context)
Django also supports a special __ (double underscore) syntax to follow relationships when filtering. So the following should also work:
post_by_category = Post.objects.filter(category__category_name="aaa", published=True)
post_by_category = Post.objects.filter(category=Category.objects.get(category_name="aaa"))
This should work if you want filter post by specific category name.

Why is the URL not working after adding foreignkey field to model?

I'm creating a blog application and I added a category for its blog posts. When adding a new category it can be can be done without any problem. But the problem is I can't find posts for a specific category ID and get an error like
Field 'id' expected a number but got 'health'
But before I updated field category charafield to forenkeyfied it worked without any problem.
Here is my code:
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = SummernoteTextField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
image = models.ImageField(upload_to='images',null=True, blank=True)
category = models.ForeignKey('blog.category', on_delete=models.SET_NULL, null=True, blank=True)
class category(models.Model):
name = models.CharField(max_length=80)
def __str__(self):
return self.name
views.py
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats.replace('-', ' '))
return render(request, 'categories.html', {'cats':cats.replace('-', ' '), 'category_posts':category_posts})
forms.py
class PostForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name'))
class Meta:
model = Post
fields = ('title', 'category','author', 'content', 'image','status')
You didn't share the full traceback but the error likely is caused by this line
Post.objects.filter(category=cats.replace('-', ' '))
You are filtering against the category foreign key using a string hence the error.
What you intended seems to be to filter against the category name:
Post.objects.filter(category__name=cats.replace('-', ' '))

I want to add user's id on the url path or in the address of the page

i have a url on my page that is "http://127.0.0.1:8000/affiliation/link/10006/".
In the above url I want to add the user id along so that it looks like :"http://127.0.0.1:8000/affiliation/link/01/10006/" something like this, whereas '01' is the user id of the user who uploaded the product.
Below are the files.
views:
#Display individual product and render short links for all using pyshorteners
def link_view(request, uid):
results = AffProduct.objects.get(uid=uid)
slink = "http://127.0.0.1:8000/" + request.get_full_path()
shortener = pyshorteners.Shortener()
short_link = shortener.tinyurl.short(slink)
return render(request, 'link.html', {"results": results, "short_link": short_link})
models:
#Product details uploaded
class AffProduct(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo')
product_title = models.CharField(max_length=255)
uid = models.IntegerField(primary_key=True)
specification = models.CharField(max_length=255)
sale_price = models.IntegerField()
discount = models.IntegerField()
img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/")
img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/")
promote_method = models.TextChoices
terms_conditions = models.CharField(max_length=255, null=True)
promote_method = models.CharField(
max_length=20,
choices=promote_choices,
default='PPC'
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
urls:
urlpatterns = [
path('link/<int:uid>/', views.link_view, name='link_view')
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if you really want user.id in your path you can add it just like "uid" in your current urlpatterns
path('link/<int:user_id>/<int:uid>/', views.link_view, name='link_view')
# and your view signature would be:
def link_view(request, user_id, uid):
but if you just need the current user object, it can be obtained from "request" object passed into your view
def link_view(request, uid):
user = request.user
# ...

AttributeError; Dynamic url for list of charts by category issue (queryset filter)

Django 'CategorisedListView' object has no attribute 'slug' or Page not found (error 404) issue
I'm on Django 2.0, using generic class list view. I have tried dynamic url based on slug and queryset filter on slug to get list of charts by category.
Please help! I've been stuck here for a couple of days since.
views.py
class CategoriesView(generic.ListView):
template_name = 'Bokeh/categories.html'
context_object_name = 'all_categories'
def get_queryset(self):
return Category.objects.all()
class CategorisedListView(generic.ListView):
model = Category
template_name = 'categories/list_of_charts_by_category.html'
context_object_name = 'categorised'
def get_queryset(self):
self.category = get_object_or_404(Category, name = self.kwargs['slug'])
return Chart.objects.filter(category=self.slug)
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
image_file = models.ImageField(default=None, unique=True)
slug = models.SlugField(max_length=100, unique=True)
parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True, null=True, related_name='children')
def __str__(self):
return self.name
def get_absolute_url(self):
return '{slug}/'.format(slug=self.slug)
class Meta:
ordering = ('name',)
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Chart(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(max_length=250)
url = models.URLField(default=None, blank=True)
embed_url = models.TextField(default=None, blank=True)
image_file = models.ImageField(default=None, unique=True)
code_file = models.FileField(default=None, blank=True, unique=True)
chart_library = models.CharField(max_length=250)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
tag = TaggableManager()
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.name + ' - ' + self.chart_library
def get_absolute_url(self):
return reverse('Bokeh:detail', kwargs={'pk': self.pk})
def read_file(self):
data = self.code_file.path
with open(self.code_file.path, 'r', encoding='UTF-8') as data:
content = data.read()
return content
class Meta:
ordering = ('name',)
urls.py
path("categories/", views.CategoriesView.as_view(), name='categories'),
# /Bokeh/categories/<category_slug>
path("categories/<slug:slug>/", views.CategorisedListView.as_view(), name='list_of_charts_by_category'),
it is supposed to query the database when a specific category is clicked and return the list of charts categorised under that specific category. However, the page throws 'CategorisedListView' object has no attribute 'slug'
The lookup you're doing in get_queryset() isn't quite right. Firstly, you seem to be looking up the Category by name rather than by the slug. Then you try and filter the Charts using their category attribute, but instead of passing the category you pass a non-existent attribute self.slug.
Try changing the implementation to this:
def get_queryset(self):
# Lookup the Category using it's slug attribute, not name, and assign to local variable
category = get_object_or_404(Category, slug=self.kwargs['slug'])
# Now lookup the Charts using the category we just looked up
return Chart.objects.filter(category=category)

ValueError at /author/admin/ in Django

I have the following blog project :
urls.py conf :
url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts')
posts/models:
class Post(models.Model):
title = models.CharField(max_length=200)
summary = models.CharField(max_length=500, default = True)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
category = models.ManyToManyField('Category')
author = models.ForeignKey(User, default=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)
def __str__(self):
return self.title
def slug(self):
return slugify(self.title)
posts/views:
def getAllPosts(request, author=False):
latest_posts = Post.objects.all().order_by('-pub_date')
comments = Comment.objects.all().order_by('-pub_date')
author_posts = User.objects.get(id=author)
author_posts = author_posts.post_set.all()
context = {
'latest_posts':latest_posts,
'comments':comments,
'author_posts':author_posts
}
return render(request, 'posts/getAllPosts.html', context)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
templates/posts/getAllPosts:
<a href={% url 'grabAuthorPosts' author=post.author.username %}>
{{post.author}}</a>
I am trying to make it so that when the post.author link is clicked, the user will be taken to a page consisting of posts related to that particular author. The link formulation itself seems ok, as when clicked on a post created by admin, the url reads localhost/author/admin/
I believe my problem is in getting the context variable author_posts to work. I'm new to Django so any explanation greatly appreciated.
latest_posts, as well as author=False is used elsewhere in the template to get all posts regardless of author, which works fine.
The error is :
ValueError at /author/admin/
invalid literal for int() with base 10: 'admin'

Categories