简体   繁体   中英

Django - URL template tag with 2 arguments

I'm new to Django and sorry if the question is silly. I have a URL with two slugs, one for the category which is a manytomany field and one for the posts:

path('<slug:slug_staticpage>/<slug:slug>/', views.post, name='post_detail')

views.py

def post(request, slug, slug_staticpage):
    category = get_object_or_404(StaticPage, slug_staticpage=slug_staticpage)
    blogpost = get_object_or_404(Post, slug=slug)
    post = Post.objects.filter(slug=slug)
    page_id = category.pk
    related_posts = Post.objects.filter(static_page__pk=page_id)[:6]
    return render(request, "blog/blog-post-final.html", {'slug': slug, 'slug_staticpage': category.slug_staticpage, 'post':post, 'related_posts':related_posts})

models.py

class Post(models.Model):
    title = models.CharField(max_length=300)
    content = RichTextField()
    slug = models.SlugField(max_length=200, unique=True)
    published = models.DateTimeField(verbose_name="Published", default=now())
    image = models.ImageField(verbose_name="Image", upload_to="blog", null=True, blank=True)
    author = models.ForeignKey(User, verbose_name="Author", on_delete=models.PROTECT)
    categories = models.ManyToManyField(Category, verbose_name="Categories", related_name="get_post")
    static_page = models.ManyToManyField(StaticPage, verbose_name="Página estática", related_name="get_post")
    created = models.DateField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=STATUS, default=0)

I want to display those URLs in my homepage via the template tag, but I don't know how to retrieve the slug_staticpage slug:

<a href="{% url 'blog:post_detail'  slug_staticpage=post.slug_staticpage slug=post.slug %}">

The above syntax is not working, I can only retrieve the slug of the post.

Can someone help me sort this out? Thanks a lot for your precious help :)

Askew

As you have a Many-to-Many relationship, you should have a single url for each of those static_page objects.

You can achieve that via iterating over the static_page objects:

{% for slug_url in post.slug_staticpage.all %}
   <a href="{% url 'blog:post_detail'  slug_staticpage=slug_url slug=post.slug %}"> 
{% endfor %}

although I'm not sure whether you really need such relationship or not.

I solved it myself by adding the following to models.py

def get_absolute_url(self):
   return reverse('blog:post_detail', kwargs={'slug_staticpage':self.static_page.slug_staticpage, 'slug':self.slug})

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM