# Professional-Internship-practice **Repository Path**: potatorunfast/professional-internship-practice ## Basic Information - **Project Name**: Professional-Internship-practice - **Description**: 专业实习课上训练 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-10 - **Last Updated**: 2026-03-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 本次项目参考Django教程,网址[Django教程](https://docs.djangoproject.com/en/6.0/intro/)以及CSDN博客写的Django(详细说明请看下面教程) ### 一、环境搭建(Win+Vsc+Anaconda) 1.下载Anaconda,选择Miniconda进行下载 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20124354.png) - 使用自带Anaconda Prompt命令(注意,每次使用都得从这开始) - 本次下载参考csdn[Django学习Part 1:环境搭建](https://blog.csdn.net/2301_81312828/article/details/158615575)---不在过多阐述 2. 每次运行diango前准备 - 切换路径,我得从C盘转到D盘 ``` cd /d D:\professional-internship-practice\DiangoProject\djangotutorial ``` - 激活diango环境 ``` conda activate django ``` ### 二、Writing your first Django app, part 1 1. 启动开发服务器 ``` python manage.py runserver ``` - 点击网址 [http://127.0.0.1:8000/](http://127.0.0.1:8000/) - 正确显示图 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20134216.png) 2. 创建投票应用(前提激活环境) ``` python manage.py startapp polls ``` - a.Write your first view(编写第一个视图) - 打开vsc,在文件 polls/views.py 并在其中放入以下 Python 代码: ``` from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") ``` - b.要为 polls 应用定义 URLconf,创建一个名为 polls/urls.py 的文件,加入代码 ``` from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] ``` - c.在 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), ] ``` - d.重新激活django环境,并进行运行 ``` python manage.py runserver ``` - 在浏览器访问[http://localhost:8000/polls/ ](http://localhost:8000/polls/ ) - 效果展示图 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20143133.png) ### 三、Writing your first Django app, part 2 1. 使用Vsc,打开mysite/settings.py并编辑 - 找到TIME_ZONE 这行,进行修改成如下代码 ``` TIME_ZONE = 'Asia/Shanghai' ``` - 创建一个数据库表 ``` python manage.py migrate ``` - 注意:若已有或者db.sqlite3损坏,建议删除,然后在执行代码 2. 创建模型 - a.连接数据库(前提准备工作)参考链接[Django学习Part 2](https://blog.csdn.net/2301_81312828/article/details/158621263/) - b.编辑 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) ``` 3. 激活模型 - a.编辑 mysite/settings.py 文件,并将该点分路径添加到 INSTALLED_APPS 设置中 ``` INSTALLED_APPS = [ "polls.apps.PollsConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] ``` - b.执行数据库迁移操作 ``` python manage.py makemigrations polls ``` - 只打印 SQL,不执行,对数据库无任何修改 ``` python manage.py sqlmigrate polls 0001 ``` - 现在再次运行 migrate 来在您的数据库中创建这些模型表 ``` python manage.py migrate ``` 4. Playing with the API(与 API 互动 ) - a.在模型中添加 __str__() 方法很重要,这不仅是为了在交互式提示符中处理时自己的方便,还因为对象的表示形式在整个 Django 自动生成的管理界面中都会被使用.通过编辑 Question 模型(在 polls/models.py 文件)并向 Question 和 Choice 添加一个 __str__() 方法. ``` import datetime from django.db import models from django.utils import timezone 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): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text ``` - b.进入交互式 Python 解释器,并使用 Django 提供的免费 API 进行一些操作 ``` python manage.py shell ``` - b.进入交互式 Shell,依次输入以下代码 ``` Question.objects.all() ``` ``` from django.utils import timezone ``` ``` q = Question(question_text="What's new?", pub_date=timezone.now()) ``` ``` q.save() ``` ``` q.id ``` ``` q.question_text ``` ``` q.pub_date ``` ``` q.question_text = "What's up? ``` ``` q.save() ``` ``` Question.objects.all() ``` - 注意想要知道详细注释,请登录网址[django part2教程](https://docs.djangoproject.com/en/6.0/intro/tutorial02/) - 看到效果图如下 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20185357.png) - 保存这些更改并启动一个新的 Python 交互式 shell ``` exit() ``` ``` python manage.py shell ``` ``` Question.objects.all() ``` ``` Question.objects.filter(id=1) ``` ``` Question.objects.filter(question_text__startswith="What") ``` ``` from django.utils import timezone ``` ``` current_year = timezone.now().year ``` ``` Question.objects.get(pub_date__year=current_year) ``` ``` Question.objects.get(id=2) ``` ``` Question.objects.get(pk=1) ``` ``` q = Question.objects.get(pk=1) ``` ``` q.was_published_recently() ``` ``` q = Question.objects.get(pk=1) ``` ``` q.choice_set.all() ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20190634.png) ``` q.choice_set.create(choice_text="Not much", votes=0) ``` ``` q.choice_set.create(choice_text="The sky", votes=0) ``` ``` q.choice_set.create(choice_text="Just hacking again", votes=0) ``` ``` c.question ``` ``` q.choice_set.all() ``` ``` q.choice_set.count() ``` ``` Choice.objects.filter(question__pub_date__year=current_year) ``` ``` c = q.choice_set.filter(choice_text__startswith="Just hacking") ``` ``` c.delete() ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20193136.png) ``` exit() ``` 5. 创建管理员用户 - 创建一个可以登录后台管理站点的用户 ``` python manage.py createsuperuser ``` 输入你想要的用户名,使用的电子邮件地址,输入您的密码 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20193645.png) 6. 启动开发服务器 ``` python manage.py runserver ``` 打开网址[http://127.0.0.1:8000/admin/](http://127.0.0.1:8000/admin/) ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20193848.png) - 输入自己账号和密码 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-10%20193941.png) 7. 让 poll 应用可在管理后台中修改 - 打开 polls/admin.py 文件,并编辑 ``` from django.contrib import admin from .models import Question admin.site.register(Question) ``` - 拓展--如何验证当前用户已创建 ``` python manage.py shell ``` ``` from django.contrib.auth import get_user_model User = get_user_model() user = User.objects.get(username='admin') # 将 'admin' 替换为你设置的用户名 print(user.is_active, user.is_staff, user.is_superuser) # 应全部为 True user.check_password('你的密码') # 返回 True 表示密码正确 ``` ### 四、Writing your first Django app, part 3(编写你的第一个 Django 应用,第 3 部分) 1. Writing more views(编写更多视图) - 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 (polls/urls.py) ``` from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path("", views.index, name="index"), # ex: /polls/5/ path("/", views.detail, name="detail"), # ex: /polls/5/results/ path("/results/", views.results, name="results"), # ex: /polls/5/vote/ path("/vote/", views.vote, name="vote"), ] ``` - 启动开发服务器 ``` python manage.py runserver ``` - 尝试在浏览网上输入网址例如[http://127.0.0.1:8000/polls/34/](http://127.0.0.1:8000/polls/34/) ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-11%20103331.png) - 类似的网址 - [http://127.0.0.1:8000/polls/34/results/](http://127.0.0.1:8000/polls/34/results/) - [http://127.0.0.1:8000/polls/34/vote/](http://127.0.0.1:8000/polls/34/vote/) 2. Write views that actually do something(编写实际能执行操作的视图) - 在poll/views.py进行更换代码 ``` from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by("-pub_date")[:5] output = ", ".join([q.question_text for q in latest_question_list]) return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged ``` - 创建一个视图可以使用的模板 - 在polls下创建temples文件夹,然后在temples文件夹下创建polls的文件夹 - 在polls下创建index.html,代码如下 ``` {% if latest_question_list %} {% else %}

