Model trong django - Model in django
Vào polls vào models.pyfrom django.db import models
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=500)
time_pub = models.DateTimeField()
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
vote = models.IntegerField(default=0)
Vào thư mục theo đường dẫn chạy lệnh:
C:\Users\Admin\PycharmProjects\pythonProject\mySite> python manage.py makemigrations
Vào thư mục theo đường dẫn chạy lệnh:
C:\Users\Admin\PycharmProjects\pythonProject\mySite> python manage.py migrate
Chạy tiếp lệnh :
PS C:\Users\Admin\PycharmProjects\pythonProject\mySite> python manage.py shell
Chạy lệnh :
- from polls.models import Question
Tạo Biến thời gian:
- from django.utils import timezone
- timezone.now()
- t = timezone.now() : biến t bằng giá trị ngày tháng
Tạo Question:
- Chạy lệnh : q = Question(question_text="Bạn thích màu gì?",time_pub=t)
Chạy lênh : q.save() để lưu dữ liệu vào database.
Kiểm tra database bằng lệnh sau:
>>> q.id
Kết quả: 1
>>> q.question_text
Kết quả: 'Bạn thích màu gì?'
Tạo câu trả lời :
>>> from polls.models import Choice
>>> c = Choice(question=q, choice_text="do",vote=0)
>>> c.save()
>>> d = Choice(question=q, choice_text="xanh",vote=0)
>>> d.save()
>>> Choice.objects.all()
<QuerySet [<Choice: Choice object (1)>, <Choice: Choice object (2)>]>
Admin site trong Python Django
PS C:\Users\Admin\PycharmProjects\pythonProject\mySite> python manage.py createsuperuser
Username (leave blank to use 'admin'): hunglsctk42@gmail.com
Email address: hunglsctk42@gmail.com
Password:
Password (again):
Superuser created successfully.
Chú ý ( password nhập vào sẽ không hiển thị)
Sau khi login ta sẽ có giao diện như sau:Vào polls admin.py nhập mã sau:
from django.contrib import admin
from .models import Choice, Question
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
kết quả :
Templates trong Django python
vào polls Tạo 1 Directory tên templates trong tempalates Tạo 1 Directory tên polls
Tạo file index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Đây là templade</h1>
</body>
</html>
Vào polls vào views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, "polls/index.html")
# Create your views here.
kết quả:
Vào mySite vào urls.py :from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
Vào polls vào views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
myname="Lê Hùng"
taiSan = ["Điện thoại","máy tính","ô tô"]
context = {"name":myname,"taisan": taiSan}
return render(request, "polls/index.html",context)
# Create your views here.
Vào polls vào index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Đây là templade</h1>
<p> Chào các bạn mình là {{ name}}</p>
<h2>Tài sản tôi gồm:</h2>
<ul>
{% for item in taisan %}
<li>{{item}}</li>
{% endfor%}
</ul>
</body>
</html>
kết quả:
Vào polls vào index.html:
{% extends 'polls/base.html'%}
{% block content1 %}
<h1>Đây là templade</h1>
<p> Chào các bạn mình là {{ name}}</p>
<h2>Tài sản tôi gồm:</h2>
<ul>
{% for item in taisan %}
{% if item != 'máy tính' %}
<li>{{item}}</li>
{% endif%}
{% endfor%}
</ul>
{%endblock%}Vào polls Tạo file base.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.header{
padding: 30px;
background-color: #ccc;
color: #fff;
}
</style>
</head>
<body>
<div class="header">
<h1>My website</h1>
</div>
<div class="menu">
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>link4</li>
</ul>
</div>
<div class="content">
{% block content1%}
{%endblock%}
</div>
</body>
</html>
Vào polls vào views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
myname="Lê Hùng"
taiSan = ["Điện thoại","máy tính","ô tô"]
context = {"name":myname,"taisan": taiSan}
return render(request, "polls/index.html",context)
# Create your views here.
kết quả:
Vào polls Tạo file base.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.header{
padding: 30px;
background-color: #ccc;
color: #fff;
}
</style>
</head>
<body>
<div class="header">
<h1>My website</h1>
</div>
<div class="menu">
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>link4</li>
</ul>
</div>
<div class="content">
{% block content1%}
{%endblock%}
{% block question_list %}
{%endblock%}
</div>
</body>
</html>
Vào polls vào views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Question
def index(request):
myname="Lê Hùng"
taiSan = ["Điện thoại", "máy tính", "ô tô"]
context = {"name": myname, "taisan": taiSan}
return render(request, "polls/index.html", context)
def viewlist(request):
list_question = Question.objects.all()
# list_question = get_object_or_404(Question, pk=1)
context1 = {"dsquest": list_question}
return render(request, "polls/question_list.html", context1)
# Create your views here.
Vào polls vào urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('list/', views.viewlist, name='views_list'),
]
Vào polls tạo question_list.py
{% extends 'polls/base.html'%}
{% block question_list %}
{% if dsquest %}
{% for item in dsquest %}
<p>
{{item.question_text}}
</p>
{% endfor %}
{% else %}
<h3 style="color: red;">Không có dữ liệu câu hỏi !!!</h3>
{% endif %}
{%endblock%}Kết quả:
Tiến hành chạy server :
Truy cập :
http://127.0.0.1:8000/admin/polls/question/
Thêm dữ liệu câu hỏi và câu trả lời.
Vào polls vào urls.py:from django.urls import path
from django.views.generic import TemplateView
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('list/', views.viewlist, name='views_list'),
path('detail/<int:question_id>', views.detailView, name='detail'),
]
Vào polls vào views.py:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Question
def index(request):
myname="Lê Hùng"
taiSan = ["Điện thoại", "máy tính", "ô tô"]
context = {"name": myname, "taisan": taiSan}
return render(request, "polls/index.html", context)
def viewlist(request):
list_question = Question.objects.all()
# list_question = get_object_or_404(Question, pk=1)
context1 = {"dsquest": list_question}
return render(request, "polls/question_list.html", context1)
def detailView(request, question_id):
q = Question.objects.get(pk=question_id)
return render(request, "polls/detail_question.html", {"qs": q})
Vào polls tạo file detail_question.html:
{% extends 'polls/base.html'%}
{% block question_list %}
{% if qs %}
<h3 style="margin-left: 50px">{{qs.question_text}}</h3>
<from>
<ul>
{% for item in qs.choice_set.all %}
<li style="list-style: none">
<input type="radio" value="{{item.id}}" name="choice">
{{item.choice_text}}
</li>
{% endfor %}
<p><input type="submit"></p>
</ul>
</from>
{% endif %}
{%endblock%}Vào polls Tạo file base.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.header{
padding: 30px;
background-color: #ccc;
color: #fff;
}
.menu{
background-color: #cccccc;
color: #fff;
}
.menu ul li{
float: left;
padding: 10px;
list-style: none;
}
.menu::after{
clear: both;
display: table;
content: "";
}
</style>
</head>
<body>
<div class="header">
<h1>My website</h1>
</div>
<div class="menu">
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>link4</li>
</ul>
</div>
<div class="content">
{% block content1%}
{%endblock%}
{% block question_list %}
{%endblock%}
</div>
</body>
</html>
Vào polls tạo question_list.py
{% extends 'polls/base.html'%}
{% block question_list %}
{% if dsquest %}
{% for item in dsquest.choice_set.all %}
<p>
{{item.question_text}}
</p>
{% endfor %}
{% else %}
<h3 style="color: red;">Không có dữ liệu câu hỏi !!!</h3>
{% endif %}
{%endblock%}Kết quả :
Xử lý hành động submit form với django
Vào polls Tạo file base.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.header{
padding: 30px;
background-color: #ccc;
color: #fff;
}
.menu{
background-color: #cccccc;
color: #fff;
}
.menu ul li{
float: left;
padding: 10px;
list-style: none;
}
.menu::after{
clear: both;
display: table;
content: "";
}
</style>
</head>
<body>
<div class="header">
<h1>My website</h1>
</div>
<div class="menu">
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>link4</li>
</ul>
</div>
<div class="content">
{% block content1%}
{%endblock%}
{% block question_list %}
{%endblock%}
{% block question_result %}
{%endblock%}
</div>
</body>
</html>
Vào polls vào urls.py:
from django.urls import path
from django.views.generic import TemplateView
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('list/', views.viewlist, name='views_list'),
path('detail/<int:question_id>', views.detailView, name='detail'),
path('<int:question_id>/', views.vote, name='vote'),
]
Vào polls vào views.py:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Question
def index(request):
myname="Lê Hùng"
taiSan = ["Điện thoại", "máy tính", "ô tô"]
context = {"name": myname, "taisan": taiSan}
return render(request, "polls/index.html", context)
def viewlist(request):
list_question = Question.objects.all()
# list_question = get_object_or_404(Question, pk=1)
context1 = {"dsquest": list_question}
return render(request, "polls/question_list.html", context1)
def detailView(request, question_id):
q = Question.objects.get(pk=question_id)
return render(request, "polls/detail_question.html", {"qs": q})
def vote(request, question_id):
q = Question.objects.get(pk=question_id)
try:
dulieu = request.POST["choice"]
c = q.choice_set.get(pk=dulieu)
except:
HttpResponse("Lỗi không có choice")
c.vote = int(c.vote) + 1
c.save()
return render(request, "polls/result.html", {"q": q})
Vào polls Vào file detail_question.html:
{% extends 'polls/base.html'%}
{% block question_list %}
{% if qs %}
<h3 style="margin-left: 50px">{{qs.question_text}}</h3>
<form action="{% url 'vote' qs.id %}" method="post">
{% csrf_token %}
<ul>
{% for item in qs.choice_set.all %}
<li style="list-style: none">
<input type="radio" value="{{item.id}}" name="choice">
{{item.choice_text}}
</li>
{% endfor %}
<p><input type="submit" value="gửi"></p>
</ul>
</form>
{% endif %}
{%endblock%}Vào polls tạo file result.html
{% extends 'polls/base.html'%}
{% block question_result %}
{% if q %}
<h3>{{ q.question_text }}</h3>
<p>kết quả bình chọn là:</p>
{% for item in q.choice_set.all %}
<p>{{ item.choice_text }} : <span style="color: #ff5833">{{ item.vote}}</span></p>
{% endfor %}
<a href="{% url 'views_list' %}">next</a>
{% endif %}
{%endblock%}Vào polls tạo question_list.py
{% extends 'polls/base.html'%}
{% block question_list %}
{% if dsquest %}
{% for item in dsquest %}
<a href="{% url 'detail' item.id %}">
<p>
{{item.question_text}}
</p>
</a>
{% endfor %}
{% else %}
<h3 style="color: red;">Không có dữ liệu câu hỏi !!!</h3>
{% endif %}
{%endblock%}Kết quả:

0 Nhận xét