简体   繁体   English

Django如何添加数据?

[英]How to add data in Django?

This is the Memo text where User can submit their Memo form.这是用户可以提交其备忘录表单的备忘录文本 I need to add(update) new message this record via Update button in DJANGO. by the way I used PK and FK db table.我需要通过 DJANGO 中的更新按钮添加(更新)这条记录的新消息。顺便说一句,我使用了 PK 和 FK 数据库表。

How can I modify it?我该如何修改它?

Tks.谢谢。

Error Message:错误信息:

IntegrityError at /addshowmemo/72/ (1048, "Column 'software_id' cannot be null") /addshowmemo/72/ 处的 IntegrityError(1048,“列‘software_id’不能为空”)

Request Method: POST Request URL:/127.0.0.1/addshowmemo/72/ Django Version: 3.1.5 Exception Type: IntegrityError Exception Value: (1048, "Column 'software_id' cannot be null") Exception Location: d:\project\python\it\venv\lib\site-packages\django\db\backends\mysql\base.py, line 78, in execute Python Executable: d:\project\python\it\venv\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\project\python\it', 'c:\Users\tou52\.vscode\extensions\ms-python.python-2022.4.1\pythonFiles\lib\python\debugpy\_vendored\pydevd', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310', 'd:\project\python\it\venv', 'd:\project\python\it\venv\lib\site-packages']请求方式:POST 请求 URL:/127.0.0.1/addshowmemo/72/ Django 版本:3.1.5 异常类型:IntegrityError 异常值:(1048, "Column 'software_id' cannot be null") 异常位置:d:\project\ python\it\venv\lib\site-packages\django\db\backends\mysql\base.py, line 78, in execute Python Executable: d:\project\python\it\venv\Scripts\python.exe Python 版本: 3.10.2 Python 路径: ['D:\project\python\it', 'c:\Users\tou52\.vscode\extensions\ms-python.python-2022.4.1\pythonFiles\lib\python\debugpy\ _vendored\pydevd', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\DLLs', ' C:\Users\tou52\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310', 'd:\project\python\it\venv ', 'd:\project\python\it\venv\lib\site-packages']

Models:楷模:

class Memo(models.Model):
notes = models.TextField()
software = models.ForeignKey(Software, on_delete=models.CASCADE)
timestamp = models.DateTimeField(default=timezone.now)

def __str__(self):
    return self.notes

class Software(models.Model):
STATUS_CHOICES = [
    (0, 'Planning'),
    (1, 'Development'),
    (2, 'Using'),
    (3, 'Obsolete')
]
name = models.CharField(max_length=100, verbose_name="SysName")
url = models.CharField(max_length=100, verbose_name="SysAdd")
status = models.PositiveIntegerField(default=0, choices=STATUS_CHOICES,  verbose_name="Status") 
company = models.ForeignKey(Company, on_delete=models.CASCADE,  verbose_name="Company")
team = models.ForeignKey(Team, on_delete=models.DO_NOTHING,  verbose_name="Team")
def __str__(self):
    return self.name

Templates:模板:

<form method="POST" name="myform" action="." >
{% csrf_token %}
<table class="table table-striped">
  <tr>
     <td align=right>Memo:</td>
      <td>
            <input type=text size=50 name="Cmemo" value='{{Nmemo.notes}}'>
    </td>
  </tr>
<tr>
    <td> </td>
<td>
    <input type=submit value="Confirm" class="btn btn-primary">||<a href='/showall/' class="btn btn-warning">Home</a>
</td>
<td></td>
</tr>

views:观点:

def add_showmemo(request,id=None,logmemo=None):
memos = Memo.objects.all()
if request.method=="POST":
    Cmemo = request.POST.get('Cmemo')
    Nmemo = Memo(notes=Cmemo)
    Nmemo.save()     
    return redirect("/showdetail/")
return render(request, "add_showmemo.html", locals())

db database:数据库:

Memo db备忘录数据库

id/notes/timestamp/software_id
 1/xxx/2022-01-02/32
 2/ooo/2022-01-03/31
 3/yyy/2022-01-04/40
 4/vvv/2022-01-05/1
 5/sss/2022-01-06/2

SoftWare db软件数据库

id/name/url/company_id/status/team_id
 1/watch/NA/9/1/8
 2/shoes/NA/10/2/8
 3/pen/NA/10/7/2/8
 4/apple/NA/7/2/9
 5/phone/NA/4/0/6

The problem here is that you have foreign key to software which cannot be null这里的问题是你有software的外键不能是 null

software = models.ForeignKey(Software, on_delete=models.CASCADE)

therefore when you save memo without software attached - it hits database constraint of non-null field.因此,当您在没有附加software的情况下保存备忘录时 - 它会遇到非空字段的数据库约束。

Thus, you have two options:因此,您有两个选择:

  1. If software is not mandatory to be on memo - make it nullable:如果软件不是必须在备忘录上的 - 让它可以为空:

     software = models.ForeignKey(Software, on_delete=models.SET_NULL, null=True, blank=True)
  2. Or if it indeed must be there - find the relevant software and attach it to memo in views.py .或者,如果它确实必须存在 - 找到相关软件并将其附加到views.py中的备忘录。 For example:例如:

     Cmemo = request.POST.get('Cmemo') software = Software.objects.get(id=request.POST.get('software_id')) Nmemo = Memo(notes=Cmemo, software=software) Nmemo.save()

You also might want to explore Django forms - there it will be more simple and "automatic" without need to extract fields one-by-one.您可能还想探索 Django forms - 它将更加简单和“自动”,无需逐一提取字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM