Django常见问题集

时间:2022-03-02 21:47:20
django2.0发行文档说,django2.0最后一个支持的是python3.4+...

所以,还在用python2.7的同学只能手动指定版本下载了

pip2 install django==1.8.17 或 pip2 install django==1.10

摘自:https://docs.djangoproject.com/en/2.0/releases/2.0/

Python2.7.x 下载django的报错

'''
在新创建的Django项目中执行makemigrations时,遇到:
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fault_reporting.userinfo', but app 'fault_reporting' isn't installed.
这类app并没有安装的错误
而仔细观察,这个报错的app名字是我们之前项目中的app名字,但现在却在我们当前的项目中报错了。究其原因,则是因为之前的项目中的app缓存被存在了Django的模块内的"某些地方"
而我们当在新的项目中用到"某些地方"的功能时,执行了之前的缓存内容,从而引发错误
而普通的解决办法,就是删除当前项目中的.idea文件和__pycache__文件,然后就是删除migrations文件下的00开头的py文件都解决不了。甚至是卸载Django重新安装————都没用!
因为我们并没有删除Django模块中"某些地方"的缓存文件(pip uninstall Django都清不了这些缓存文件)。so,我们要手动去删除这这个"某个地方"的缓存文件
打开你的解释器下的Lib\site-packages\django\contrib\admin\migrations
删除除了__init__.py外的其他的文件
然后再次运行makemigrations即可
see also:https://*.com/questions/40222268/valueerror-in-django-when-running-the-python-manage-py-migrate-command
'''

makemigrations时遇到ValueError:Related mode 'app01.Userinfo' cannot be resolved

from django.db import models

class UserInfo(models.Model):
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32) class Token(models.Model):
user = models.OneToOneField(UserInfo,on_delete=None)
token = models.CharField(max_length=64) # 关键字on_delete=None
# 2.0版本在源码中取消了on_delete=None,需要手动传递, class OneToOneField(ForeignKey): def __init__(self, to, on_delete, to_field=None, **kwargs): # 源码中取消默认值
kwargs['unique'] = True
super().__init__(to, on_delete, to_field=to_field, **kwargs) # 而在django1.11.5和1.8.17版本中,都是有默值的
def __init__(self, to, on_delete=None, to_field=None, **kwargs):

django2.x版本关于model在绑定外键的时候,遇到on_delete报错

 启动报错:SyntaxError: Generator expression must be parenthesized,有时候,在使用命令python manager.py runserver时,会发先启动失败,报错日志如下:
[root@cs es_demo]# python37 manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f220f0edae8>
Traceback (most recent call last):
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/apps/config.py", line 94, in create
module = import_module(entry)
File "/usr/local/python/python37/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 4, in <module>
from django.contrib.admin.filters import (
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/filters.py", line 10, in <module>
from django.contrib.admin.options import IncorrectLookupParameters
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/options.py", line 12, in <module>
from django.contrib.admin import helpers, widgets
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/widgets.py", line 151
'%s=%s' % (k, v) for k, v in params.items(),
^
SyntaxError: Generator expression must be parenthesized 可以发现最后一行提示说是语法错误,说是生成器表达式有问题,那具体的报错行内容是'%s=%s' % (k, v) for k, v in params.items(),,可以看到,最后一个标点符号很有意思,我们找到源码文件对应的行,把这个标点符号去掉即可。
ps:如果是pycharm中修改的话,由于这个文件是源码,还要注意提示框中选择I want to edit this file anyway。

Django之启动报错:Generator expression must be parenthesized

# Django1.11 + Python3.6 + win10
"""
可能的原因
在ROM与ajax交互时,难免会遇到传递queryset对象,但是你会发现使用`JsonResponse`并不好用
"""
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
def ui_index(request):
if request.method == 'POST':
pk = request.POST.get('pk')
result = ui_models.UiCase.objects.filter(case_vest_project=pk)
# return HttpResponse({"case": result})
return JsonResponse({"case": result}) # 依然不好使 # 就算使用`JsonResponse({"case": result})`依然不好使:
```
TypeError: Object of type 'QuerySet' is not JSON serializable
``` **可能的解决办法** ```python
from django.core import serializers
def ui_index(request):
if request.method == 'POST':
pk = request.POST.get('pk')
result = ui_models.UiCase.objects.filter(case_vest_project=pk)
return JsonResponse({"case": serializers.serialize('json', result)})
``` 这个时候,可以使用`serializers`来解决。然后前端的ajax正常接收即可,无需反序列化: ```html
<script>
$(".selected_project").on('click', 'li', function () {
var pk = $(this).attr('pk');
$.ajax({
url: "{% url 'ui_index' %}",
type: "POST",
data: {'pk': pk},
success: function (data) {
console.log(typeof(data), data);
if (data) {
$.each(data, function (index, item) {
console.log(item.case_name, item.pk, )
})
}
}
})
})
</script>
``` see also:[【已解决】Object of type 'QuerySet' is not JSON serializable](<http://www.voidcn.com/article/p-dwqjezai-bpk.html>)

Django1.11:SyntaxError: Generator expression must be parenthesized


欢迎斧正,that's all