[Django] CRUD(Create/Retrieve/Update/Delete)

Create – create or add new entries in a table in the database. 
Retrieve – read, retrieve, search, or view existing entries as a list(List View) or retrieve a particular entry in detail (Detail View) 
Update – update or edit existing entries in a table in the database 
Delete – delete, deactivate, or remove existing entries in a table in the database

  

We're going to learn how to work with a database outside of using the django admin panel.


create room_form.html  inside  main/templates/main

{% extends 'main.html' %}

{% block content %}

<div>
    <form method="POST" action="" >
        {% csrf_token %}
            {{form.as_p}}
            <input type="Submit" value="Submit" />
    </form>
</div>

{% endblock content %}

POST; for creating and updating , if I don't specify the action, it's going to send it to the current url that we're at. csrf_token this token will be sent on every form submit so when we're sending post requests in django we need to pass in this token; we're just sending that token along with every request and it's making sure that the user didn't try to do anything malicious with that.


and go to views.py

def createRoom(request):
    form = RoomForm()
    if request.method == 'POST':
        form = RoomForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')

    context = {'form': form}
    return render(request, 'main/room_form.html', context)

and url.py

urlpatterns = [
path('', views.home, name="home"),
path('room/<str:pk>/', views.room, name="room"),

path('create-room/', views.createRoom, name="create-room"),

Le'ts go into our home.tml page and this is where a user can create a room from. 


    <a href="{% url 'create-room' %}">Create Room</a>


Now you see "submit" on the page. 


we're going to make new file.. 

main/forms.py

from django.forms import ModelForm
from .models import Room

class RoomForm(ModelForm):
    class Meta:
        model = Room
        fields = '__all__'

fields = '__all__' is going to create the form based on the metadata of the room




Popular posts from this blog

[Python] Dictionary

[Visual Design 2/3]

[JavaScript] For loop , Function