【django】关于request.POST[]和request.POST.get()的问题 5C

自己写了个django网站,今天用postman和python requests.post分别进行了登录接口测试,结果发现postman一直报错MultiValueDictKeyError at /login而requests.post是正常。然后我修改了uname和upwd的参数,发现request.POST.get()参数正常,request.POST[]会报错。这个是为什么呢?
代码如下:

uname = request.POST.get('uname')
upwd = request.POST['upwd']

同时想请教一下postman和requests工作原理上的区别,谢谢!

ttphoon
ttphoon 我知道post[]和pst.get()的基本区别一个是没获取到会报错,一个是不会报错。
大约一年之前 回复

2个回答

ttphoon
ttphoon 我问的是request.POST.get()和request.POST[]的区别,不是requests.post和get,谢谢
大约一年之前 回复

request.POST['upwd'] 错误,是因为它不是list或者dict类型,或者他们的子类型,所以你使用这个方法报错
request.POST.get('uname') 成功,是因为request.POST父类实现了get这个方法
图片说明
postman 谷歌一款模拟网络请求工具
requests 你自己开发的模拟网络请求脚本
本质上都是模拟网络请求,但是postman可直接使用chrome上该域名cookies

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
<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[:] ```

一筹莫展 Django显示 MultiValueDictKeyError at /myDetector/

我试过很多办法了 都没法解决 哥哥们帮忙看看 ![图片说明](https://img-ask.csdn.net/upload/201905/17/1558060013_805939.png) 代码见下 mainDealer()函数 def mainDealer(request): # post = request.POST.items() print("rawTarget =", request.POST["rawTarget"]) target = reverse("myDetector:tempTest") + '?' argName = request.POST["paramName"] argPath = argName.split("?")[0] argName = argName.split("?")[1] # dealt by model lmModel = Judger.readModelFromFile(name=Judger.getFileName( argName, "2018119", "lm"), obj_hook=Judger.lmFromFile) cmModel = Judger.readModelFromFile(name=Judger.getFileName( argName, "2018119", "cm"), obj_hook=Judger.cmFromFile) lmPredictRst = lmModel.predict( samples=[ request.POST["paramValue"]], realRst=[]) cmPredictRst = cmModel.predict( samples=[ request.POST["paramValue"]], realRst=[]) judgeRst = {"lm": lmPredictRst[0], "cm": cmPredictRst[0]} if not judgeRst["lm"]: addNewMarkedValue(argName, request.POST["paramValue"], "lm", argPath) if not judgeRst["cm"]: addNewMarkedValue(argName, request.POST["paramValue"], "cm", argPath) # request.session["argName"] = argName request.session["argPath"] = argPath request.session["argValue"] = request.POST["paramValue"] request.session["ip"] = request.META['REMOTE_ADDR'] request.session["judgeRst"] = judgeRst request.session["rawTarget"] = request.POST["rawTarget"] target = target[:-1] return HttpResponseRedirect(target) urlpatterns = [ url(r'^$', views.mainDealer, name='mainDealer'), url(r'^tempTest/$', views.tempTest, name='tempTest'), url(r'^showModels/$', views.showModels, name='showModels'), url(r'^delOneMarkedValue/$', views.dealMv), url(r'^reTrain/$', views.reTrain), url(r'^machineClassificationRst/$', views.readMLClassificationRst), url(r'^dealMLClassificationRst/$', views.dealMLClassificationRst), url(r'^xssIntoDb/$', views.xssIntoDb, name='xssIntoDb'), url(r'^xssDetectorPage/$', views.xssDetectorPage, name='xssDetectorPage'), url(r'^readXss/$', views.readXss, name='readXss'), url(r'^xssStateChange/$', views.xssStateChange, name='xssStateChange'), ] 试了request.POST.get() 没有用 依旧报错

django刚入门,创建博客的时候出现这个错误,求解决

![图片说明](https://img-ask.csdn.net/upload/201904/01/1554112752_11759.png) ![图片说明](https://img-ask.csdn.net/upload/201904/01/1554112854_18340.png) 具体代码如下 html文件应该没错 views.py: from django.shortcuts import render # Create your views here. from django.template import loader,Context from django.http import HttpResponse from blog.models import BlogPost def archive(request): posts = BlogPost.objects.all(); #@UndefinedVariable t = loader.get_template('archive.html') c = Context({'posts': posts}) return HttpResponse(t.render(c)) models.py: from django.db import models from django.contrib import admin # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length = 150) content = models.TextField() timestamp = models.DateTimeField() class BlogPostAdmin(admin.ModelAdmin): list_display = ('title', 'content', 'timestamp') admin.site.register(BlogPost, BlogPostAdmin) settings.py: TEMPLATE_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', 'blog' ) MIDDLEWARE_CLASSES = ( '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', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'wangxiran.urls' WSGI_APPLICATION = 'wangxiran.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'wangxiran', 'USER':'root', 'PASSWORD':'Aa123456', 'HOST':'127.0.0.1', 'POST':'3306', } } # Internationalization # https://docs.djangoproject.com/en/dev/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/dev/howto/static-files/ STATIC_URL = '/static/' urls.py: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from blog.views import archive urlpatterns = patterns('', # Examples: # url(r'^$', 'wangxiran.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^blog/', archive), ) 照着网上教材做的 但是就是出不来啊 求大佬们帮帮

问个有关django+heroku的问题

``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku 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/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( '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', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' 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', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.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.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) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} 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(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} 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 not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```

