Django学习笔记之二
一、使用Django自带的后端管理平台
1、后台创建管理员
python manage.py createsuperuser
Email address: admin@example.com
Password: ********** Password (again): ********* Superuser created successfully.
2、打开后台页面
输入刚才的用户名及密码登陆:
此时还看不到我们刚才创建的数据表
那我们打开polls/admin.py文件,把我们所创建的数据表配置进去后台,可以通过修改models.py / admin.py代码来设置多种显示格式,其中一种如下:
from django.contrib import admin
from polls.models import Choice, Question
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)

二、自定义模板
先在polls文件夹下方创建一个名叫templates的目录,再修改如下配置文件,把目录添加到系统路径
mysite/settings.py
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
各种template如下:
templates/polls/index.html
{% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
templates/polls/detail.html
<h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls: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>
templates/polls/results.html
<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 'polls:detail' question.id %}">Vote again?</a>
三、创建视图
polls/views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | from django.shortcuts import render,get_object_or_404 from django.http import HttpResponseRedirect,HttpResponse from django.core.urlresolvers import reverse from django.views import generic from django.utils import timezone from polls.models import Choice, Question # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset( self ): """Return the last five published question""" return Question.objects. filter ( pub_date__lte = timezone.now() ).order_by( '-pub_date' )[: 5 ] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset( self ): return Question.objects. filter (pub_date__lte = timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): p = get_object_or_404(Question,pk = question_id) try : selected_choice = p.choice_set.get(pk = request.POST[ 'choice' ]) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html' ,{ 'question' :p, 'error_message' : "You didn't select a choice" , }) else : selected_choice.votes + = 1 selected_choice.save() return HttpResponseRedirect(reverse( 'polls:results' ,args = (p. id ,))) |
mysite/urls.py 总的url配置
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^polls/', include('polls.urls',namespace="polls")), url(r'^admin/', include(admin.site.urls)), )
polls/urls.py 子url配置
from django.conf.urls import patterns,url from polls import views urlpatterns=patterns('', url(r'^$',views.IndexView.as_view(),name='index'), url(r'^(?P<pk>\d+)/$',views.DetailView.as_view(),name='detail'), url(r'^(?P<pk>\d+)/results/$',views.ResultsView.as_view(),name='results'), url(r'^(?P<question_id>\d+)/vote/$',views.vote,name='vote'), )
四、最终Models如下:
polls/models.py
import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now >= self.pub_date >= now - datetime.timedelta(days=1) was_published_recently.admin_order_field='pub_date' was_published_recently.bollean = True was_published_recently.short_description='Published recently?' class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
五、自定义样式/静态文件位置配置,在polls文件夹下面创建static文件夹
静态文件如:polls/static/polls/style.css
mysite/settings.py 文件中应有下面的默认配置,如果没有,手动添加
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' #STATIC_URL = [os.path.join(BASE_DIR,'static')]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?