Редактирование модели с помощью шаблонов в django

Перед обновлением формы update.html я получаю ошибку null constraint. Как мне обновить заметку в моем приложении? Когда я пытаюсь обновить модель заметки, я получаю эту ошибку:

Request URL:    http://127.0.0.1:8000/list
Django Version: 2.0.7
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: TakeNotes_note.title

В views.py

def see(request):
    if request.user.is_anonymous == False:
        # lIST OF THE NOTES
        notes = list(Note.objects.filter(user = str(request.user)))
        context = {"notes":notes}
        if request.method == 'POST':
            # GET THE NOTE REQUESTED
            note_req = request.POST.get("note_req")
            if request.POST.get("form_type") == note_req:
                # CHECK THE DETAILS OF THE NOTED
                for i in context['notes']:
                    if i.title == note_req:
                        deets = {'note': i}
                        return render(request,'read.html',deets)
            # Updating the note
            elif request.POST.get("form_type") == "EDIT":
                print("Editing", )
                for i in context['notes']:
                    if i.title == note_req:
                        deets = {"note":i}

                    if request.method == "POST": # Here is my problem
                        newTitle = request.POST.get("title")
                        newNote = request.POST.get("note")
                        print(newTitle, newNote)
                        i.title = newTitle
                        i.note = newNote
                        i.save()
                return render(request,"Update.html",deets)

                #missing Update

            # Deleting the note
            elif request.POST.get("form_type") == "DELETE":
                 for i in context['notes']:
                    if i.title == note_req:
                        i.delete()
                        return redirect("/")

        return render(request,'UserIndex.html',context)

    else:
        return redirect("/")

в Update.html

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Note || {{ websiteName }}</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="{% static 'style/addNote.css' %}">
</head>
<body>
    <header class='flex j-between a-center'>
        <div class="logo">
            <img src="{% static 'logo.svg' %}" alt="Logo" height="50px" class='logo'>
        </div>
        <form method="post" class="flex a-center j-between">      
            {% csrf_token %}  
            <div class="title">
                <input type="text" name="title" id="" value="{{note.title}}">
            </div>
            <div class="saveBtn">
                <button type="submit">
                    <i class='fas fa-save'></i>
                </button>
            </div>
        </header>
        <div class="textarea">
            <textarea name="note" id="" cols="30" rows="10">{{note.note}}</textarea>
        </div>
    </form>
</body>
</html>

в UserIndex.html

Следует использовать класс genereic django для улучшения вашего кода, вы можете увидеть в этом url https://ccbv.co.uk/ несколько примеров.

При ваших проблемах, если вы используете elif request.POST.get("form_type") == "EDIT": очевидно, что ваш метод - POST, вам нужно убрать это условие "if request.method == "POST":"

Вернуться на верх