【问题标题】:Django URL Path from DB file value来自 DB 文件值的 Django URL 路径
【发布时间】:2021-12-06 00:01:03
【问题描述】:

我正在尝试创建“项目”页面,这些页面的路径使用 {{ project.title }} 值,而不是我使用的当前方法。我不太明白我怎么能做到这一点,但感觉我很接近?

Models.py

from django.db import models

# Create your models here.
class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    technology = models.CharField(max_length=20)
    image = models.FilePathField(path='projects/static/img/')
    live = models.URLField()
    source = models.URLField()

    def __str__(self):
        return self.title

Urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("", views.project_index, name="projects"),
    path("<int:pk>/", views.project_details, name="project_details"),  # PK for Primary Key
]

Views.py

from django.shortcuts import render
from .models import Project

# Create your views here.
def project_index(request):
    projects = Project.objects.all()
    context = {'projects': projects}
    return render(request, 'projects/project_index.html', context)

def project_details(request, pk):
    project = Project.objects.get(pk=pk)
    context = {'project': project}
    return render(request, 'projects/project_details.html', context)

我认为path("&lt;int:pk&gt;/", 需要成为一个蛞蝓,但我就是不知道如何绑定数据库数据。 可能是context = {'project': project}

目前的网址是http://127.0.0.1:8000/projects/1/ - 我正在寻找http://127.0.0.1:8000/projects/EXAMPLE/

谢谢

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    urls.py

        path("<title>/", views.project_details, name="project_details"),
    

    views.py

    
    def project_details(request, title: str):
        project = Project.objects.filter(title=title).first()
        if project is None:
            titles = list(Project.objects.all().values_list('title', flat=True))
            msg = f'Project(title=title) not found. Exist titles are: {titles}'
            raise Exception(msg)
        ...
    

    【讨论】:

    • 您好,尝试此操作时出现以下错误? imgur.com/a/OlzJmba
    • 网站打不开。请将错误添加到您的问题中。
    • 链接对我来说仍然可以正常工作吗?它声明no Project matches the given query
    【解决方案2】:

    您必须将SlugField 添加到您的models.py 文件中:

    Models.py

    from django.db import models
    from django.utils.text import slugify
    
    # Create your models here.
    class Project(models.Model):
        title = models.CharField(max_length=100)
        description = models.TextField()
        technology = models.CharField(max_length=20)
        image = models.FilePathField(path='projects/static/img/')
        live = models.URLField()
        source = models.URLField()
        slug = models.SlugField(default="", blank=True, null=False, db_index=True)
    
        def __str__(self):
            return self.title
    
        def save(self, *args, **kwargs):
            self.slug = slugify(self.title)
            super().save(*args, **kwargs)
    
    

    Views.py

    from django.shortcuts import render
    from .models import Project
    
    # Create your views here.
    def project_index(request):
        projects = Project.objects.all()
        context = {'projects': projects}
        return render(request, 'projects/project_index.html', context)
    
    def project_details(request, slug):
        project = Project.objects.get(slug=slug)
        context = {'project': project}
        return render(request, 'projects/project_details.html', context)
    
    

    Urls.py

    
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path("", views.project_index, name="projects"),
        path("<slug:slug>/", views.project_details, name="project_details"),
    ]
    

    确保运行makemigrations,然后运行migrate

    【讨论】:

    • 我喜欢这个解决方案,但是当我尝试它时出现以下错误? imgur.com/a/kuyASZe
    • 确保运行 makemigrationsmigrate
    • 它现在返回:imgur.com/a/jjTnlJi 并且控制台以 Not Found 响应:/projects/example/
    • 尝试在 slug url 后添加一个“/”:path("&lt;slug:slug&gt;/", views.project_details, name="project_details"), ]
    • 解决了上述问题,但提出了一个新问题。我必须注意,在数据库中它被称为带有大写字母的示例,但是在 URL 中尝试两者都会返回相同的错误,如果这很重要的话。 imgur.com/a/JluZLUS
    猜你喜欢
    • 1970-01-01
    • 2011-07-25
    • 2013-09-01
    • 2011-09-17
    • 2011-01-30
    • 2012-08-14
    • 2018-07-29
    • 2012-02-03
    • 2017-09-05
    相关资源
    最近更新 更多