Django Basic - Part 2
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
- makemigrations
$ python manage.py makemigrations homepage
result:
- 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
-
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})
-
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>
-
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:
-
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
- Make a model (ORM) in homepage/models.py
- Register Admin User of the model in homepage/admin.py
- Do Migration (makemigrations(git add), migrate(git commit))
- Make a template in template/your.html
- Make a view in homepage/views.py (input: template-html, data-models class)
- 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