【python学习笔记】

         【操作系统:macOS】、      【python版本:3.8】、     【Django版本:4.0.5】

        这几天跟着Eric Matthes的《Python编程从入门到实践》学了下python,书是2016年7月版的,可能是由于时间上比较久远,里面一些例子与现今的python版本略有冲突,所以学习过程中也遇到些麻烦,作为新手小白也是经过各方查资料方才解决,因此呢想着做个汇总或许对需要的人是个帮助,也方便自己以后查阅吧。

        闲话不说,步入正题。

        这篇文主要汇总了在第三个项目web建站部分所遇到的一些问题。

       一、环境搭建篇

        问题一:建立虚拟环境

        1)报错:(我使用的python3,使用python命令行执行报错:“No module named venv”)

192:learning_log$ python -m venv ll_env
/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No module named venv

        2)解决:(如果使用的python3,请替换命令行python为python3)

192:learning_log$ python3 -m venv ll_env
192:learning_log$

        问题二:在Django中创建项目

        执行命令:django-admin.py startproject learning_log .

        1)报错:(command not found 找不到命令。)

(ll_env) 192:learning_log$ django-admin.py startproject learning_log .
-bash: django-admin.py: command not found

        2)解决:(更换命令行为:django-admin startproject learning_log .  去掉原命令中的.py) 

(ll_env) 192:learning_log$ django-admin startproject learning_log .
(ll_env) 192:learning_log$ 

        二、 程序代码篇

        问题一:定义模型Entry时报错(文件:models.py

        1) 报错:(TypeError: __init__() missing 1 required positional argument: 'on_delete' ,意思是ForeignKey()函数缺少参数)

(ll_env) 192:learning_log$ python manage.py makemigrations learning_logs
Traceback (most recent call last):
  File "manage.py", line 22, in   main()
  File "manage.py", line 18, in main execute_from_command_line(sys.argv)
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/core/management/__init__.py", line 420, in execute
    django.setup()
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/apps/registry.py", line 116, in populate
    app_config.import_models()
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/apps/config.py", line 304, in import_models
    self.models_module = import_module(models_module_name)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "", line 1014, in _gcd_import
  File "", line 991, in _find_and_load
  File "", line 975, in _find_and_load_unlocked
  File "", line 671, in _load_unlocked
  File "", line 783, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "/Users/learning_log/learning_logs/models.py", line 16, in 
    class Entry(models.Model):
  File "/Users/learning_log/learning_logs/models.py", line 18, in Entry
    topic = models.ForeignKey(Topic)
TypeError: __init__() missing 1 required positional argument: 'on_delete'
(ll_env) 192:learning_log pandatv$

        2)解决:(修改models.py文件中ForeignKey()函数,添加第二个参数         on_delete=models.CASCADEΩ on_delete=models.CASCADE。)

        models.py

from django.db import models

# Create your models here.

class Topic(models.Model):
	"""用户学习的主题"""
	text = models.CharField(max_length=200)
	date_added = models.DateTimeField(auto_now_add=True)

	def __str__(self):
		"""返回模型的字符串表示"""	
		return self.text


class Entry(models.Model):
	"""学到的有关某个主题的具体知识"""
	#topic = models.ForeignKey(Topic) #错误代码:这里是书中缺少参数的代码
	topic = models.ForeignKey(Topic, on_delete=models.CASCADE)  #✅正确代码
	text = models.TextField()
	date_added = models.DateTimeField(auto_now_add=True)

	class Meta:
		verbose_name_plural = 'entries'

	def __str__(self):
		"""返回模型的字符串表示"""	
		return self.text[:50] + "..."

        问题二:映射URL(文件:urls.py

        1)错误1:(ImportError: cannot import name 'url' from 'django.conf.urls' )

ll_env) 192:learning_log$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/core/management/commands/runserver.py", line 134, in inner_run
    self.check(display_num_errors=True)
  File "/Users/learning_log/ll_env/lib/python3.8/sitepackages/django/core/management/base.py", line 487, in check
    all_issues = checks.run_checks(
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver
    return check_method()
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 480, in check
    for pattern in self.url_patterns:
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/utils/functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 696, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/utils/functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 689, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "", line 1014, in _gcd_import
  File "", line 991, in _find_and_load
  File "", line 975, in _find_and_load_unlocked
  File "", line 671, in _load_unlocked
  File "", line 783, in exec_module
  File "", line 219, in _call_with_frames_removed
  File "/Users/pandatv/python_ljy/learning_log/learning_log/urls.py", line 17, in 
    from django.conf.urls import include, url 
ImportError: cannot import name 'url' from 'django.conf.urls' (/Users/learning_log/ll_env/lib/python3.8/site-packages/django/conf/urls/__init__.py)

        2) 错误2:(Specifying a namespace in include() without providing an app_name is not supported,path()函数中include()参数错误。)

File "/Users/learning_log/learning_log/urls.py", line 24, in 
    path('', include('learning_logs.urls', namespace='learning_logs')),
  File "/Users/learning_log/ll_env/lib/python3.8/site-packages/django/urls/conf.py", line 42, in include
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

        3)解决:

        错误1是因为我这个版本(Django - 4.0.5版本)所对应的urls的文件路径不一样,修改为相应的文件路径即可。

        错误2是因为path()函数中include()参数错误,将path('', include('learning_logs.urls', namespace='learning_logs')),修改为:path('', include(('learning_logs.urls','learning_logs'), namespace='learning_logs')),即可。

        urls.py

from django.contrib import admin
#from django.conf.urls import include, url #错误1代码
from django.urls import include, path #正确1代码

urlpatterns = [
    #url(r'^admin/',include(admin.site.urls)),
    #url(r'',include('learning_logs.urls', namespace='learning_logs')),
    path('admin/', admin.site.urls),
    #path('', include('learning_logs.urls', namespace='learning_logs')),# 错误2代码
    path('', include(('learning_logs.urls','learning_logs'), namespace='learning_logs')), #正确2代码
]

你可能感兴趣的:(python,学习,django,python)