【问题标题】:Unable to add data from admin panel to webpage in django无法将数据从管理面板添加到 django 中的网页
【发布时间】:2021-11-26 09:52:18
【问题描述】:

我试图在 django 中将数据从管理员动态添加到我的 HTML 页面,但是当我尝试在管理面板中添加数据时,它没有在 HTML 文件中显示任何内容。当我做makemigrations 时,我在下面得到这个

You are trying to add a non-nullable field 'link' to researchpaper without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:

在管理面板中我收到此错误

models.py

from django.db import models

class researchpaper(models.Model):
    title = models.CharField(max_length=300)
    publication = models.CharField(max_length=200)
    link = models.CharField(max_length=300)
    authors = models.CharField(max_length=200)
    year = models.DateField("date published")

views.py

def publications(request):
    data = researchpaper.objects.all()
    return render(request, 'lab/publications.html',context={
       "datas": data 
    })

urls.py

path('publications', views.publications, name='publications'),

HTML 文件


                {% for public in datas %}
                <tr>
                    <td>
                        <h5>2021</h5>
                        <p style="color: black;"><b>{{public.title}}</b></p>
                        <p style="font-size: 14px;"><i>{{public.publications}}</i></p>
                        <p style="font-size: 14px;"><i>{{public.author}}</i></p>
                    </td>
                    <td><a href="#"
                            target="blank" style="color: dodgerblue;"><i class="ai ai-google-scholar-square ai-2x"
                                style="padding-right: 10px;"></i></a></td>
                </tr>
                <tr>
                    <td>
                        <hr>
                    </td>
                </tr>
                {% endfor %}

为什么会出现这个问题,请帮忙

迁移快照

【问题讨论】:

  • 如果添加新字段,它必须允许 NULL 值或具有默认值。
  • 分享模型
  • 上面的模型代码我已经贴出来了

标签: python django django-models django-views django-urls


【解决方案1】:

选择第一个选项,它会再次出现,再次选择它并添加像“R”这样的虚拟数据,如果这不起作用,请尝试删除除__init__文件之外的所有迁移文件以及删除db.sqlite3文件如果你使用 SQLite。

【讨论】:

  • 我已经尝试过你提到的,但我又遇到了同样的错误?
  • 您是否删除了migration 文件中除__init__ 之外的所有文件并删除了db.sqlite3 ?还有make migrationmigrate 命令?请确保您已完成所有这些步骤,如果您有时间,请从迁移文件中添加快照。
  • 谢谢,它解决了操作错误,但是在管理面板中添加的数据没有反映在 HTML 页面中
  • 恭喜!你做得很好。根据没有出现在 HTML 中的数据,您可以在这里提出另一个问题,并在您的问题中添加 views.py 文件和 HTML 路径。
  • 谢谢。我在问题中添加了views.py 和 HTML 方面,请查看
猜你喜欢
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多