django +jquery+ ajax get提交报错,post提交就可以

``` 模板:(index.html) “ <html> <body> <p>请输入两个数字</p> <form action="/index" method="get"> a: <input type="text" id="a" name="a"> <br> b: <input type="text" id="b" name="b"> <br> <p>result: <span id='result'></span></p> <button type="button" id='sum'>提交</button> </form> <!---<script type="text/javascript" src="/static/jquery-3.3.1.min.js"></script>---> <script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#sum").click(function(){ var a = $("#a").val(); var b = $("#b").val(); $.get("/index",{'a':a,'b':b}, function(ret){ $('#result').html(ret.result) }) }); }); </script> </body> </html>” ``` ``` **url 代码:** urlpatterns = [ url(r'testDb' , testDb), url(r'query' , Query), url(r'formdemo' , searchtest.search), url(r'^seachDemo' , searchtest.search_form), url(r'^index' , view.loginIndex), ] ``` ``` python 代码view.py: def loginIndex(request): if(request.method == 'GET'): a = int(request.GET.get('a')) b = int(request.GET.get('b')) return_json = {'result': a + b} return HttpResponse(json.dumps(return_json), content_type='application/json') return render(request,"index.html") ``` 报错: TypeError at /index int() argument must be a string, a bytes-like object or a number, not 'NoneType' Request Method: GET Request URL: http://127.0.0.1:8000/index Django Version: 2.0.3 Exception Type: TypeError Exception Value: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Exception Location: D:\PythonDemo\PythonDemo\view.py in loginIndex, line 12 Python Executable: D:\PythonDemo\venv\Scripts\python.exe Python Version: 3.6.3 Python Path: ['D:\\PythonDemo', 'D:\\PythonDemo', 'D:\\PythonDemo\\venv\\Scripts\\python36.zip', 'X:\\python\\DLLs', 'X:\\python\\lib', 'X:\\python', 'D:\\PythonDemo\\venv', 'D:\\PythonDemo\\venv\\lib\\site-packages', 'D:\\PythonDemo\\venv\\lib\\site-packages\\setuptools-28.8.0-py3.6.egg', 'D:\\PythonDemo\\venv\\lib\\site-packages\\pip-9.0.1-py3.6.egg', 'X:\\PyCharm\\PyCharm 2017.3.4\\helpers\\pycharm_matplotlib_backend'] Server time: Sun, 18 Mar 2018 07:35:40 +0000 这个报错也让我很懵逼,我把提交方式,和ajax方法改成post,就没有这个报错,程序可以正常运行

Django 在后台管理页面中实现添加用户报错:RuntimeError at /admin/booktest/bookinfo/add/ generator raised StopIteration

