How to create breadcrumb in my view function BY mptt - django

How to create breadcrumb in my view function?
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
slug = models.SlugField( null=True, blank=True)
description = models.TextField(null=True, blank=True)
image = models.ImageField(
upload_to=user_directory_path, default='posts/default.jpg')
def get_absolute_url(self):
return reverse('Category:post_single', args=[self.slug])
class Meta:
ordering = ('-name',)
def __str__(self):
return self.name
class Post(models.Model):
class NewManager(models.Manager):
def get_queryset(self):
return super().get_queryset() .filter(status='published')
options = (
('draft', 'Draft'),
('published', 'Published'),
)
category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=250)
excerpt = models.TextField(null=True)
image = models.ImageField(
upload_to='uploads/', default='posts/default.jpg')
image_caption = models.CharField(max_length=100, default='Photo by Blog')
slug = models.SlugField(max_length=250, unique_for_date='publish')
publish = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blog_posts')
content = models.TextField()
status = models.CharField(
max_length=10, choices=options, default='published')
favourites = models.ManyToManyField(
User, related_name='favourite', default=None, blank=True)
likes = models.ManyToManyField(
User, related_name='like', default=None, blank=True)
like_count = models.BigIntegerField(default='0')
views = models.PositiveIntegerField(default=0)
thumbsup = models.IntegerField(default='0')
thumbsdown = models.IntegerField(default='0')
thumbs = models.ManyToManyField(User, related_name='thumbs', default=None, blank=True)
objects = models.Manager() # default manager
newmanager = NewManager() # custom manager
def get_absolute_url(self):
return reverse('blog:post_single', args=[self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
#views
def post_single(request, post):
post = get_object_or_404(Post, slug=post, status='published')
postcat = Post.objects.filter(category=post.category)
fav = bool
if post.favourites.filter(id=request.user.id).exists():
fav = True
allcomments = post.comments.filter(status=True)
page = request.GET.get('page', 1)
paginator = Paginator(allcomments, 10)
try:
comments = paginator.page(page)
except PageNotAnInteger:
comments = paginator.page(1)
except EmptyPage:
comments = paginator.page(paginator.num_pages)
user_comment = None
if request.method == 'POST':
comment_form = NewCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.post = post
user_comment.save()
return HttpResponseRedirect('/' + post.slug)
else:
comment_form = NewCommentForm()
session_key = 'view_post_{}'.format(post)
if not request.session.get(session_key,False):
post.views +=1
post.save()
request.session[session_key] = True
return render(request, 'blog/single.html', {'post': post,'Category': Category.objects.all(),'Category2': postcat,
'comments': user_comment, 'comments': comments, 'comment_form': comment_form, 'allcomments': allcomments, 'fav': fav})
blog/single.html
{{ node.name }}
I want in my single post info (post_single) breadcrumb with category. Something like this: Category > Subcategory > Sub-Subcategory .,,,
Someone told me to use get_ancestors:
Example:
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">🏠</li>
{% for node in post.category.ancestors %}
<li class="breadcrumb-item">{{node.name}}</li>
{% endfor %}
<li class="breadcrumb-item active" aria-current="page">{{ object }}</li>
</ol>
</nav>
{{ post.category }}
How to implement this with my model?
Thank you. I would be grateful.

Related

How to add Latest Post Of Category Show in the Detail Article

Views.py
def PostView(request,slug):
Postdata = Post.objects.get(slug=slug)
side_data = Post.objects.all()
category_posts = Post.objects.filter(category__cat_slug=slug)
return render(request,'post-detail.html',{'Postdata':Postdata,'side_data':side_data,'category_posts':category_posts})
Models.py
class Category(models.Model):
name = models.CharField(max_length=100)
category_description = FroalaField()
cat_slug = models.SlugField(max_length=200, null=False)
def __str__(self):
return self.name
options = (
('draft', 'Draft'),
('published', 'Published'),
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
category = models.ForeignKey(
Category, on_delete=models.CASCADE,null=True,)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='myapp_post')
updated_on = models.DateTimeField(auto_now= True)
content = FroalaField()
feature_img = models.ImageField(upload_to = 'images/', null=False)
status = models.CharField(max_length=10, choices=options, default='draft')
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
Post-detail.html
<h4>Related Post</h4>
<br>
{% for data in category_posts %}
<h4>{{data.title}}</h4>
{% endfor %}
I'm trying to Add Category Related latest Posts in the Article.
For Example
If an article in which category name is Django Tutorial. In the Article Detail, I want to add the Related latest post of this category.
you can try this :
Post.objects.filter(slug=slug).order_by('-id')[0]
order by id will give you the last one added
or you can use directly :
Post.objects.filter(slug=slug).last()

django if in queryset is always false

class Product(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
featured = models.BooleanField(default=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
class OrderItem(models.Model):
item = models.ForeignKey(Product, on_delete=models.CASCADE )
quantity = models.IntegerField(default=1)
item_cart = models.CharField(max_length=20, null=True, blank=True)
active = models.BooleanField(default=True)
class Cart(models.Model):
user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE)
products = models.ManyToManyField(OrderItem, blank=True)
subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
"""
"""
def product_list_view(request):
queryset = Product.objects.all()
item = OrderItem.objects.all()
cart_obj, new_obj = Cart.objects.new_or_get(request)
print(item)
context = {
'product_list': queryset,
'cart' : cart_obj,
'orderitem' : item
}
return render(request, "products/list.html", context)
"""hmtl page list.hmtl
{% if obj in orderitem %} doesnt print else print allways
"""
{% for obj in product_list %}
<div class='col my-3'>
{{obj.title}}
{{obj.price}}
{{orderitem}}
{% if obj in orderitem %}
<h1>in cart</h1>
{% else %}
<h5>delete</h5>
{% endif %}
</div>
{% endor %}
orderitem = <QuerySet [<OrderItem: iphone 6s>, <OrderItem: hi>]>,
obj = hi ,
in list.hmtl if obj in orderitem always shows error and also tried obj.title in orderitem
But always else statement is printed without any error
trying to check the product is in ordereditem...

Django show extra content in class based view with ForeignKey models

I'm trying to add extra content to Djangos Class-based view to the template
I have some models like this
class District(models.Model):
district = models.CharField(max_length=255, null=False, unique=False, blank=True)
def __str__(self):
return self.district
class Street(models.Model):
street_name = models.CharField(max_length=255, null=False, unique=False, blank=True)
district = models.ForeignKey(District, verbose_name=_('district'), on_delete=models.CASCADE, null=True, blank=True)
zone = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.street_name
class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL)
timestamp = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=1, choices=STATUS, default=CREATED)
comment = models.CharField(max_length=255, null=True, unique=False, blank=True)
name = models.CharField(max_length=255, null=True, unique=False)
street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True)
class ArticlesListView(LoginRequiredMixin, PermissionRequiredMixin,ListView):
model = Article
paginate_by = 50
context_object_name = "articles"
permission_required = 'is_staff'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['Filter_name'] = Article.objects.order_by().values('name').distinct()
context['Filter_user'] = Article.objects.order_by().values('user').distinct()
return context
def get_queryset(self, **kwargs):
return Article.objects.all()
And late in the template
{% for f in Filter_name %}
<ul>
<li>{{f.name}}</li>
</ul>
{% endfor %}
How can I display a list of the district names and a list of the author names in the template with ForeignKey?
U can try something like that
{% for item in model_1.foreign_model_set.all %}
<h1>{{ item }}</h1>
{% endfor %}

Django - Annotation not showing in template

I'm trying to get annotations showing in my templates. I have two models (model1 and model2) and I want to show the number of model2's related to model1.
Here is my views.py:
def model2_count(request, pk):
model2count = models.Model1.objects.filter(pk=model1.pk).annotate(title_count=Count(‘model2__title'))
return render(request, 'model1/_model1.html', {‘m2c’: model2count})
Here is the template (model1/_model1.html):
I tried this:
{% for object in m2c %}</h3>
{{ object.title }}
{{ object.title_count }}
{% endfor %}
And tried this:
{% if m2c.title_count %}
{{ m2c.title_count }}
{% endif %}
I've been pulling my hair out over this for a couple days and can't figure it out. The following has been largely unhelpful:
Django - Annotating Weighted AVG by Group
Django: Annotation not working?
Django templates are not showing values of annotations
Django annotated value in template
What's frustrating is that I can't even say why applying these solutions hasn't worked.
Any input is appreciated.
Also, here are my models with all the BS taken out.
class Publication(models.Model):
title = models.CharField(max_length=150, unique=False, blank=False)
contributors_note = models.TextField(max_length=300, blank=False)
website = models.URLField()
publisher = models.CharField(max_length=250, unique=False)
publication_date = models.DateField(default=datetime.date.today)
slug = models.SlugField(allow_unicode=True, unique=False)
content_type = models.CharField(max_length=100, unique=False)# In this field user's define the type of content (blog, newspaper article, publication etc)
research_type = models.CharField(max_length=100, unique=False)# In this field user's define whether the research is based on primary or secondary research
user = models.ForeignKey(Current_user, related_name="publication")
created_at = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category, related_name="publication",null=True, blank=False)
comment = models.TextField()
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse(
"publication:single",
kwargs={
"username": self.user.username,
"pk": self.pk
}
)
class Meta:
ordering = ["-created_at"]
class Assessment(models.Model):
title = models.CharField(max_length=150, unique=False, blank=False)
publication = models.ForeignKey('publication.Publication', on_delete=models.CASCADE, related_name='assessment')
analyst = models.ForeignKey(Current_user, null=True, blank=True, related_name="assessment")
created_at = models.DateTimeField(auto_now_add=True)
approved_comment = models.BooleanField(default=False)
key_finding1 = models.TextField(max_length=300)
key_finding2 = models.TextField(max_length=300)
key_finding3 = models.TextField(max_length=300)
ratings_range = (
('1', 'Very Weak'),
('2', 'Weak'),
('3', 'Moderate'),
('4', 'Strong'),
('5', 'Very Strong'),
)
content_rating_1 = models.CharField(max_length=1, choices=ratings_range)
content_rating_1_comment = models.TextField(max_length=300)
content_rating_2 = models.CharField(max_length=1, choices=ratings_range)
content_rating_2_comment = models.TextField(max_length=300)
content_rating_3 = models.CharField(max_length=1, choices=ratings_range)
content_rating_3_comment = models.TextField(max_length=300)
content_rating_4 = models.CharField(max_length=1, choices=ratings_range)
content_rating_4_comment = models.TextField(max_length=300)
content_rating_5 = models.CharField(max_length=1, choices=ratings_range)
content_rating_5_comment = models.TextField(max_length=300)
source_rating_1 = models.CharField(max_length=1, choices=ratings_range)
source_rating_1_comment = models.TextField(max_length=300)
source_rating_2 = models.CharField(max_length=1, choices=ratings_range)
source_rating_2_comment = models.TextField(max_length=300)
source_rating_3 = models.CharField(max_length=1, choices=ratings_range)
source_rating_3_comment = models.TextField(max_length=300)
source_rating_4 = models.CharField(max_length=1, choices=ratings_range)
source_rating_4_comment = models.TextField(max_length=300)
source_rating_5 = models.CharField(max_length=1, choices=ratings_range)
source_rating_5_comment = models.TextField(max_length=300)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.title
class Meta:
ordering = ["-created_at"]
Bad mistake on my part. The solution's given above worked. Here is my final code:
views.py
class PublicationDetail(SelectRelatedMixin, generic.DetailView):
model = models.Publication
select_related = ("category", "user")
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get("username")).annotate(assessment_count=Count('assessment'))
Fellow noobs that follow:
- It's easier for the people that want to help you (and faster for you) if you just post your original code instead of trying to get smart. Don't be embarrassed. I would've saved us all time if I had just done that.
First aggregations are done only using the field name i.e model2 not model2__title
Next getting counts of annotated columns recommended to use .values or values_list but not required.
https://docs.djangoproject.com/es/2.1/topics/db/aggregation/#cheat-sheet
model1 = Model1.objects.get(pk=model1.pk)
model2count = (
Model1.objects.annotate(count=Count('model2'))
.filter(pk=model1.pk)
.values_list('title', 'count', named=True)
)
template.html
{% for object in model2count %}
{{ object.title }}
{{ object.count }}
{% endfor %}

can't click category url Django 1.10

enter image description here
I see URL, but click on it not goving at page.
If I go directly to the link, the page opens. In my opinion the matter lies in the def post_list
model
class Category(models.Model):
name = models.CharField(max_length=128, unique=True, verbose_name='Название')
slug = models.SlugField(unique=True)
image = models.ImageField(null=True, blank=True, verbose_name='Изображение')
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
class Meta:
verbose_name = 'Категории'
verbose_name_plural = 'Категории'
def __str__(self): # For Python 2, use __unicode__ too
return self.name
def get_absolute_url(self):
return reverse('show_category', kwargs={'slug': self.slug})
class Post(models.Model):
category = models.ForeignKey(Category, default=1, verbose_name='Категория')
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, verbose_name='Пользователь')
title = models.CharField(max_length=120, verbose_name='Заголовок')
slug = models.SlugField(unique=True)
image = models.ImageField(null=True, blank=True, verbose_name='Изображение')
content = models.TextField(max_length=10000, verbose_name='Контент')
updated = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name='Обновлено')
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Создано')
keywords = models.CharField(max_length=1024, blank=True, null=True)
description = models.CharField(max_length=1024, blank=True, null=True)
class Meta:
verbose_name = 'Статьи'
verbose_name_plural = 'Статьи'
ordering = ["-timestamp", "-updated"]
def __str__(self): # For Python 2, use __unicode__ too
return self.title
def get_absolute_url(self):
return reverse('detail', kwargs={'slug': self.slug, 'category': self.category})
views
only problem page
def post_list(request):
queryset_list = Post.objects.all()
category_list = Category.objects.all()
search = request.GET.get("s")
if search:
queryset_list = queryset_list.filter(
Q(title__icontains=search) |
Q(content__icontains=search) #|
#Q(user__first_name__icontains=search) |
#Q(user__last_name__icontains=search)
).distinct()
paginator = Paginator(queryset_list, 5) # Show 5 contacts per page
page = request.GET.get('page')
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"category_list": category_list,
"title": "Новое"
}
return render(request, "post_list.html", context)
urls
from .views import (
post_list,
post_detail,
show_category,
)
urlpatterns = [
url(r'^$', post_list, name="list"),
url(r'^(?P<category>[-\w]+)/(?P<slug>[-\w]+)/$', post_detail, name="detail"),
url(r'^(?P<slug>[-\w]+)/$', show_category, name='show_category'),
]
html
{% for cat in category_list %}
<li>{{ cat.name }}</li>
{% endfor %}