No polls are available.

{% endif %} ``` - 注意:这里默认setting.py中TEMPLATES里有'APP_DIRS': True,这里基本配置好了,不需要手动操作 - 更新 index 中的 polls/views.py,页面完整代码 ``` from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by("-pub_date")[:5] template = loader.get_template("polls/index.html") context = {"latest_question_list": latest_question_list} return HttpResponse(template.render(context, request)) # Leave the rest of the views (detail, results, vote) unchanged 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) ``` - 启动服务器 ``` python manage.py runserver ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-11%20181227.png) ### 五、Writing your first Django app, part 4(编写你的第一个 Django 应用,第 4 部分) - 速通模式 1. 先编写一个最小化的表单 在polls/detail.html,完整页面如下 ```
{% csrf_token %}

{{ question.question_text }}

{% if error_message %}

{{ error_message }}

{% endif %} {% for choice in question.choice_set.all %}
{% endfor %}
``` 2. 创建results.html,路径在templates/polls/results.html,完整代码 ```

{{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • {% endfor %}
Vote again? ``` 3. 使用通用视图:代码越少越好 修改polls/views.py,完整代码如下 ``` from django.db.models import F from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = "polls/index.html" context_object_name = "latest_question_list" def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by("-pub_date")[:5] class DetailView(generic.DetailView): model = Question template_name = "polls/detail.html" class ResultsView(generic.DetailView): model = Question template_name = "polls/results.html" # ... 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 = F("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("polls:results", args=(question.id,))) ``` - 启动服务器,点击网址[http://127.0.0.1:8000/polls/1/](http://127.0.0.1:8000/polls/1/) - 最后效果展示 ![输入图片说明](Image/image%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20175706.png) ### 六、part5部分--自动化测试 1. 检测bug ``` python manage.py shell ``` ``` import datetime ``` ``` from django.utils import timezone ``` ``` future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) ``` ``` future_question.was_published_recently() ``` 结果图 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20201924.png) - 但由于未来的事情不是“最近的”,这显然是错误的。 2. 修复并创建一个测试用例以暴露该错误 修改polls/view.py,完成代码如下 ``` import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) ``` 修改polls/models.py ``` import datetime from django.db import models from django.utils import timezone 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 - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text ``` - 运行测试 ``` python manage.py test polls ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20202520.png) 3. 测试客户端 ``` python manage.py shell ``` ``` from django.test.utils import setup_test_environment ``` ``` setup_test_environment() ``` ``` from django.test import Client ``` ``` client = Client() ``` ``` response = client.get("/") ``` ``` response.status_code ``` ``` from django.urls import reverse ``` ``` response = client.get(reverse("polls:index")) ``` ``` response.status_code ``` ``` response.content ``` ``` response.context["latest_question_list"] ``` 结果图 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20203008.png) ### 七、part6,编写一个应用---设计背景图 1. 创建static文件夹,在里面在创建polls,images文件夹 - 在刚创建的polls下创建style.css,其代码如下 ``` li a { color: green; } ``` - 在 polls/templates/polls/index.html 的顶部添加以下内容 ``` {% load static %} ``` - 效果展示 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20203830.png) 2. 添加背景图片 - 自己找一张背景图片,放在images文件下 - 对style.css文件进行修改 ``` body { background: white url("images/background.png") no-repeat; } ``` 运行网址[http://127.0.0.1:8000/polls/](http://127.0.0.1:8000/polls/) - 存在问题,背景图不会铺满整个页面 - 解决方案,修改style.css代码 ``` body { background: white url("images/background.png") no-repeat center center fixed; background-size: contain; } ``` 效果展示图 ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20205003.png) ### 八、part7 1. 自定义管理表单 在polls/admin.py下重新排序编辑表单中的字段。 ``` from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fields = ["pub_date", "question_text"] admin.site.register(Question, QuestionAdmin) ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20210400.png) - 表单分成字段集 - 在polls/admin.py下 ``` from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {"fields": ["question_text"]}), ("Date information", {"fields": ["pub_date"]}), ] admin.site.register(Question, QuestionAdmin) ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20210434.png) 2. 添加相关对象 - 注册 Choice 到 admin 中 - 在polls/admin.py下添加 ``` from django.contrib import admin from .models import Choice, Question # ...已知存在代码省略 admin.site.register(Choice) ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20210633.png) 优化,在创建 Question 对象时直接添加一批 Choices 在polls/admin.py下移除 Choice 模型的 register() 调用。然后,编辑 Question 注册代码 ``` from django.contrib import admin from .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) ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20210807.png) 优化一下,显示所有用于输入相关 Choice 对象的字段需要占用很多屏幕空间。因此修改代码,让相关对象以更紧凑的表格格式显示 在polls/admin.py下 ``` class ChoiceInline(admin.TabularInline): ... ``` 将 StackedInline换成TabularInline ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20210934.png) 3. 自定义管理页面更改列表 使用 list_display 管理选项,它是一个字段名称列表,用于在对象变更列表页面上以列的形式显示 在polls/admin.py下 ``` class QuestionAdmin(admin.ModelAdmin): # ... list_display = ["question_text", "pub_date", "was_published_recently"] ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20211121.png) - 还可以使用 list_filter 过滤器。将以下行添加到 QuestionAdmin ``` list_filter = ["pub_date"] ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20212002.png) - 还可以添加一些搜索功能 ``` search_fields = ["question_text"] ``` 4. 自定义项目模板 - 在djangotutorial 目录下创建templates 目录,然后再templates 目录下创建admin文件夹 - 在 mysite/settings.py中里的 TEMPLATES 设置中添加一个 DIRS 选项 ``` "DIRS": [BASE_DIR / "templates"] ``` - 查找Django 源代码中默认的 Django admin 模板目录 ``` python -c "import django; print(django.__path__)" ``` - 找到路径,打开xxx/xxxx/django/contrib/admin/templates/ admin/base_site.html,将base_site.html复制到admin文件夹 - 编辑该文件并将 {{ site_header|default:_('Django administration') }} (包括花括号)替换为你自己的站点名称 - 例如代码如下 ``` {% extends "admin/base.html" %} {% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} ###以换成自己站点 {% if user.is_anonymous %} {% include "admin/color_theme_toggle.html" %} {% endif %} {% endblock %} ``` ![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-14%20220814.png) ### Part8 ---安装 Django Debug Toolbar - 安装工具 ``` python -m pip install django-debug-toolbar ``` - 完成Debug Toolbar 需要 4 个关键配置 - 在settings.py下把 debug_toolbar 加到 INSTALLED_APPS ``` INSTALLED_APPS = [ "debug_toolbar", "polls.apps.PollsConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] ``` - 添加 Debug Toolbar 中间件 ``` MIDDLEWARE = [ "debug_toolbar.middleware.DebugToolbarMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ``` - 最后面设置 INTERNAL_IPS ``` INTERNAL_IPS = [ "127.0.0.1", ] ``` - 修改 urls.py ``` from django.contrib import admin from django.urls import include, path import debug_toolbar urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), path("__debug__/", include(debug_toolbar.urls)), ] ``` 效果展示![输入图片说明](Image/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202026-03-15%20145718.png)