1.环境搭建
(1).安装Python,pycharm,自己百度
(2)安装django
sudo pip3 isntall Django
2.实例1
进入你想建站的目录运行
django-admin startproject mysite
python manage.py runserver ip:port//网站开始运行
python manage.py startapp polls//创建一个网站的应用
//开始编写视图
//进入polls文件件,打开views.py
//views.py文件内容如下
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
//现在在polls/urls.py加入路径(urls.py为自己新建的文件),文件内容如下:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
//把polls的路径加入mysite,修改mysite/urls.py文件如下:
mysite/urls.py¶
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
//访问试试
结果如下图:
3.实例2
这部分将会连接到数据库
mysite/settings.py 保存你的网站的设置
INSTALLED_APPS 默认包括了以下 Django 的自带应用:
django.contrib.admin – 管理员站点, 你很快就会使用它。
django.contrib.auth – 认证授权系统。
django.contrib.contenttypes – 内容类型框架。
django.contrib.sessions – 会话框架。
django.contrib.messages – 消息框架。
django.contrib.staticfiles – 管理静态文件的框架。
python manage.py migrate//启动 INSTALLED_APPS 包含的应用
//编辑polls/models.py文件,如下:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
//在settings.py文件里面添加默认应用
'polls.apps.PollsConfig',
//运行
python manage.py makemigrations
python manage.py migrate
python manage.py sqlmigrate polls 0001
python manage.py inspectdb > Event/models.py //数据库反向生成
//现在创建管理员帐号
python manage.py createsuperuser
//在polls/admin.py¶文件里面添加model的管理
from django.contrib import admin
from .models import Question
admin.site.register(Question)
4.实例3
创建更多的视图
//修改polls/views.py文件如下
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
//修改polls/urls.py文件如下
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
//现在可以去管理界面添加数据
//....
//管理界面的更改polls/admin.py
from django.contrib import admin
from .models import Question,Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
("Question", {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
list_display = ('question_text', 'pub_date')
inlines = [ChoiceInline]
list_filter = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
//现在数据已经录入继续编辑视图
//在polls/templates/polls/index.html的文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
//detail.html文件如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>detail</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>
</body>
</html>
//results.html文件如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>results</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'detail' question.id %}">Vote again?</a>
</body>
</html>
//views.py文件如下
from django.shortcuts import render,get_object_or_404
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('results', args=(question.id,)))
整体文件的结构图: