'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.

How can I modify it?

Tks.

Error Message :

IntegrityError at /addshowmemo/72/ (1048, "Column 'software_id' cannot be null")

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']

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


Solution 1:[1]

The problem here is that you have foreign key to software which cannot be 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.

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. 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1