#报错问题:(WIN10+python3.7+django1.8.2) ```python Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/booktest/bookinfo/add/ Django Version: 1.8.2 Python Version: 3.7.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'booktest') Installed Middleware: ('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', 'django.middleware.security.SecurityMiddleware') Traceback: File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\core\handlers\base.py" in get_response 125. response = middleware_method(request, callback, callback_args, callback_kwargs) File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\middleware\csrf.py" in process_view 174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\core\handlers\wsgi.py" in _get_post 137. self._load_post_and_files() File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\http\request.py" in _load_post_and_files 260. self._post, self._files = self.parse_file_upload(self.META, data) File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\http\request.py" in parse_file_upload 225. return parser.parse() File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\http\multipartparser.py" in parse 149. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\http\multipartparser.py" in __iter__ 628. yield parse_boundary_stream(sub_stream, 1024) File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\http\multipartparser.py" in parse_boundary_stream 567. chunk = stream.read(max_header_size) File "A:\MyApply\Soft\CodeApply\Python\virtualenv\env\lib\site-packages\django\http\multipartparser.py" in read 337. out = b''.join(parts()) Exception Type: RuntimeError at /admin/booktest/bookinfo/add/ Exception Value: generator raised StopIteration ```

django用户登录后回到主页,无法获取已登录状态

#views.py定义的视图 from django.contrib.auth import authenticate,login def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect('/homepage/') #回到主页 else: #返回账户invalid的消息 else: #返回login页面 ``` #在主页的显示html文件中,使用is_authenticated先判断了用户是否登录了,如下: {% if user.is_authenticated %} <h5>>Hello {{ user.username }} !</h5> {%else%} <h5>Weclome !</h5> {%endif%} 问题是:在user_login视图里,使用login后,能正常返回到主页,说明登录成功,可是在主页中,使用is_authenticated判定后,总是为False,总是无法显示已登录的状态。 环境:Python 2.7,Django:1.10

求解!!!!!请问怎样调用在django自带的数据库中新建立的数据表?

下面是view.py 的一部分代码,我想把用户输入的数据存到“书籍信息表”,但是 不知道哪里出问题了,django自带了sqlite3数据库,要使用在sqlite3里新建立的表要不要先连接,求解!!! 数据表分别有:用户信息表、书籍信息表、管理员信息表 from django.shortcuts import render, redirect from .models import 用户信息表, 书籍信息表, 管理员信息表 from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.contrib import auth def sell(request): if request.method == ‘GET’: return render(request, ‘我要卖.html’) elif request.method == ‘POST’: 书名 = request.POST【‘书名’】 作者 = request.POST【‘作者’】 try: ISDN码 = request.POST【‘ISDN’】 出版社 = request.POST【‘出版社’】 卖家联系方式 = request.POST【‘电话’】 product = 书籍信息表() product.book_name = 书名 product.author = 作者 product.isdn码 = ISDN码 product.publisher = 出版社 product.Tel = 卖家联系方式 product.save() return redirect(‘主页’) except Exception as err: return render(redirect, ‘我要卖.html’, {‘错误’: ‘请填写完整信息!’})

萌新求救!Django 做出来的网页404异常

我才学习制作了一个小的网页(此时路径是:"http://127.0.0.1:8000/index/") ![图片说明](https://img-ask.csdn.net/upload/201907/11/1562841009_226257.png) 主要目的是向mysql数据库传输一个图片一个文件已经图片的图片名字,在选择完文件点提交后,就变成"http://127.0.0.1:8000/views/" 了,并且报404错误,![图片说明](https://img-ask.csdn.net/upload/201907/11/1562840959_604996.png) 如何才能返回一个正常的网页,比如:index2.html。然后图片,文件也能上传到mysql。 views.py ``` from django.shortcuts import render from myapp import models from myapp.forms import PersonForm # Create your views here. def index(request): if request.method == 'POST': form =PersonForm(request.POST, request.FILES) pic1 = form.cleaned_data['pic1'] name1 = form.cleaned_data['name1'] label1 = form.cleaned_data['label1'] models.db_boxs.objects.create(pic=pic1,name=name1,label=label1) return HttpResponse('regist success') if request.method == 'GET': return render(request,'index.html',{'form':PersonForm()}) return render(request,'index.html',{'form':PersonForm()}) ``` url.py ``` from django.contrib import admin from django.urls import path from myapp import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index) ] ```

django 关于post请求长度限制问题

我用django框架做了个接口,接受一个图片,处理图片,返回结果。 调用接口的测试代码是这样的: ``` img = cv2.imread('C:\\Users\\51530\\Desktop\\openFace\\43.png',cv2.IMREAD_GRAYSCALE) parms = { 'img' : img } # test = { # 'name':'yuhaibo' # } re=requests.post('http://127.0.0.1:8001/identifyUser/', data = parms) # re=requests.post('http://127.0.0.1:8001/test/', data = test) print(re.text) ``` 运行的结果就是提示我 TooManyFieldsSent at /identifyUser/ The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. 我加注释的部分运行时没问题的,就是传图片(用opencv读取的图片)出了问题,请大神指教下,我这个接口想接收图片,应该怎么改? 万分感谢!!!

在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表单提交问题,后端接收不到数据

``` {% extends 'blog_base.html' %} {% load staticfiles %} {% block main %} <h1 class="page-title">Contact</h1> <article class="post"> <div class="entry-content clearfix"> <form action="{% url 'contacts:post_contact'%}" method="post" class="contact-form"> <div class="row"> <div class="col-md-6 col-md-offset-3"> {% csrf_token %} <input type="text" name="name" value="{{form.name}}" placeholder="Name" required> <input type="email" name="email" value="{{form.email}}" placeholder="Email" required> <input type="text" name="subject" value="{{form.subject}}" placeholder="Subject" required> <textarea name="text" value="{{form.text}}" placeholder="Your Message" required></textarea> <input type="submit" value="Submit" class="btn-send btn-5 btn-5b ion-ios-paperplane" /> </div> </div> <!-- row --> </form> </div> </article> {% endblock main %} ``` 这是前段静态页面,后端是 ``` def post_contact(request): # HTTP 请求有 get 和 post 两种,一般用户通过表单提交数据都是通过 post 请求, # 因此只有当用户的请求为 post 时才需要处理表单数据。 if request.method == 'POST': # 用户提交的数据存在 request.POST 中,这是一个类字典对象。 # 我们利用这些数据构造了 CommentForm 的实例,这样 Django 的表单就生成了。 form = ContactForm(request.POST) if form.is_valid(): contact = form.save(commit=False) contact.save() # 然后重定向到 get_absolute_url 方法返回的 URL。 return render(request, 'contacts/contact.html') # 不是 post 请求,说明用户没有提交数据,重定向到文章详情页。 return render(request, 'contacts/contact.html', {'form': form}) ``` 如何修改才能获取到前段的提交的值,并存入库中,测试了好久,dug显示页面提交成功 200,但是后端断点并未访问,感谢各位大神帮助!

Django在本地window下测试没问题,上传到Ubuntu或者centos下报拒绝访问403错误,请问如何解决?谢谢!

1.本人刚开始学习Django,在Windows下参照教程和网络资料东拼西凑,写了一个连接内网服务器查询身份证号码信息的网页,在window7下python3.8,Django3.0.5运行正常。 2.由于Django部署需要Apache和uwsgi,需要Linux环境,就尝试部署到centos7,但是启动Django后报HTTP Error 403: Forbidden错误。 ``` python manage.py runserver 0.0.0.0:8000 ``` ``` setting.py中ALLOWED_HOSTS = ['*']或者服务器ip都不行 ``` 3.网上查了很久,参照了[Apache 部署 Django 项目过程记录与问题总结](https://blog.csdn.net/Ahri_J/article/details/71703030 ""),也关闭了防火墙,换了Ubuntu,同样是python3.8,Django3.0.5环境下,依然报同样的HTTP Error 403: Forbidden错误。参照[Python 3.x 中"HTTP Error 403: Forbidden"问题的解决方案](https://blog.csdn.net/eric_sunah/article/details/11301873 ""),也未解决问题。 求教高手,万分感谢! 报错图片: ![图片说明](https://img-ask.csdn.net/upload/202004/06/1586163086_341797.jpg) Traceback代码 ``` Environment: Request Method: POST Request URL: http://23.84.2.142:8000/search Django Version: 3.0.5 Python Version: 3.8.0 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/mysite/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/mysite/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/mysite/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mysite/mysite/search.py", line 127, in result datas = get_GXPT(message) File "/home/mysite/mysite/search.py", line 82, in get_GXPT content_ryxx = urllib.request.urlopen(req1).read() File "/usr/lib/python3.8/urllib/request.py", line 222, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.8/urllib/request.py", line 531, in open response = meth(req, response) File "/usr/lib/python3.8/urllib/request.py", line 640, in http_response response = self.parent.error( File "/usr/lib/python3.8/urllib/request.py", line 569, in error return self._call_chain(*args) File "/usr/lib/python3.8/urllib/request.py", line 502, in _call_chain result = func(*args) File "/usr/lib/python3.8/urllib/request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) Exception Type: HTTPError at /search Exception Value: HTTP Error 403: Forbidden ``` ```

django使用@login_required时出现重定向次数过多问题是怎么回事

报错如下: ![图片说明](https://img-ask.csdn.net/upload/201908/23/1566554722_363027.png) 目录如下: ![图片说明](https://img-ask.csdn.net/upload/201908/23/1566554300_221679.png) index的views.py: ![图片说明](https://img-ask.csdn.net/upload/201908/23/1566554666_927148.png) login的views.py: ``` from django.shortcuts import render, redirect from .forms import * # Create your views here. def login_views(request): if request.method == 'GET': # 获取请求源地址,如果没有的话则获取'/' url = request.META.get('HTTP_REFERER', '/') # print("请求源地址:"+url) # 判断session中是否有uid和uname if 'uid' in request.session and 'uname' in request.session: return redirect(url) else: # 判断cookie中是否有uid和uname, if 'uid' in request.COOKIES and 'uname' in request.COOKIES: # 如果有的话则取出来并保存进session,再回首页 uid = request.COOKIES['uid'] uname = request.COOKIES['uname'] request.session['uid'] = uid request.session['uname'] = uname return redirect(url) else: form = LoginForm() # 构建响应对象,并将url保存进cookies resp = render(request, 'login.html', locals()) resp.set_cookie('url', url) return resp else: # post请求 # 获取请求源地址 url = request.META.get('HTTP_REFERER', '/') # 接收uname和upwd判断是否登录成功 uname = request.POST['uname'] upwd = request.POST['upwd'] user_name = Users.objects.filter(uname=uname) users = Users.objects.filter(uname=uname, upwd=upwd) # 如果成功继续向下执行,否则回到登录页 if users: # 登录成功,将id和uname保存进session id = users[0].id request.session['uid'] = id request.session['uname'] = uname # 如果有记住密码则将数据保存进cookies # 先从cookies中将url的值获取出来 url = request.COOKIES.get('url', '/') resp = redirect(url) # 如果url存在于cookies中的话,则将url从cookies中删除出去 if 'url' in request.COOKIES: resp.delete_cookie('url') if 'isSave' in request.POST: expires = 60 * 60 * 24 * 365 resp.set_cookie('uid', id, expires) resp.set_cookie('uname', uname, expires) return resp else: # 登录失败,回到登录页面 message = '登录失败!' return redirect('/login/') ```

问个有关python+django+heroku的问题

``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku 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/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( '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', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' 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', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.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.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) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} 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(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} 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 not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```

Django ajax无法调用后台方法

![图片说明](https://img-ask.csdn.net/upload/202004/08/1586339472_731380.png) 事件触发后无法调用ans_ajax方法,没有与视图函数连接 (不是因为type:psot这个原因) 视图函数代码如下: ``` def ans_ajax(request): text = request.POST.get('text') pro_id = request.POST.get('pro_id') user_name = request.session.get('user_name', default='') num = models.Ans.objects.count() + 1 models.Ans.objects.create(ans_id=num,ans_content=text,to_pro_id=pro_id,user_name=user_name) return render(request, 'homepage.html') ``` 求大佬帮忙解决

django怎么使用ajax,为什么我老是报404,小白求赐教

这是views里面的代码, def get_signal(request): if request.method == 'POST': print(request.method) msg_ids = request.POST.get('ids') print(msg_ids) res = {'aa': ' aa', 'bb': 'bb'} return HttpResponse(json.dumps(res), content_type='application/json') 这是urls里面的代码 from django.contrib import admin from django.urls import path from bokehTestApp import views as view urlpatterns = [ path('admin/', admin.site.urls), path('getSignal', view.get_signal) ] 这里是html里面的代码 var data = {'ids': id_data} function getSignal() { if(id_data.length > 0){ $.ajax({ "url": '/getSignal/', type: "POST", data: data, datatype: "json", success: function (res) { alert(res.data) } }) } }

django如何在用户登录后返回到原来来页面,并保持登陆状态

各位朋友们好,现在用django做一个用户登录页面,希望能够在用户登录后返回到原来来页面,并保持登陆状态,网上找到了下面这个方法 ``` def login_user(request): if request.method == 'GET': #记住来源的url,如果没有则设置为首页('/') request.session['login_from'] = request.META.get('HTTP_REFERER', '/') #TODO:显示登陆页面,blablabla if request.method == 'POST': #TODO: 用户登录操作,blablabla #重定向到来源的url return HttpResponseRedirect(request.session['login_from']) ``` 这个方法有一个问题就是,虽然通过重定向返回到原来登陆的页面,但是仍然显示未登陆的状态,我本来想传一个request.user 作为参数传递给展示页面的,但是HttpResponseRedirect不能传递参数,希望朋友们能够指点一下,万分感谢了。

django 提交表单后 函数解析参数报错TypeError: not nonetype

这是views里的代码 ``` from django.http import HttpResponse from django.shortcuts import render from .models import Item # Create your views here. def get_html(req): return render(req,"item.html") def create_item(req): #解析参数 params = req.POST name = params.get("i_name") barcode = params.get("i_barcode") cate_id = int(params.get("cate_id")) #创建数据 item = Item.objects.create( name = name, barcode = barcode, category_id=cate_id ) return HttpResponse("创建成功啦{}".format(item.name)) ``` 这是models的代码 ``` from django.db import models # Create your models here. class Category(models.Model): name = models.CharField( max_length=30, verbose_name="分类名", db_column="cate_name" #改数据表字段的名字 ) cate_num = models.CharField( max_length=20, null=True, verbose_name="分类的编号" ) create_time = models.DateTimeField( auto_now_add=True, verbose_name="创建时间" ) update_time = models.DateTimeField( auto_now=True, verbose_name="修改时间" ) class Meta: # 改数据表的名字 db_table = "category" # PEP8 class Item(models.Model): name = models.CharField( max_length=40, verbose_name="商品名字" ) barcode = models.CharField( max_length=13, verbose_name="条码", null=True ) category = models.ForeignKey( Category, db_index=True ) ``` ![图片说明](https://img-ask.csdn.net/upload/201903/05/1551792138_370806.png)![图片说明](https://img-ask.csdn.net/upload/201903/05/1551792151_50008.png)

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

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

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

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

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

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

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

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

将一个接口响应时间从2s优化到 200ms以内的一个案例

一、背景 在开发联调阶段发现一个接口的响应时间特别长,经常超时,囧… 本文讲讲是如何定位到性能瓶颈以及修改的思路,将该接口从 2 s 左右优化到 200ms 以内 。 二、步骤 2.1 定位 定位性能瓶颈有两个思路,一个是通过工具去监控,一个是通过经验去猜想。 2.1.1 工具监控 就工具而言,推荐使用 arthas ,用到的是 trace 命令 具体安装步骤很简单,大家自行研究。 我的使用步骤是...

学历低,无法胜任工作,大佬告诉你应该怎么做

微信上收到一位读者小涛的留言,大致的意思是自己只有高中学历,经过培训后找到了一份工作,但很难胜任,考虑要不要辞职找一份他能力可以胜任的实习工作。下面是他留言的一部分内容: 二哥,我是 2016 年高中毕业的,考上了大学但没去成,主要是因为当时家里经济条件不太允许。 打工了三年后想学一门技术,就去培训了。培训的学校比较垃圾,现在非常后悔没去正规一点的机构培训。 去年 11 月份来北京找到了一份工...

JVM内存结构和Java内存模型别再傻傻分不清了

JVM内存结构和Java内存模型都是面试的热点问题,名字看感觉都差不多,网上有些博客也都把这两个概念混着用,实际上他们之间差别还是挺大的。 通俗点说,JVM内存结构是与JVM的内部存储结构相关,而Java内存模型是与多线程编程相关,本文针对这两个总是被混用的概念展开讲解。 JVM内存结构 JVM构成 说到JVM内存结构,就不会只是说内存结构的5个分区,而是会延展到整个JVM相关的问题,所以先了解下

和黑客斗争的 6 天!

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

Google 与微软的浏览器之争

浏览器再现“神仙打架”。整理 | 屠敏头图 | CSDN 下载自东方 IC出品 | CSDN(ID:CSDNnews)从 IE 到 Chrome,再从 Chrome 到 Edge,微软与...

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

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

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

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

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

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

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

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

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

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

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

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

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

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

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

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

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

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

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

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

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

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

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

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

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

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

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

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

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

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

立即提问