Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

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

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"><a href="/">??</a></li>
{% for node in post.category.ancestors %}
<li class="breadcrumb-item"><a href="{{node.get_absolute_url}}">{{node.name}}</a></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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...