Django Basic - Part 2

2 minute read

Model

Django can have ORM (Object Relational DB) and sql.

models.py

dir - homepage/models.py:

class Coffee(models.Model):
    """
    types are
    string: CharField
    number: IntergerField, SmallIntegerField, ...
    logic: BooleanField
    time/date: DateTimeField
    ...
    """
    name = models.CharField(default="",max_length=30) # null=False(default): must have value
    price = models.IntegerField(default=0)
    is_ice = models.BooleanField(default=False)

admin.py

If register admin in django app, we can manage db in admin page.

admin.py:

from django.contrib import admin
from .models import Coffee
# Register your models here.
admin.site.register(Coffee)

result:

Groups, Users are also models as default when creating superuser

Migration

To let django know model infomation:
makemigration(notice to django about changes of models) -> migrate(save changes)

makemigrations == git add  
migrate == git commit  
  1. makemigrations
     $ python manage.py makemigrations homepage
    

    result:

  2. migrate
     $ python manage.py migrate
    

    result:

    result of page:

Display class’s attribute

added two objects in coffee:
result:

Display class object as its attribute(name):

##### models.py #####

class Coffee(models.Model):

    def __str__(self):
        return self.name

    name = models.CharField(default="",max_length=30) # null=False(default): must have value
    price = models.IntegerField(default=0)
    is_ice = models.BooleanField(default=False)

result:

coffe page view

  1. Add coffee_view to views.py

    homepage/views.py:

     from django.shortcuts import HttpResponse, render
     from .models import Coffee # import Coffee class
    
     ...
    
     def coffee_view(request):
         coffee_all = Coffee.objects.all() # all, get, filter, ...
         return render(request, 'coffee.html', {"coffee_list":coffee_all})
    
    
  2. Make Coffe Template

    homepage/template/coffee.html:

     <!DOCTYPE html>
     <html>
         <head>
             <title>Coffee List</title>
                
         </head>
    
         <body>
             <h1>My Coffee List</h1>
             <p>{{coffee_list}}</p>
         </body>
     </html>
    
  3. Add urls.py in webproj/urls.py

     from django.contrib import admin
     from django.urls import path
     from homepage.views import index, coffee_view
    
     urlpatterns = [
         path('', index), # localhost/
         path('admin/', admin.site.urls), # localhost/admin
         path('coffee/', coffee_view), # localhost/coffee
     ]
    
    

    result:

  4. Display as Objects’ attributes.

     <!DOCTYPE html>
     <html>
         <head>
             <title>Coffee List</title>
                
         </head>
    
         <body>
             <h1>My Coffee List</h1>
             {% for coffee in coffee_list %}
                 <p>{{coffee.name}}, {{coffee.price}}</p>
             {% endfor %}
         </body>
     </html>
    

    result:

Summary

Process

  1. Make a model (ORM) in homepage/models.py
  2. Register Admin User of the model in homepage/admin.py
  3. Do Migration (makemigrations(git add), migrate(git commit))
  4. Make a template in template/your.html
  5. Make a view in homepage/views.py (input: template-html, data-models class)
  6. Add a url in /urls.py

Form

homepage/forms.py:

Make forms.py

from django import forms
from .models import Coffee

# forms.ModelForm
class CoffeeForm(forms.ModelForm): # ModelForm을 μƒμ†λ°›λŠ” CoffeForm 생성
    class Meta:
        model = Coffee # model
        fields = ('name', 'price', 'is_ice') # name, price, is_ice

Add to views.py

from django.shortcuts import HttpResponse, render
from .models import Coffee
from .forms import CoffeeForm
...
def coffee_view(request):
    coffee_all = Coffee.objects.all() # all, get, filter, ...
    form = CoffeeForm()
    return render(request, 'coffee.html', {"coffee_list":coffee_all, "coffee_form":form})

Modify Template

Without Submit(save) Button

coffee.html:

    <body>
        <h1>My Coffee List</h1>
        {% for coffee in coffee_list %}
            <p>{{coffee.name}}, {{coffee.price}}</p>
        {% endfor%}
        <form action="">
            {{ coffee_form.as_p}} <!-- as_p: as paragraph -->
        </form>
    </body>

result:

Add Save Button

    <body>
        <h1>My Coffee List</h1>
        {% for coffee in coffee_list %}
            <p>{{coffee.name}}, {{coffee.price}}</p>
        {% endfor%}

        <form action="" method="POST">
            {{ coffee_form.as_p}} <!-- as_p: as paragraph -->
            <button type="submit">Save</button>
        </form>
    </body>

result:

Form needs Verification

After push save button:

To solve this,
Add CSRF Token:

    <body>
        <h1>My Coffee List</h1>
        {% for coffee in coffee_list %}
            <p>{{coffee.name}}, {{coffee.price}}</p>
        {% endfor%}

        <form action="" method="POST">{% csrf_token %}
            {{ coffee_form.as_p}} <!-- as_p: as paragraph -->
            <button type="submit">Save</button>
        </form>
    </body>

To get information from the page as β€œSave” Button,
Modify views.py.

def coffee_view(request):
    coffee_all = Coffee.objects.all() # all, get, filter, ...
    # if request is POST
        # Complete Form by POST
        # If valid, save it.
    if request.method=="POST":
        form  = CoffeeForm(request.POST)
        if form.is_valid(): #
            form.save()
    
    form = CoffeeForm()
    return render(request, 'coffee.html', {"coffee_list":coffee_all, "coffee_form":form})

result:

Leave a comment