python - 数据库在 django 中多次存储数据

标签 python django

我正在制作一个小网站,通过它的书来学习 django

所以我制作了一个名为 Writer 的数据库模型

class Writer(models.Model):
  name = models.CharField(max_length=20);

我做了一个 View ( Controller )来注册作家

def addwriter(request,name):
  nimos = Writer(name=name);
  nimos.save();
  return render_to_response("addJournalist.html",{"name":nimos.name});

及其网址:

(r'^new/(.+)/',addwriter)

note: i know it should be done using post form but i made it that way because the book didn't reach forms yet.

when i access the writers in a web page: view

def mainjournal(request):
   writers = Writer.objects.all();
   return render_to_response("journalMain.html",{"writers":writers});

模板部分 {% block 内容 %}

  {% for writer in writers %}

    <p>{{ writer.name }} and his id is {{ writer.id }}</p>


 {% empty %}

      good luck finding writers man


 {% endfor %}



 {% endblock %}

它为我在另一个 View 中添加的每个名称提供了三个名称:

示例(在网页中添加乔治):

乔治和他的 ID 是 22

乔治和他的 ID 是 23

George/img,他的 id 是 24

我不知道为什么所以我问你为什么

最佳答案

向您的 addwriter View 添加一些日志。就像这样

logger = logging.getLogger(__name__)

def addwriter(request,name):
  logger.debug("the coming request is: {}, and the name is: {}".format(request, name))
  nimos = Writer(name=name);
  nimos.save();
  return render_to_response("addJournalist.html",{"name":nimos.name})

我想你就像@Rohan所说的那样,你向这个 View 发送了3个请求。您的 python 代码工作正常。

这是我的幼稚测试代码

from django.test import TestCase
from .models import Writer


class WriterTestCase(TestCase):

    def test_writer_name_function(self):
        for i in range(3):
            self.client.get("/new/George/")
        writer_set = Writer.objects.all()
        self.assertEqual(writer_set.count(), 3)

PS:在添加记录器代码之前,请确保您已经在 django 中设置了日志记录

关于python - 数据库在 django 中多次存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25579911/

相关文章:

python - 将其中一个索引作为元组的 MultiIndex

python - 在 Python twisted 中创建受控的 TLS 对话并将其存储以用作测试数据

python - 在 Python 中从选定的列表元素中查找最大的数字

python - 在django模板中相乘

python - Django 模型不工作 : module 'django.contrib.admin' has no attribute 'Modeladmin'

python - Python 中带有包装 C 函数的多线程

python - 如何使用 Django 模型查询获取缺失数据?

python - 如何在 Django 模型查询中从 mysql 数据库中获取日期时间作为字符串

python - Django channel 不发送回复消息

python - 在 Python 中,如何在 except block 中放入调试器并访问异常实例?