Home > Software design >  Django primary key url issues
Django primary key url issues

Time:04-10

I am makeing a simple blog project. In my project, there is one page where there is a list of all the blog posts. If you click on the title of the post you are taken to the post. I used (?P\d ) I the URL path so the user would be directed to the correct post. However, this did not work. Any help would be much appreciated.

all_posts.html

    {% extends "base.html" %}
{% block content %}
<div >
  <h1>Blog Posts</h1>
</div>
<div >
 {% for blog_post in object_list %}
 <table >
   <ul >
     <li><a  href="{% url 'blog_app:view' pk=blog_post.pk %}">{{ blog_post.post_title }}</a></li>
   </ul>
</table>
 {% endfor %}
</div>
{% endblock %}

modles.py

from django.db import models

# Create your models here.
class Blog_Post(models.Model):
    slug = models.SlugField(max_length=1000, editable=False, null=True)
    post_title = models.CharField(max_length=100, editable=True, blank=False, null=True)
    blog_content = models.TextField(max_length=10000, blank=False, editable=True, null=True)
    files = models.FileField(blank=True, null=True, upload_to=True)
    date = models.DateTimeField(blank=False, null=True, auto_now=True, editable=False)
    likes = models.IntegerField(blank=True, null=True, editable=False)

urls.py

    from django.urls import path
from . import views

app_name = "blog_app"

urlpatterns = [
    path('create/', views.create_blog_post.as_view(), name='create'),
    path('view/(?P<pk>\d )/', views.view_blog_post.as_view(), name='view'),
    path('all_posts/', views.all_blog_posts.as_view(), name='all'),
    path('delete/<slug:slug>', views.delet_blog_post.as_view(), name='delete')
]

CodePudding user response:

path is for converters like slug, str, int, to work with regex you need re_path

you can just redefine it as "view/<int:pk>/"

CodePudding user response:

    {% extends "base.html" %}
    {% block content %}
    <div >
    <h1>Blog Posts</h1>
    </div>
    <div >
    {% for blog_post in object_list %}
    <table >
    <ul >
        <li><a  href="{% url 'blog_app:view' pk=blog_post.pk %}">{{ blog_post.post_title }}</a></li>
    </ul>
    </table>
    {% endfor %}
    </div>
    {% endblock %}

i think the problem is in this line

 <li><a  href="{% url 'blog_app:view' pk=blog_post.pk %}">

when you send data in url tag you don't assign it to prametars , the right line will be this :

     <li><a  href="{% url 'blog_app:view' blog_post.pk %}">
  • Related