-
What is a Django project?
A) A collection of configuration and apps for a particular website
B) A single web application
C) A Python package with its own components
D) A web server configuration file
Answer: A) A collection of configuration and apps for a particular website
-
Which command is used to start a new Django project?
A) django-admin startapp
B) django-admin runserver
C) django-admin startproject
D) django-admin createsuperuser
Answer: C) django-admin startproject
-
What is the purpose of
__init__.py
in project directories?A) It allows Python to recognize the folder as a package.
B) It is useless and can be deleted.
C) It is used to initialize any empty values.
D) None of the above
Answer: A) It allows Python to recognize the folder as a package.
-
What is the correct order of steps to display a “Hello World” message using Django views and URLconf?
-
Create a view function that returns an HttpResponse with “Hello World”.
-
Create a urls.py file in your app directory and map a URL to the view function.
-
Add the app’s URLconf to the project’s urls.py.
-
Run the development server and visit the mapped URL.
-
A) 1, 2, 3, 4
B) 1, 3, 2, 4
C) 2, 1, 3, 4
D) 3, 2, 1, 4
Answer: A) 1, 2, 3, 4
- What happens when urls.py file is edited while the development server is still running?
A) Development server terminates.
B) The development server automatically restarts.
C) The development server does nothing.
D) The web page is automatically reloaded.
Answer: B) The development server automatically restarts.
- Which setting contains the parameter of the main URLs file?
A) ROOT_URLCONF
B) MAIN_URLCONF
C) STATIC_URL
D) MEDIA_URL
Answer: A) ROOT_URLCONF
- What is the purpose of
__init__.py
in project directories?
A) It allows Python to recognize the folder as a package.
B) It is useless and can be deleted.
C) It is used to initialize any empty values.
D) None of the above
Answer: A) It allows Python to recognize the folder as a package.
- Which method is used instead of path() in urls.py to pass in regular expressions as routes?
A) static()
B) re_path()
C) include()
D) url()
Answer: B) re_path()
- Which keyword is used to load another template in a template file?
A) import
B) include
C) from
D) None of these
Answer: B) include
- Which of these is not a valid method or approach to perform URL resolution in Django?
A) Using Template {{ url : }} in a template
B) Using reverse() in View Functions
C) Using get_absolute_url()
D) None of the above
Answer: A) Using Template {{ url : }} in a template
- What does the
__init__.py
file in a Django directory signify?
A) It initializes any empty values.
B) It is useless and can be deleted.
C) It allows Python to recognize the folder as a package.
D) It stores configuration settings.
Answer: C
- Which command is used to apply migrations in Django?
A) python manage.py apply
B) python manage.py migrate
C) python manage.py runserver
D) python manage.py migrateapp
Answer: B
- What is the purpose of the Django admin interface?
A) To manage user permissions
B) To serve static files
C) To create, read, update, and delete content
D) To handle URL routing
Answer: C
- Which function should be used in Django URLs to include other URL patterns?
A) path()
B) re_path()
C) include()
D) url()
Answer: C
- What does the Post.objects.all() method do in Django?
A) Creates a new Post object
B) Deletes all objects in the Post table
C) Retrieves all objects from the Post table
D) Updates all objects in the Post table
Answer: C
- What will happen if MyObject.objects.get() is called with parameters that do not match any item in the database?
A) The Http404 exception is raised
B) The DatabaseError exception is raised
C) The MyObject.DoesNotExist exception is raised
D) The object is created and returned
Answer: C
- What is a Django model?
A) A template for HTML files
B) A built-in feature that Django uses to create tables, fields, and constraints
C) A CSS framework
D) A JavaScript library
Answer: B) A built-in feature that Django uses to create tables, fields, and constraints
- Which command is used to create a new migration in Django?
A) migrate
B) create_migration
C) makemigrations
D) startmigration
Answer: C) makemigrations
- Which of the following is a supported database by Django?
A) PostgreSQL
B) MongoDB
C) CouchDB
D) Neo4j
Answer: A) PostgreSQL
- Which method is used to fetch a single object from the database in Django?
A) all()
B) filter()
C) get()
D) exclude()
Answer: C) get()
- Which field type would you use to store an email address in a Django model?
A) CharField
B) EmailField
C) TextField
D) URLField
Answer: B) EmailField
- Which of the following statements about Django ORM is true?
A) It requires manual SQL for all database operations.
B) It automatically handles database migrations without user input.
C) It simplifies database programming by mapping Python objects to database tables.
D) It is compatible with all NoSQL databases by default.
Answer: C) It simplifies database programming by mapping Python objects to database tables.
- What file do you typically edit to define URL patterns in a Django project?
a) settings.py
b) models.py
c) urls.py
d) views.py
Answer: c) urls.py
- What is the purpose of Django’s get_template method?
a) To fetch data from the database
b) To retrieve and render an HTML template
c) To handle user authentication
d) To manage static files
Answer: b) To retrieve and render an HTML template
- Which of the following is a built-in Django field type for handling email addresses?
a) CharField
b) TextField
c) EmailField
d) URLField
Answer: c) EmailField
- In Django’s Model-View-Template (MVT) pattern, which component is responsible for business logic?
a) Model
b) View
c) Template
d) Controller
Answer: b) View
- What is Django middleware?
A. A lightweight plugin that processes during request and response execution
B. A template engine
C. A database model
D. A URL dispatcher
Answer: A
-
有一个Django项目,其URLconf的配置如下。
项目的urls.py内容:
from django.urls import path, include urlpatterns = [ path('', views.hello_view), path('top10/', views.top10), path('movie/<int:year>/', views.year_list), path('movie/<int:year>/<int:quarter>/', views.quarter_list), path('movie/<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ]
请根据上述的设置,判断一下哪一组url都能正确访问?
A.
"http://localhost:8080/movies/ http://localhost:8080/movies/top10/ http://localhost:8080/movies/2022_12/ http://localhost:8080/movies/2022/4.5/ http://localhost:8080/movies/2022/1/cn_war/"
B.
"http://localhost:8080/movies/ http://localhost:8080/movies/top10/ http://localhost:8080/movies/2022/ http://localhost:8080/movies/2022/ http://localhost:8080/movies/2022/1.8/cn_war/"
C.
"http://localhost:8080/ http://localhost:8080/top10/ http://localhost:8080/movies/2022_2/ http://localhost:8080/movies/2022/4/ http://localhost:8080/movies/2022/a/cn_war/"
D.
"http://localhost:8080/ http://localhost:8080/top10/ http://localhost:8080/movie/2022/ http://localhost:8080/movie/2022/4/ http://localhost:8080/movie/2022/1/cn_war/"
-
有一个Django项目,其URLconf的配置如下。
项目的urls.py内容:
from django.urls import path, include urlpatterns = [ path('movies/', include('myapp.urls')), ]
在应用myapp目录下的urls.py中的内容如下:
urlpatterns = [ path('', views.hello_view), path('top10/', views.top10), path('<int:year>/', views.year_list), path('<int:year>/<int:quarter>/', views.quarter_list), path('<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ]
请根据上述的设置,判断一下哪一组url都能正确访问?
A.
"http://localhost:8080/movies/ http://localhost:8080/movies/top10/ http://localhost:8080/movies/2022/ http://localhost:8080/movies/2022/4/ http://localhost:8080/movies/2022/1/cn_war/"
B.
"http://localhost:8080/movies/ http://localhost:8080/movies/top10/ http://localhost:8080/movies/2022_12/ http://localhost:8080/movies/2022/4.5/ http://localhost:8080/movies/2022/1/cn_war/"
C.
"http://localhost:8080/movies/ http://localhost:8080/movies/top10/ http://localhost:8080/movies/2022/ http://localhost:8080/movies/2022/ http://localhost:8080/movies/2022/1.8/cn_war/"
D.
"http://localhost:8080/movies/ http://localhost:8080/movies/top10/ http://localhost:8080/movies/2022_2/ http://localhost:8080/movies/2022/4/ http://localhost:8080/movies/2022/a/cn_war/"
-
以下代码哪个能在浏览器上返回当前时间
A.
"def current_datetime(request): now = datetime.datetime.now() html = ""<html><body>It is now %s.</body></html>"" % now return HttpResponse(html)"
B.
"def current_datetime(request): now = datetime.datetime.now() html = ""<html><body>It is now</body></html>"" return HttpResponse(html)"
C.
"def current_datetime(request): now = datetime.datetime.now() html = ""<html><body>It is now %s.</body></html>"" % now return html"
D. 以上都不是
-
有一个Django项目,其URLconf的配置如下。
项目的urls.py内容:
from django.urls import path, include urlpatterns = [ path('movies/', include('myapp.urls')), ]
在应用myapp目录下的urls.py中的内容如下:
urlpatterns = [ path('', views.hello_view), path('top10/', views.top10), path('<int:year>/', views.year_list), path('<int:year>/<int:quarter>/', views.quarter_list), path('<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ]
请根据上述的设置,判断一下哪一项的代码与之等价?
A.
"项目的urls.py内容:
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ]
在应用myapp目录下的urls.py中的内容如下:
urlpatterns = [ path('', views.hello_view), path('top10/', views.top10), re_path('(?P<year>[0-9]{4})/$', views.year_list), re_path('(?P<year>[0-9]{4})/(?P<quarter>[1-4])/', views.quarter_list), path('<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ]"
B.
"项目的urls.py内容:
from django.urls import path, include urlpatterns = [ path('', views.hello_view), path('top10/', views.top10), re_path('(?P<year>[0-9]{4})/$', views.year_list), re_path('(?P<year>[0-9]{4})/(?P<quarter>[1-4])/', views.quarter_list), path('<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ]"
C.
"项目的urls.py内容:
from django.urls import path, include extra_patterns = [ path('', views.hello_view), path('top10/', views.top10), path('<int:year>/', views.year_list), path('<int:year>/<int:quarter>/', views.quarter_list), path('<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ] urlpatterns = [ path('movies/', include(extra_patterns)), ]"
D.
"项目的urls.py内容:
from django.urls import path, include urlpatterns = [ path('', views.hello_view), path('top10/', views.top10), path('<int:year>/', views.year_list), path('<int:year>/<int:quarter>/', views.quarter_list), path('<int:year>/<int:quarter>/<slug:slug>/', views.slug_list), ]"
-
有Django项目的url路由配置如下所示:
urlpatterns = [ path('set/', views.set_cookie, name='cset'), path('get/', views.get_cookie, name='cget'), path('del/', views.delete_cookie, name='cdel'), path('test/', views.cookie_test, name='ctest'), path('login/', views.login, name='login'), path('index/', views.index, name='index'), path('logout/', views.logout, name='logout'), path('register/', views.register, name='register'), path('active/', views.active_process), ]
请问哪个选项的模板中{%url%}可正确还原?
A.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>主页</title> </head> <body> <div> <hr> {% if is_login %} <h3>欢迎{{ username }}回来,登录成功</h3><br> <p>会话id:{{ sessionid }}</p> <hr> <a href=""{% url log_out %}"">注销</a> {% else %} <h3>尚未登录,请<a href=""{% url log_in %}"">点击这里</a>重新登录</h3> <hr> {% endif %} </div> </body> </html>"
B.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>主页</title> </head> <body> <div> <hr> {% if is_login %} <h3>欢迎{{ username }}回来,登录成功</h3><br> <p>会话id:{{ sessionid }}</p> <hr> <a href=""{% url 'log_out' %}"">注销</a> {% else %} <h3>尚未登录,请<a href=""{% url 'log_in' %}"">点击这里</a>重新登录</h3> <hr> {% endif %} </div> </body> </html>"
C.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>主页</title> </head> <body> <div> <hr> {% if is_login %} <h3>欢迎{{ username }}回来,登录成功</h3><br> <p>会话id:{{ sessionid }}</p> <hr> <a href=""{% url 'logout' %}"">注销</a> {% else %} <h3>尚未登录,请<a href=""{% url 'login' %}"">点击这里</a>重新登录</h3> <hr> {% endif %} </div> </body> </html>"
D.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>主页</title> </head> <body> <div> <hr> {% if is_login %} <h3>欢迎{{ username }}回来,登录成功</h3><br> <p>会话id:{{ sessionid }}</p> <hr> <a href=""{% 'logout' %}"">注销</a> {% else %} <h3>尚未登录,请<a href=""{% 'login' %}"">点击这里</a>重新登录</h3> <hr> {% endif %} </div> </body> </html>"
-
有模板hello.html如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title> </head> <body> <h1>Welcome to myapp.</h1> <p> Data is {{ list }}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %} </ul> </body> </html>
请问下面哪一个view函数能够正常渲染这个模板
A.
"def hello_view(request): context = { ""list"" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } return render(""hello.html"", context )"
B.
"def hello_view(request): context = { ""list"" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } return render(request, ""hello.html"" )"
C.
"def hello_view(request): context = { ""list"" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } return render(request, ""hello.html"" ,context)"
D.
"def hello_view(request): list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] return render(request, ""hello.html"" ,list)"
-
有如下view函数及模板,经模板引擎渲染后,页面上应显示包含艺术家名称及序号的两列多行表格,且表格每一行的背景色间隔变化。 如下模板在“
<!-- 此处代码缺失,需补充完整 -->
”部分,关键代码缺失,请选择,如下那个代码片段正式所缺失的部分。from django.shortcuts import render def hello_view(request): context = { "musicians_list": [ '路德维希·凡·贝多芬', '莫扎特', '肖邦', '德彪西', '海顿', '拉威尔', '巴赫', '弗朗茨·舒伯特', '柴可夫斯基', '弗朗茨·李斯特'], } return render(request, "home.html", context)
模板home.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .row-odd { background-color: #f2f2f2; } .row-even { background-color: #fde9d9; } </style> </head> <body> <h2>循环生成表格各行</h2></br> <table border="1"> <thead> <tr> <th>序号</th> <th>艺术家</th> </tr> </thead> <!-- 此处代码缺失,需补充完整 --> </table> </p> </body> </html>
A.
"{% for artist in musicians_list %} <tr class=""{% 'row-odd' 'row-even' %}""> <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> {% endfor %}"
B.
"{% for artist in musicians_list %} <tr class=""{% cycle 'row-odd' 'row-even' %}""> {# forloop 是内建的模板变量,值是一个整数,表示循环的次数。这个属性的值从 1 开始 #} <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> {% endfor %}"
C.
"{% for artist in musicians_list %} <tr class=""{% cycle 'row-odd' 'row-even' %}""> <td>{{ artist }}</td> </tr> {% endfor %}"
D.
" <tr class=""{% cycle 'row-odd' 'row-even' %}""> {# forloop 是内建的模板变量,值是一个整数,表示循环的次数。这个属性的值从 1 开始 #} <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> "
-
有Django项目mysite,在该项目的根目录下,建立了一个模板子目录templates,请问哪个设置代码是正确的?
A.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
B.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
C.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR)], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
D.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
-
有模板hello.html如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title> </head> <body> <h1>Welcome to myapp.</h1> <p> Data is {{ list }}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %} </ul> </body> </html>
请问下面哪一个view函数能够正常渲染这个模板
A.
"def hello_view(request): context = { ""list"" : [""one"", ""two"", ""three"", ""four"", ""five"", ""six""] } return render(""hello.html"", context )"
B.
"def hello_view(request): return render(request, ""hello.html"", { ""list"" : [""one"", ""two"", ""three"", ""four"", ""five"", ""six""] })"
C.
"def hello_view(request): context = { ""list"" : [""one"", ""two"", ""three"", ""four"", ""five"", ""six""] } return render(request, ""hello.html"" )"
D.
"def hello_view(request): ""list"" : [""one"", ""two"", ""three"", ""four"", ""five"", ""six""] return render(request, ""hello.html"" ,list)"
-
有Django项目,名为mysite,其模板配置代码如下:
...... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mytemplates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ......
请问选项中的哪个项目路径与之相匹配?
A.
"mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py myapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py templates/ tests.py views.py"
B.
"mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py templates/ myapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py"
C.
"mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py mytemplates/ myapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py"
D.
"mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py myapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py mytemplates/ tests.py views.py"
-
要在Django项目的配置文件中添加静态文件路径设置,请问如下哪个配置片段是正确的?
A.
...略... STATICURL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'common-static'), # 静态文件目录位置 ) ...略...
B.
...略... STATIC_URL = 'static/' STATICFILESDIRS = ( os.path.join(BASE_DIR, 'common-static'), # 静态文件目录位置 ) ...略...
C.
...略... STATICURL = 'static/' STATICFILESDIRS = ( os.path.join(BASE_DIR, 'common-static'), # 静态文件目录位置 ) ...略...
D.
...略... STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'common-static'), # 静态文件目录位置 ) ...略...
-
如下哪个选项是没有错误的Django模板代码?
A.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0""> <meta http-equiv=""X-UA-Compatible"" content=""ie=edge""> <title>Homepage</title> </head> <body> <h1>Welcome to myapp.</h1> <p> Data is {{ list }}</p> <h4>List is </h4> <ul> {{ for i in list }} <li>{{ i }}</li> {{ endfor }} </ul> </body> </html>"
B.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0""> <meta http-equiv=""X-UA-Compatible"" content=""ie=edge""> <title>Homepage</title> </head> <body> <h1>Welcome to myapp.</h1> <p> Data is {{ list }}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %} </ul> </body> </html>"
C.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0""> <meta http-equiv=""X-UA-Compatible"" content=""ie=edge""> <title>Homepage</title> </head> <body> <h1>Welcome to myapp.</h1> <p> Data is <% list %></p> <h4>List is </h4> <ul> <% for i in list %> <li><% i %></li> <% endfor %> </ul> </body> </html>"
D.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0""> <meta http-equiv=""X-UA-Compatible"" content=""ie=edge""> <title>Homepage</title> </head> <body> <h1>Welcome to myapp.</h1> <p> Data is {% list %}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{% i %}</li> {% endfor %} </ul> </body> </html>"
-
阅读选项中模板代码,请选出能够在页面上实现表格行间隔显示不同背景色效果的选项。
A.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>Title</title> <style type=""text/css""> .row-odd { background-color: #f2f2f2; } .row-even { background-color: #fde9d9; } </style> </head> <body> <table border=""1""> <thead> <tr> <th>序号</th> <th>艺术家</th> </tr> </thead> {% for artist in musicians_list %} <tr class=""{% cycle 'row-odd' 'row-even' %}""> <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> {% endfor %} </table> </body> </html>"
B.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>Title</title> <style type=""text/css""> .row-odd { background-color: #f2f2f2; } .row-even { background-color: #fde9d9; } </style> </head> <body> <table border=""1""> <thead> <tr> <th>序号</th> <th>艺术家</th> </tr> </thead> {% for artist in musicians_list %} <tr class=""{% 'row-odd' 'row-even' %}""> <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> {% endfor %} </table> </body> </html>"
C.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>Title</title> <style type=""text/css""> .row-odd { background-color: #f2f2f2; } .row-even { background-color: #fde9d9; } </style> </head> <body> <table border=""1""> <thead> <tr> <th>序号</th> <th>艺术家</th> </tr> </thead> {% for artist in musicians_list %} <tr class=""{% ['row-odd' ,'row-even'] %}> <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> {% endfor %} </table> </body> </html>"
D.
"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <title>Title</title> <style type=""text/css""> .row-odd { background-color: #f2f2f2; } .row-even { background-color: #fde9d9; } </style> </head> <body> <table border=""1""> <thead> <tr> <th>序号</th> <th>艺术家</th> </tr> </thead> {% for artist in musicians_list %} <tr class=""row-odd row-even""> <td>{{ forloop.counter }}</td> <td>{{ artist }}</td> </tr> {% endfor %} </table> </body> </html>"
-
有Django项目名称为mysite,应用为myapp,其有如下模型定义代码:
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) publication_date = models.DateField() num_pages = models.IntegerField(blank=True, null=True)
请选择上述模型间关系描述正确的选项?
A. Book与Author是多对多关系,Book与Publisher是一对多关系,Author与Publisher是隐含关联关系
B. Book与Author是多对多关系,Book与Publisher是一对多关系,Author与Publisher间无关联关系
C. Book与Author是一对多关系,Book与Publisher是多对多关系,Author与Publisher间无关联关系
D. 以上都不对
-
有Django项目名称为mysite,应用为myapp,其有如下模型定义代码:
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField()
以下哪个操作可以完成Publisher数据的添加?
A.
pub_dz = Publisher.create(name='电子工业出版社',address='万寿路南口金家村288号',city='北京', state_province='北京',country='中国',website='https://www.phei.com.cn/')
B.
pub_dz = Publisher(name='电子工业出版社',address='万寿路南口金家村288号',city='北京', state_province='北京',country='中国',website='https://www.phei.com.cn/')
C.
"pub_dz = Publisher(name='电子工业出版社',address='万寿路南口金家村288号',city='北京', state_province='北京',country='中国',website='https://www.phei.com.cn/') pub_dz.save()"
D.
"pub_dz = Publisher(name='电子工业出版社',address='万寿路南口金家村288号',city='北京', state_province='北京',country='中国',website='https://www.phei.com.cn/') pub_dz.objects.save()"
-
有Django项目名称为mysite,应用为myapp,其有如下模型定义代码:
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField()
以下哪个选项可以实现不区分大小写查询名称中包含“Reilly”的出版商?
A.
Publisher.filter(name__contains="Reilly")
B.
Publisher.filter(name__icontains="Reilly")
C.
Publisher.objects.filter(name__contains="Reilly")
D.
Publisher.objects.filter(name__icontains="Reilly")
-
有Django项目名称为mysite,应用为myapp,其有如下模型定义代码:
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) publication_date = models.DateField() num_pages = models.IntegerField(blank=True, null=True)
以下选项哪一个是包含错误操作语句的选项。
A.
Publisher.objects.get(name is None)
B.
Publisher.objects.get(name="O'Reilly")
C.
pub_list = Publisher.objects.filter(country='中国') books = Book.objects.filter(publisher__in=pub_list)
D.
Book.objects.filter(id__in = [2,4,6])
-
有表单如下:
<form method="POST" action="{% url 'login' %}" > {% csrf_token %} <label >用户名</label> <input type="text" name="user" placeholder="请输入用户名" > <label >密码:</label> <input type="password" name="pwd" placeholder="************"> </form>
请问下面那个代码片段能正常接收表单数据并完成用户登录检查?
A.
if request.method == ""POST"": username = request.POST.get('user') pwd = request.POST.get('pwd') try: user = User.objects.get(name=username) if check_password(pwd, user.psw): request.session[user.uid] = username request.session['is_login'] = user.uid return redirect('index') else: return render(request, 'login.html') except MultipleObjectsReturned: return render(request, 'icoder/login.html', {'messages': ['用户重复', ]}) except ObjectDoesNotExist: return render(request, 'icoder/login.html', {'messages': ['用户不存在', ]})
B.
if request.method == ""GET"": username = request.GET.get('user') pwd = request.GET.get('pwd') try: user = User.objects.get(name=username) if check_password(pwd, user.psw): request.session[user.uid] = username request.session['is_login'] = user.uid return redirect('index') else: return render(request, 'login.html') except MultipleObjectsReturned: return render(request, 'icoder/login.html', {'messages': ['用户重复', ]}) except ObjectDoesNotExist: return render(request, 'icoder/login.html', {'messages': ['用户不存在', ]})
C.
if request.method == ""POST"": username = request.POST.get('username') pwd = request.POST.get('password') try: user = User.objects.get(name=username) if check_password(pwd, user.psw): request.session[user.uid] = username request.session['is_login'] = user.uid return redirect('index') else: return render(request, 'login.html') except MultipleObjectsReturned: return render(request, 'icoder/login.html', {'messages': ['用户重复', ]}) except ObjectDoesNotExist: return render(request, 'icoder/login.html', {'messages': ['用户不存在', ]})
D.
if request.method == ""POST"": username = request.POST.get('user') pwd = request.POST.get('pwd') print(request.POST) try: user = User.objects.get(name=username) except MultipleObjectsReturned: return render(request, 'icoder/login.html', {'messages': ['用户重复', ]}) except ObjectDoesNotExist: return render(request, 'icoder/login.html', {'messages': ['用户不存在', ]})
-
有模板代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生信息</title> </head> <body> <form method="POST" action="/stu/"> {% csrf_token %} <div > <br> <div> <div> <h3>输入学生信息</h3> </div> </div> <div> {{ form.as_p }} </div> <hr> <div> <div> <button type="reset" >重置</button> <button type="submit" >提交</button> </div> </div> </div> </form> </body> </html>
url路由配置如下:
urlpatterns = [ path('stu/', views.stu), ]
如下哪个选项中的view函数定义可以完成学生数据的接收与保存操作?
A.
def stu(request): if request.method == ""GET"": form = StudentForm(request.GET) if form.is_valid(): try: request.save() return HttpResponse('接收到提交的数据,保存成功!') except: return HttpResponse('数据库操作异常,保存数据失败') else: form = StudentForm() return render(request, 'index.html', {'form': form})
B.
def stu(request): if request.method == ""GET"": form = StudentForm(request.GET) if form.is_valid(): try: form.save() return HttpResponse('接收到提交的数据,保存成功!') except: return HttpResponse('数据库操作异常,保存数据失败') else: form = StudentForm() return render(request, 'index.html', {'form': form})
C.
def stu(request): if request.method == ""POST"": form = StudentForm(request.POST) if form.is_valid(): try: form.save() return HttpResponse('接收到提交的数据,保存成功!') except: return HttpResponse('数据库操作异常,保存数据失败') else: form = StudentForm() return render(request, 'index.html', {'form': form})
D.
def stu(request): if request.method == ""POST"": form = StudentForm(request.POST) if form.is_valid(): try: request.save() return HttpResponse('接收到提交的数据,保存成功!') except: return HttpResponse('数据库操作异常,保存数据失败') else: form = StudentForm() return render(request, 'index.html', {'form': form})
-
有Django项目,model定义如下:
class Student(models.Model): stu_id = models.CharField(max_length=20) # 学号 stu_name = models.CharField(max_length=50) # 姓名 stu_gender = models.CharField(max_length=2) # 性别 stu_birthdate = models.DateField() # 出生日期 stu_class = models.CharField(max_length=10) # 班级 stu_contact = models.CharField(max_length=20, blank=True) # 联系电话 stu_email = models.EmailField(blank=True) # 电子邮箱
与之绑定的ModelForm定义是如下哪一个?
A.
from django import forms from .models import Student class StudentForm(models.Model): class Meta: model = Student fields = '__all__'
B.
from django import forms from .models import Student class StudentForm(): class Meta: model = Student fields = '__all__'
C.
from django import forms from .models import Student class StudentForm(forms.Form): class Meta: model = Student fields = '__all__'
D.
from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields = '__all__'
-
In Django, to include another URL pattern you should always use ____ when you include other URL patterns, except for admin.site.urls.
Answer: include()
-
In the Django template system, forloop.counter is an example of a valid attribute used in a ____ loop.
Answer: for
-
To avoid template loading conflicts in Django, it is recommended to add an additional ____ to act as a namespace inside each templates directory.
Answer: sub-folder
-
The command to start a Django development server is __.
Answer: python manage.py runserver
-
In Django, to reference other URLconfs, the __ function is used.
Answer: include
-
To bring all the objects stored in a Django model named Post, you would use the method __.
Answer: Post.objects.all()
-
Django uses the __ command to create migrations based on changes to models.
Answer: makemigrations
-
In Django, to save an object to the database, the __ method is called on the object.
Answer: save()
-
Django’s __ method is used to filter querysets based on given parameters, translating them into SQL WHERE clauses.
Answer: filter()
-
In Django, the views.py file contains functions that handle the __ logic of the application.
Answer: business
-
The django.db.models.Model is a base class for defining __ in Django, which are used to interact with the database.
Answer: models
-
The command python manage.py runserver is used to start the Django development server.
Answer: True
-
You should always use include() when you include other URL patterns in Django.
Answer: True
-
In Django, models.py is where we define our database models which Django automatically translates into database tables.
Answer: True
-
The admin.py file in a Django app is used for configuring the app itself.
Answer: False (It is used for configuring the built-in Django Admin app)
-
The
__init__.py
file in a Django application is required for Python to recognize the directory as a package.Answer: True
-
In Django, the include() function should always be used when including other URL patterns except for admin.site.urls.
Answer: True
-
The CharField in Django is used to store large text data.
Answer: False
-
The INSTALLED_APPS setting in Django’s settings file tells Django which apps are activated for a given project.
Answer: True
-
In Django, the INSTALLED_APPS setting in settings.py is used to register the applications that are enabled in the project.
Answer: True
-
The makemigrations command in Django is used to apply migrations and sync the database with the models.
Answer: False
(The makemigrations command creates new migrations based on the changes detected to your models; migrate is used to apply those migrations)
-
Django middleware classes must subclass a specific Django middleware base class.
Answer: False
-
The process_response method in Django middleware is executed in the top-down order of the middleware stack.
Answer: False
-
In Django, the SessionMiddleware is responsible for generating unique session IDs.
Answer: True
—— writing by Pan Qifan(潘琦藩) ——