我有一个家庭项目,DRF部署在其中,数据库本身是postgresql,我学会了如何创建一个页面模板,但没有数据库的数据.我就是这么做的:

$ mkdir static
$ vim Project1/settings.py
$ cat Project1/settings.py
...
from pathlib import Path
import os
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'portfolio',
    'ckeditor', 
    'ckeditor_uploader',
]
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'Project2')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media/"
...
$ mv Project2/css static/
$ ls static/
css
$ vim Project2/index.html
$ cat Project2/index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <title>Project2</title>
</head>
<body>
    <!--SECTIONS-->
    <!--CARDS-->
    <section>
        <div class="container">
            <div class="cards">
                <div class="card__content" id="">
                    <h2 class="card_hidden" onclick="card__hidden(this)">Опыт работы</h2>
                    <div style="text-align: left;">
                        <ul>            
                            <li><strong>
                            ' . $row['begin'] . ' -
                            ' . $row['finish'] . ':</strong>
                            ' . $row['place'] . ';
                            ' . $row['specialization'] . '; <strong>Дополнительная информация:</strong>
                            ' . $row['content'] . '; <strong>Достижения:</strong>
                            ' . $row['progress'] . ';
                            </li>
                        </ul>
                    </div>
                </div>
            </div>  
        </div>
    </section> 
    <!-- JS -->
    <script src="{% static 'js/jquery.js' %}"></script>
    <script src="{% static 'js/main.js' %}"></script>
</body>
</html>
$ python manage.py runserver
$ google-chrome http://IP:8000/contents/

是的网站打开,但没有数据库中的数据.我开始以这种方式补充从数据库下载数据的代码:

$ vim portfolio/models.py
$ cat portfolio/models.py
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
class Place(models.Model):
    title = models.CharField(max_length=255, verbose_name="Место работы")
    spec = models.CharField(max_length=255, verbose_name="Должность")
    years = models.CharField(max_length=25, blank=True, null=True)
    description = models.TextField(verbose_name="Обязанности")
    progress = models.TextField(verbose_name="Достижения")
    doc=models.FileField(upload_to="uploads/%Y/%m/%d/", verbose_name="Файлы", blank=True, null=True)
    begin=models.DateField(blank=True, null=True, verbose_name="Начало работы")
    finish=models.DateField(blank=True, null=True, verbose_name="Конец работы")
    is_published=models.BooleanField(default=True, verbose_name="Публикация")
    cat=models.ForeignKey('Category', on_delete=models.PROTECT, null=True, verbose_name="Категории")
    ordinal = models.IntegerField()
    class Meta:
        ordering = ["-title"]
    def __str__(self):
        return self.title
class Portfolio(models.Model):
        title = models.TextField(verbose_name="Достижение")
        description = RichTextUploadingField(verbose_name="Статья")
        image = models.ImageField(upload_to='uploads/%Y/%m/%d/', blank=True, null=True)
        url = models.URLField(blank=True, null=True)
        ordinal = models.IntegerField()
        def __str__(self):
                return self.title
class Category(models.Model):
    name=models.CharField(max_length=100, db_index=True, verbose_name="Категория")
    ordinal = models.IntegerField()
$ python manage.py makemigrations
$ python manage.py migrate
$ vim portfolio/views.py
$ cat portfolio/views.py
...
from django.views.generic import ListView
...
class PortfolioListView(ListView):
    model = Portfolio
$ vim Project1/urls.py
$ cat Project1/urls.py
...
from portfolio.models import Portfolio
from portfolio.views import PortfolioListView
urlpatterns = [
    ...
    path('contents/', views.show_contents),
    path('portfolio2/', PortfolioListView.as_view()),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
$ vim Project2/content_list.html
$ cat david138it/content_list.html
{% extends "index.html" %}
{% block content %}
    <h2>Content</h2>
    <ul>
        {% for content in object_list %}
            <li>{{ content.title }}</li>
        {% endfor %}
    </ul>
{% endblock %}
$ google-chrome http://192.168.122.98:8000/portfolio2/
...
Internal Server Error: /portfolio2/
Traceback (most recent call last):
  File "/home/USER/pyenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/USER/pyenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response
    response = response.render()
  File "/home/USER/pyenv/lib/python3.10/site-packages/django/template/response.py", line 114, in render
    self.content = self.rendered_content
  File "/home/USER/pyenv/lib/python3.10/site-packages/django/template/response.py", line 90, in rendered_content
    template = self.resolve_template(self.template_name)
  File "/home/USER/pyenv/lib/python3.10/site-packages/django/template/response.py", line 72, in resolve_template
    return select_template(template, using=self.using)
  File "/home/USER/pyenv/lib/python3.10/site-packages/django/template/loader.py", line 47, in select_template
    raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: portfolio/portfolio_list.html
[06/Apr/2024 03:20:15] "GET /portfolio2/ HTTP/1.1" 500 83529

我遇到了一个问题时加载的投资组合2页.也就是说,他发誓从portfolio_list的哪一页,虽然我写在content_list. 我在第Built-in class-based generic views页上做的

我做错了什么?

推荐答案

您正在使用ListView 很抱歉,Django正在查找的模板不存在.

您有以下选项:

  1. 创建一个名为portfolio/portfolio_list.html的新模板,并使用它来显示Portfolio个对象的列表.

  2. 更改PortfolioListView中的template_name属性,以便它可以使用content_list.html模板.

portfolio/views.py文件中,将PortfolioListView更改为:

class PortfolioListView(ListView):
    model = Portfolio
    template_name = 'content_list.html'

假设:

content_list.html template位于正确的目录(在您的例子中是Project2/content_list.html),并且它扩展了正确的基模板(在您的例子中是index.html).

Python相关问答推荐

如何使用Google Gemini API为单个提示生成多个响应?

Pandas 第二小值有条件

如何访问所有文件,例如环境变量

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

如何使用数组的最小条目拆分数组

如何更改分组条形图中条形图的 colored颜色 ?

Python解析整数格式说明符的规则?

如何在Python中找到线性依赖mod 2

如何在图中标记平均点?

在单次扫描中创建列表

幂集,其中每个元素可以是正或负""""

Pandas:计算中间时间条目的总时间增量

替换现有列名中的字符,而不创建新列

Cython无法识别Numpy类型

Discord.py -

如何删除重复的文字翻拍?

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

Seaborn散点图使用多个不同的标记而不是点

利用广播使减法更有效率