Django Forms

There are a few typical operations that we should support for any model we develop if we are constructing a system. These are CRUD operations, which stand for create, read, update, and delete. These are the bare minimum operations that a system ought to be capable of. To far, we have developed the fetch method for the notes model by establishing an endpoint where users may obtain specific note information. We must take care of the other three processes as well in order to properly support the notes model. We will now discover how to put a create approach into practice. I have a project called "myforms" and, app called "notes". Here how my project works:

Continuous delivery with automated software testing.png

views.py

from django.shortcuts import render
from . models import Notes
from datetime import datetime
from django.views.generic import TemplateView, CreateView

class NotesCreateView(CreateView):
    model = Notes
    fields= ['title', 'text']
    template_name ='notes_form.html'
    success_url='notes'
    extra_context ={'today': datetime.today()}


class HomeView(TemplateView):
    template_name ='hello.html'
    extra_context ={'today': datetime.today()}

def detail(request, pk):
    try:
        note=Notes.objects.get(pk=pk)
    except Notes.DoesNotExist:
        raise Http404('Note does not exist.')    
    return render(request, 'notes_detail.html', {'note':note})

urls.py (inside the "notes")

from django.urls import path
from . import views

urlpatterns = [
    path('notes/notes', views.HomeView.as_view()),
    path('notes/<int:pk>', views.detail),
    path('notes/new', views.NotesCreateView.as_view(), name="notes.new"),
]

model.py

from django.db import models

class Notes(models.Model):
    title=models.CharField(max_length=200)
    text=models.TextField()
    created=models.DateTimeField(auto_now_add=True)

admin.py

from django.contrib import admin
from . import models
class NotesAdmin(admin.ModelAdmin):
    list_display = ('title', "text")

admin.site.register(models.Notes, NotesAdmin)

Open a templates folder and add these files.

hello.html

<html>
    <h1> Theese are the notes </h1>

</html>

notes_detail.html

<html>
    <h1>{{note.title}}</h1>
    <p>{{note.text}}</p>
</html>

notes_form.html

<html>
<form action="{% url 'notes.new' %}" method='POST'>{% csrf_token %}
    {{form}}
    <button>Submit</button>
</html>

So in browser: ( I know it became complicated) 127.0.0.1:8000/notes/notes/notes

notes.png

127.0.0.1:8000/notes/notes/1

notes 2.png

127.0.0.1:8000/notes/notes/new

note3.png

Notes are saved in the database. Also, when you submit it shuld go back to 127.0.0.1:8000/notes/notes/notes