Django实现Web应用显示单个主题时出现错误: 'function' object has no attribute 'entry_set'

1。 实现显示单个主题时,点击单个主题出现以下错误

'function' object has no attribute 'entry_set'

Request Method: GET

Request URL: http://localhost:8000/topics/(%3FP1%5Cd+)/

Django Version: 2.1.4

Exception Type: AttributeError

Exception Value: 'function' object has no attribute 'entry_set'

Exception Location: D:\Python_env\learning_log\learning_logs\views.py in topic, line 22

Python Executable: D:\Python_env\learning_log\11_env\Scripts\python.exe

  1. 源代码如下
from django.shortcuts import render
from .models import Topic

# Create your views here.

def index(request):
    return render(request, 'learning_logs/index.html')


def topics(request):
    # 显示所有的主题
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)


def topic(request, topic_id):
    """显示单个主题及其所有的条目"""
    topic = Topic.objects.get(id = topic_id)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

好像问题是出在entries = topic.entry_set.order_by('-date_added')
entry_set没有定义吗?

2个回答

entry_set其中的entry是指你用models创建的一张表,如果我没猜错的话你再models里并没有定义class entry():

qq_40816856
qq_40816856 建议查一下一对多数据关系的详解
12 个月之前 回复

topic没有entry_set这个属性,建议调试下面函数中的entries
def topic(request, topic_id):
"""显示单个主题及其所有的条目"""
topic = Topic.objects.get(id = topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
使用Python的Django框架做Web应用时的中文乱码问题

在两个地方使用了中文:一个是python源文件中,一个是html模板中。在用浏览器查看该页时出现乱码,形如:"????",但是将浏览器的编码改为gb2312或gbk是正常的(浏览器默认使用utf8编码) python代码: Python代码 收藏代码 #coding=utf-8 from django.shortcuts import render_to_response address = [ {'name':'张三', 'address':'地址一'}, {'name':'李四', 'address':'地址二'} ] def index(request): return render_to_response('list.html', {'address':address}) html代码: Html代码 收藏代码 <h2>通讯录</h2> <table border="1"> <tr><th>姓名</th><th>地址</th></tr> {% for user in address %} <tr> <td>{{ user.name }}</td> <td>{{ user.address }}</td> </tr> {% endfor %} </table>

Django创建超级用户时,出现错误 ValueError: invalid literal for int() with base 10: ''

ERROR exception 135 Internal Server Error: /users/ Traceback (most recent call last): File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/generics.py", line 242, in post return self.create(request, *args, **kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/mixins.py", line 24, in perform_create serializer.save() File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/rest_framework/serializers.py", line 213, in save self.instance = self.create(validated_data) File "/home/python/dihai02/per02/apps/users/serializers/user.py", line 25, in create user = User.objects.create_user(**validated_data) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/contrib/auth/models.py", line 159, in create_user return self._create_user(username, email, password, **extra_fields) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/contrib/auth/models.py", line 153, in _create_user user.save(using=self._db) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/base.py", line 924, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/base.py", line 963, in _do_insert using=using, raw=raw) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1111, in execute_sql for sql, params in self.as_sql(): File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1064, in as_sql for obj in self.query.objs File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1064, in <listcomp> for obj in self.query.objs File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1063, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1003, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value value = self.get_prep_value(value) File "/home/python/.virtualenvs/yuan/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: ''

Python编程从入门到实践 第18章Django入门 第365页“添加主题”出错,找不出原因,求大神帮忙

电脑系统为64位的win7,python为64位的3.7.4版本,Django为2.2.4版本,学习第365页“添加主题”遇到了麻烦 ,自己摸索了很长时间,网上也搜索了很久还是没解决,求大神帮帮小白。 ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566913286_833364.jpg) 在添加Chess主题时网页和终端里都报错,终端错误截图如下: ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566912120_690258.png) 网页错误最前面的截图如下: ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566912225_331720.png) 网页错误提示很长,下面这张是最后带提示的截图,我按照提示把settings.py文件里的DEBUG = False后,终端就退出了,再次运行python manage.py runserver终端也无法启动。 ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566912555_34630.png) 仔细检查代码也没查出来,models.py,settings.py,admins.py代码如下: ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566913232_687107.png) ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566913242_373496.png) ![图片说明](https://img-ask.csdn.net/upload/201908/27/1566913253_641400.png)

如何把Django+sqlite应用打包发布成可独立运行的桌面程序?

如何把Django+sqlite应用打包发布成可独立运行的桌面程序?需求:在pc上运行django+sqlite应用,无须安装django python 数据库 web服务器

Django出现TemplateDoesNotExist

如题,昨天在用Django进行web制作时,运行后出现TemplateDoesNotExist![图片说明](https://img-ask.csdn.net/upload/201803/18/1521368429_342791.jpg) 在网上查了很多资料,大多都是改setting.py里的DIR,但是我都试过了还是没有用。 最后我返回那个网页看到有两行django.template.loaders.app_directories.Loader: C:\Users\60243\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\lalala.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\60243\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\lalala.html (Source does not exist) 说实在auth和admin找不到我的html文件,后来我就照着路径把文件放进去,发现可以显示页面了。 但是我每次新作一个网页都得重新把html手动放在那两个文件夹里,感觉很麻烦,想问问大家有没有什么方法能够直接运行就能在那两个文件夹里生成写好的html??

django 图片无法显示的问题

![图片说明](https://img-ask.csdn.net/upload/201903/11/1552301506_953284.jpg) <br> django中我已经知道了图片的网络地址为http://i2.chuimg.com/f33fab1173f04d4b96881d05a20dc170_1080w_864h.jpg?imageView2/2/w/300/interlace/1/q/90 但是直接用img标签加src属性无法显示,如图: <br> ![图片说明](https://img-ask.csdn.net/upload/201903/11/1552301642_611196.jpg) 应该是django框架的问题,不知道如何解决? <br><br><br> 补充: 图片来自下厨房菜谱的步骤图片 ![图片说明](https://img-ask.csdn.net/upload/201903/11/1552310399_994992.jpg) <br> 比如这个图片的链接http://i1.chuimg.com/922148db022348169963faad8375d379_1078w_1348h.jpg@2o_50sh_1pr_1l_300w_90q_1wh <br> ![图片说明](https://img-ask.csdn.net/upload/201903/11/1552310452_784760.jpg) 我可以直接打开

django admin后台无法显示图片

请教下各个大牛, 怎我上传的图片在admin显示不出来呢 ? 谢谢呀 models.py ``` class Image(models.Model): Phase = models.ForeignKey(Growth_phase,on_delete=True) pic = models.ImageField(u'图片',upload_to='image') comments = models.CharField(max_length=30,blank=True) date_upload = models.DateTimeField(auto_now_add=True) ``` admin.py ``` from django.contrib import admin # Register your models here. from app_aman_growth.models import Growth_phase,Image from django.utils.safestring import mark_safe admin.site.register(Growth_phase) @admin.register(Image) class ImageAdmin(admin.ModelAdmin): list_display = ('Phase','comments','pic') readonly_fields = ('pic',) def image_data(self): return mark_safe(u'<img src="%s" width="100px" />'.format(self.pic.url)) image_data.short_description = u'图片' ``` setting.py ``` MEDIA_ROOT = r'D:\Program Files\Python3.7.2\Aman' MEDIA_URL = '/images/' ```

求助:Nginx+Gunicorn部署 Django后遇到Not Found错误

问题描述: Nginx+Gunicorn部署 Django后遇到Not Found错误 ![图片说明](https://img-ask.csdn.net/upload/202003/09/1583754685_161046.png) 服务器版本:CentOS 7.5 x64 说明:在虚拟环境中使用django自带的runserver运行(0.0.0.0:8000)后,使用公网IP:端口/index可以正常访问项目,关闭debug后使用 ``` pipenv run gunicorn blogproject.wsgi -w 2 -k gthread -b 0.0.0.0:8000 ``` 运行也可以正常访问,但是开启nginx后运行就出现如图错误。 /etc/nginx/conf.d/django-blog.conf配置如下 ``` [zijeak@VM_16_8_centos conf.d]$ cat django-blog.conf server { charset utf-8; listen 80; server_name 119.27.169.70; location /static { alias /home/zijeak/apps/django-blog/static; } location / { proxy_set_header Host $host; proxy_pass http://127.0.0.1:8000; } } ``` 查看nginx日志如下: ``` [zijeak@VM_16_8_centos conf.d]$ sudo nginx -t [sudo] password for zijeak: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful ``` 项目目录如下: ![图片说明](https://img-ask.csdn.net/upload/202003/09/1583755294_598395.png)

django连接MySQL报错django.db.utils.OperationalError: (2006, <NULL>)?

最近想学django,于是照着Django官方文档一步步学,没想到刚到连接数据库,就卡了。 在pycharm上通过django连接MySQL报如图所示错误![图片说明](https://img-ask.csdn.net/upload/201908/25/1566734912_878477.png)![图片说明](https://img-ask.csdn.net/upload/201908/25/1566734921_243846.png)![图片说明](https://img-ask.csdn.net/upload/201908/25/1566734929_53248.png) 网上搜索,试了各种方法,包括改hosts文件和HOST改成127.0.0.1,都不成功。把下面这几行代码注释掉,换成原来的sqlite,就可以成功运行,实在不知道什么原因,请各位大佬帮忙看下怎么解决。 环境:Django2.2.1、MySql8.0 下面是我的setting.py文件。一开始pycharm也连不上Mysql,我改了他的时区,Asia/Shanghai,就可以了,但是Django怎么也连不上 ``` """ Django settings for webProject project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'uri0z)r@kn3p)l%6(9if)1$74kv9ag$p@zadp_p$ph_x0(v9h=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'webProject.urls' 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', ], }, }, ] WSGI_APPLICATION = 'webProject.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'webcrawler', 'USER': 'root', 'PASSWORD': '111111', 'HOST': 'localhost', 'PORT': '3306', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' ```

求大佬解答,我用matplotlib绘制的图能在Django web项目中动态显示吗?

我用matplotlib可以生成出图来,怎么把这个图放到Django web项目的页面里,让我打开网页看到的图和直接运行py代码得到的图是一样的效果?求大佬指点一番

在iis上部署django进行登录时提示错误

Environment: Request Method: POST Request URL: http://localhost/admin/login/?next=/admin/ Django Version: 1.9.6 Python Version: 2.7.11 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "D:\python\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "D:\python\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\python\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "D:\python\lib\site-packages\django\contrib\admin\sites.py" in login 413. return login(request, **defaults) File "D:\python\lib\site-packages\django\contrib\auth\views.py" in inner 49. return func(*args, **kwargs) File "D:\python\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "D:\python\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "D:\python\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "D:\python\lib\site-packages\django\contrib\auth\views.py" in login 76. auth_login(request, form.get_user()) File "D:\python\lib\site-packages\django\contrib\auth\__init__.py" in login 110. request.session.cycle_key() File "D:\python\lib\site-packages\django\contrib\sessions\backends\base.py" in cycle_key 305. self.create() File "D:\python\lib\site-packages\django\contrib\sessions\backends\db.py" in create 53. self.save(must_create=True) File "D:\python\lib\site-packages\django\contrib\sessions\backends\db.py" in save 86. obj.save(force_insert=must_create, using=using) File "D:\python\lib\site-packages\django\db\models\base.py" in save 708. force_update=force_update, update_fields=update_fields) File "D:\python\lib\site-packages\django\db\models\base.py" in save_base 736. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "D:\python\lib\site-packages\django\db\models\base.py" in _save_table 820. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "D:\python\lib\site-packages\django\db\models\base.py" in _do_insert 859. using=using, raw=raw) File "D:\python\lib\site-packages\django\db\models\manager.py" in manager_method 122. return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\python\lib\site-packages\django\db\models\query.py" in _insert 1039. return query.get_compiler(using=using).execute_sql(return_id) File "D:\python\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 1060. cursor.execute(sql, params) File "D:\python\lib\site-packages\django\db\backends\utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "D:\python\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "D:\python\lib\site-packages\django\db\utils.py" in __exit__ 95. six.reraise(dj_exc_type, dj_exc_value, traceback) File "D:\python\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "D:\python\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 323. return Database.Cursor.execute(self, query, params) Exception Type: OperationalError at /admin/login/ Exception Value: unable to open database file ``` ```

Django升级后出现了ModuleNotFoundError: No module named 'Studentdjango' 请求大神帮忙看一下

![图片说明](https://img-ask.csdn.net/upload/201909/26/1569496534_51916.png)![图片说明](https://img-ask.csdn.net/upload/201909/26/1569496543_620157.png) 代码应该没什么问题,是看的教材上写的,不知道为什么把Django升级后,就 出现了这样的错误,想知道这应该是怎么解决啊

Django hello world在网页上错误404

![![![![图片说明](https://img-ask.csdn.net/upload/201703/31/1490933634_953225.png)图片说明](https://img-ask.csdn.net/upload/201703/31/1490933627_971212.png)图片说明](https://img-ask.csdn.net/upload/201703/31/1490933617_381153.png)图片说明](https://img-ask.csdn.net/upload/201703/31/1490933609_935821.png)

Pycharm 创建Django出现的问题

通过pycharm 创建 Django 出现 AttributeError: module 'pip' has no attribute 'main'的错误 ![图片说明](https://img-ask.csdn.net/upload/201910/15/1571141576_843540.png) 通过百度 尝试了第一种方法 pip降级 。 第二种方法 修改安装pycharm软件的目录packaging_tool.py 文件,def do_install(pkgs): try: #import pip try: from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main(['install'] + pkgs) def do_uninstall(pkgs): try: #import pip try: from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main(['uninstall', '-y'] + pkgs) 以上方法都没有用,解决方法链接https://blog.csdn.net/u010042585/article/details/80447109 修改完后出现这样的错误 ![图片说明](https://img-ask.csdn.net/upload/201910/15/1571141765_705180.png) 求解决啊,光是这个我都弄了3个小时了。还不行,作为初学者,恳求各位大大解决

Django服务端显示http 400错误,Invalid HTTP_HOST header

我用Python自带的HTTPHandler发送logging信息到服务器,代码如下 import logging ``` import logging.handlers logger = logging.getLogger('mylogger') http_handler = logging.handlers.HTTPHandler('localhost:8000', '/VideoParser/lYYDownloaderClientLog')#, method='POST' logger.addHandler(http_handler) logger.error('testing remote logging')在这里书写代码片 ``` 但是每次发送之后都会出现http 400,错误,并且还会显示Invalid HTTP_HOST header,如下 > Invalid HTTP_HOST header: 'localhost:8000,localhost'. The domain name provided i > s not valid according to RFC 1034/1035. > [03/Apr/2017 19:15:41] "GET /VideoParser/lYYDownloaderClientLog?filename=a.py&th > readName=MainThread&stack_info=None&processName=MainProcess&exc_text=None&create > d=1491218139.538086&levelname=ERROR&module=a&thread=3624&exc_info=None&relativeC > reated=112.00642585754395&levelno=40&pathname=C%3A%5CUsers%5Ci%5CDocuments%5CTen > cent+Files%5C2281570025%5CFileRecv%5Ca.py&msecs=538.0859375&msg=testing+remote+l > ogging&name=mylogger&args=%28%29&lineno=12&process=6700&funcName=%3Cmodule%3E HT > TP/1.1" 400 67823 我该如何修复问题? 相关代码 D:\BaiduYunDownload\编程\Python\django-test\LYYDownloaderServer\VideoParser\urls.py ``` from django.conf.urls import url from . import views app_name = 'VideoParser' urlpatterns = [ url(r'lYYDownloaderClientLog.+',views.lYYDownloaderClientLog, name='lYYDownloaderClientLog') ] ``` D:\BaiduYunDownload\编程\Python\django-test\LYYDownloaderServer\VideoParser\views.py ``` def lYYDownloaderClientLog(request): print('----666666666666---', request.GET)在这里书写代码片 ```

django项目 makemigrations时出现nodenotfounderror错误。

如题 makemigrations时出现 django.db.migrations.graph.NodeNotFoundError: Migration blog.0001_initial dependencies reference nonexistent parent node (u'auth', u'0007_alter_validators_add_error_messages')错误 求大家解答! 问题源文件: # -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-02-24 10:34 from __future__ import unicode_literals import blog.models from django.conf import settings import django.contrib.auth.models import django.core.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('tagging', '0001_initial'), ('auth', '0007_alter_validators_add_error_messages'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=30, unique=True, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.')], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('name', models.CharField(max_length=12)), ('avatar_path', models.ImageField(default='/static/image/avatar_default.jpg', upload_to='/avatar')), ], options={ 'abstract': False, 'verbose_name': 'user', 'verbose_name_plural': 'users', }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Carousel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('img', models.ImageField(upload_to='/carousel')), ('create_time', models.DateTimeField(auto_now_add=True)), ], options={ 'ordering': ['-create_time'], }, ), migrations.CreateModel( name='Catalogue', fields=[ ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ], ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('publish_Time', models.DateTimeField(auto_now_add=True)), ('ip_address', models.GenericIPAddressField()), ('content', models.CharField(max_length=200)), ('isDelete', models.BooleanField(default=False)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Editor', fields=[ ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('avaliable', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('publish_time', models.DateTimeField(auto_now_add=True)), ('modify_time', models.DateTimeField(auto_now_add=True)), ('content', models.TextField()), ('tag', blog.models.TagField_Mine(blank=True, max_length=255)), ('view_count', models.IntegerField(default=0, editable=False)), ('status', models.SmallIntegerField(choices=[(0, '\u8349\u7a3f'), (1, '\u53d1\u5e03'), (2, '\u5220\u9664')], default=0)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('catalogue', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Catalogue')), ('editor_choice', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Editor')), ], options={ 'ordering': ['-modify_time'], }, ), migrations.CreateModel( name='Repository', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('publish_time', models.DateTimeField(auto_now_add=True)), ('author', models.CharField(max_length=20)), ('content', models.TextField()), ('view_count', models.IntegerField(default=0, editable=False)), ('tag', models.ManyToManyField(blank=True, default='', to='tagging.Tag')), ], options={ 'ordering': ['-publish_time'], }, ), migrations.AddField( model_name='comment', name='post', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Post'), ), migrations.AddField( model_name='carousel', name='post', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Post'), ), migrations.AddField( model_name='user', name='editor_choice', field=models.ForeignKey(blank=True, default='tinyMCE', null=True, on_delete=django.db.models.deletion.CASCADE, to='blog.Editor'), ), migrations.AddField( model_name='user', name='groups', field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'), ), migrations.AddField( model_name='user', name='user_permissions', field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'), ), ]

<python从入门到实践>18章Django联系创建模型Pizzas和Topping时运行migrate时出现错误django.db.utils.OperationalError: no such table: pizzas_pizza

models.py ``` from django.db import models class Pizza(models.Model): name = models.CharField(max_length=5) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Topping(models.Model): pizza = models.ForeignKey(Pizza,on_delete=models.CASCADE) name = models.TextField date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'toppings' def __str__(self): return self.name[:20]+'...' ```

<python从入门到实践>19章书中只给topic设定了owner,但是entry没有出现了报错django.db.utils.OperationalError: no such column: learning_logs_entry.owner_id

我用改topic的方法改了new_entry,也没有行通。 views.py ``` from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic,Entry from .forms import TopicForm,EntryForm from django.contrib.auth.decorators import login_required def index(request): #学习笔记的主页 return render(request,'learning_logs/index.html') @login_required def topics(request): #显示所有的主题 topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics':topics} return render(request,'learning_logs/topics.html',context) @login_required def topic(request,topic_id): #显示单个主题及其所有的项目 topic = Topic.objects.filter(owner=request.user).get(id = topic_id) #确认请求的主题属于当前用户 if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic':topic,'entries':entries} return render(request,'learning_logs/topic.html',context) @login_required def new_topic(request): '''添加新主题''' if request.method != 'POST': #未提交数据 创建一个新表单 form = TopicForm() else: #POST提交的数据 对数据进行处理 form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form':form} return render(request, 'learning_logs/new_topic.html',context) @login_required def new_entry(request,topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic,'form':form} return render(request, 'learning_logs/new_entry.html',context) @login_required def edit_entry(request,entry_id): '''编辑现有的条目''' entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: #POST提交的数据,对数据进行处理 form = EntryForm(instance=entry,data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry':entry, 'topic':topic, 'form':form } return render(requ ``` models.py ``` from django.db import models from django.contrib.auth.models import User class Topic(models.Model): #用户学习主题 text = models.CharField(max_length= 200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): #返回模型的字符串表示 return self.text class Entry(models.Model): #学到的有关某个主题的具体知识 topic = models.ForeignKey(Topic,on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add= True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class meta: verbose_name_plural ='entries' def __str__(self): #返回模型的字符串表示 if len(self.text) >= 50: return self.text[:50] + '...' else: return self.text[:] ```

ztree引用Django后台数据无显示,求助!!

Django中,JS能获取到后台传过来的json数组,alert出来也能正确解析,直接把数据打印出来放到JS中也能用,但是用ztree引用就是不显示 ``` function getTree() { var tree = {}; $.ajax({ url: "/../json_test2", type: "get", contentType: "application/json", timeout: 30000, //超时时间:30秒 async: false, dataType: "json", success: function (data) { alert(data) //此处能显示 tree = data; }, error: function (data) { alert("bed") } }); return tree; } var zNodes = getTree(); //若把alert出来的数据直接粘贴到此处后ztree能正确显示。 alert(zNodes) //此处能显示 $(document).ready(function(){ $.fn.zTree.init($("#treeDemo"), setting, zNodes); }); ``` 感觉就差临门一脚,就像跟国足一样,怎么弄都弄不进去~求zhi'dao 数据库表 ![图片说明](https://img-ask.csdn.net/upload/201906/18/1560869954_408990.png) 后台 ``` def json_test2(request): book = workgroup.objects.all().values() print(book) data = list(book) print(data) data = json.dumps(data) print(data) return JsonResponse(data,safe=False) ```

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

删库了,我们一定要跑路吗?

在工作中,我们误删数据或者数据库,我们一定需要跑路吗?我看未必,程序员一定要学会自救,神不知鬼不觉的将数据找回。 在 mysql 数据库中,我们知道 binlog 日志记录了我们对数据库的所有操作,所以 binlog 日志就是我们自救的利器。 接下来就来开启程序员自救之路。 想要自救成功,binlog 这把利器一定要好,在自己之前,我们一定要确定我们有 binlog 这把利器,以下就是确保有 bi...

再不跳槽,应届毕业生拿的都比我多了!

跳槽几乎是每个人职业生涯的一部分,很多HR说“三年两跳”已经是一个跳槽频繁与否的阈值了,可为什么市面上有很多程序员不到一年就跳槽呢?他们不担心影响履历吗? PayScale之前发布的**《员工最短任期公司排行榜》中,两家码农大厂Amazon和Google**,以1年和1.1年的员工任期中位数分列第二、第四名。 PayScale:员工最短任期公司排行榜 意外的是,任期中位数极小的这两家公司,薪资...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

现代的 “Hello, World”,可不仅仅是几行代码而已

作者 |Charles R. Martin译者 | 弯月,责编 | 夕颜头图 |付费下载自视觉中国出品 | CSDN(ID:CSDNnews)新手...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