【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+OpenCV计算机视觉

Python+OpenCV计算机视觉

<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创建项目时,urls.py报错:No module named 'index.urls'

django创建音乐网站项目时,urls.py写入代码后,pycharm一直报错: No module named 'index.urls' 用idle运行时候就报错: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. 创建过程中只修改了urls.py 和setting.py 文件 代码如下: [b]urls.py[/b] from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.views import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), path('ranking.html', include('ranking.urls')), path('play/', include('play.urls')), path('comment/', include('comment.urls')), path('search/', include('search.urls')), path('user/', include('user.urls')), ] [b]settings.py[/b] (部分代码) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'index', 'ranking', 'user', 'play', 'search', 'comment', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 使用中文 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'music.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'index/templates'), os.path.join(BASE_DIR, 'ranking/templates'), os.path.join(BASE_DIR, 'user/templates'), os.path.join(BASE_DIR, 'play/templates'), os.path.join(BASE_DIR, 'comment/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 = 'music.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'music_db', 'USER': 'root', 'PASSWORD': '1234', 'HOST': '127.0.0.1', 'POST': '3306', } } 请问这种情况该如何处理呢?求指点

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 关于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读取的图片)出了问题,请大神指教下,我这个接口想接收图片,应该怎么改? 万分感谢!!!

一筹莫展 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自带的数据库中新建立的数据表?

下面是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用户登录后回到主页,无法获取已登录状态

#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怎么使用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) } }) } }

在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刚入门,创建博客的时候出现这个错误,求解决

![图片说明](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), ) 照着网上教材做的 但是就是出不来啊 求大佬们帮帮

报错出现MultiValueDictKeyError at /account/user 'userid'是什么问题呢?

Django开发用户模块,需要进行用户登录时区分不同角色,却出现了这样的问题**_MultiValueDictKeyError at /account/user 'userid'**_ 不知道是什么原因造成的,查了很多文章也没有解决当前的问题,希望得到大家的帮助 具体代码如下: models.py ``` from django.db import models # Create your models here. from django.contrib.auth.models import Group from django.contrib.auth.models import User class User2(models.Model): id = models.AutoField(primary_key=True) userid = models.CharField(max_length=20) password = models.CharField(max_length=15) status = models.CharField(max_length=15,null=True) def __str__(self): # 在Python3中使用 def __str__(self): return self.userid def __str__(self): # 在Python3中使用 def __str__(self): return self.password def __str__(self): # 在Python3中使用 def __str__(self): return self.status ``` login.html ``` <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- CSS --> <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=PT+Sans:400,700'> <link rel="stylesheet" href="{% static 'css/reset.css' %}"> <link rel="stylesheet" href="{% static 'css/supersized.css' %}"> <link rel="stylesheet" href="{% static 'css/style1.css' %}"> <script src="{% static 'js/jquery-1.8.2.min.js' %}"></script> <script src="{% static 'js/supersized.3.2.7.min.js' %}"></script> <script src="{% static 'js/supersized-init.js' %}"></script> <script src="{% static 'js1/scripts.js' %}"></script> </head> <body> <div class="page-container"> <h1 style="color: #0b0d0c">欢迎您登录</h1> <form method="POST" action="{% url 'account:user' %}" onsubmit="return eg.regCheck();"> {% csrf_token %} <div class="logGet"> <input type="text" placeholder="Username" id="userid" name="userid" autofocus /> <input type="password" placeholder="Password" id="userpwd" name="password"/> <button type="submit">登录</button> </div> </form> </div> <script> var eg = {}; eg.$ = function(id){ return document.getElementById(id); }; eg.regCheck = function(){ var uid = eg.$("userid"); var upwd = eg.$("userpwd"); if(uid.value ==''){ alert('账号不能为空!'); return false; } if(upwd.value ==''){ alert('密码不能为空!请输入密码!!!'); return false; } return true; }; </script> </body> </html> ``` views.py ``` def user(request): # try: Userid = request.POST['userid'] Password = request.POST['password'] request.session["name"] =Userid # context={} # context['userid']=userid # request.session['msg']=context print(Userid) print(Password) # return render(request, 'index.html', {}) user = User2.objects.filter(userid=Userid, password=Password) print(user) if user: for users in user: if users.status == 'C': return render(request, 'project/index.html', {}) if users.status == 'T': return render(request, 'book/book_detail.html', {'user': user}) else: return render(request, 'Work1-1.html', {'msg': '用户名或密码不正确'}) # except: # return render(request, 'login.html', {'msg': None}) def enroll(request): return render(request, 'enroll.html', {}) def test(request): #user_name = request.POST.get("userid", None) #user_password = request.POST.get("password", None) #status = request.POST.get("status",None) user_name = request.POST['user_name'] user_password = request.POST['user_password'] status = request.POST['status'] ## user_name=request.POST.get("userid",None) ## user_password=request.POST.get("password",None) from account.models import User2 from account import models User2.objects.create(userid=user_name, password=user_password, status=status) info_list = models.User2.objects.all() return render(request, 'login.html', {"info_list": info_list}) ``` 希望能得到帮助,着急!

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使用@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/') ```

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报错:django.server:"GET /favicon.ico HTTP/1.1" 500 59,该如何解决?

搭建完HttpRunnerManager环境后进行接口的调试,运行用例时页面报错: A server error occurred. Please contact the administrator. ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565747464_929466.jpg) 返回用例页面收到提示: ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565747577_116158.jpg) 点击确定后页面依旧是500报错,和图一相同,刷新页面也无济于事 ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565747927_436972.jpg) dos命令窗口关于django服务的报错: ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565748112_123790.jpg) 分别查询了前台和后台的错误解决办法,发现前台错误和其他人的原因不同,后台django的错误实在搜不到详细的内容,本人也是初次接触这套框架,对django的报错没有头绪,希望有大佬帮忙分析一下原因所在,万分感谢。

求助 关于Django ,AttributeError:'Topic' object has no attribute 'owner'

python编程入门到实践第十九章中的问题 浏览器报错信息如下 ![图片说明](https://img-ask.csdn.net/upload/201904/04/1554356911_216497.png) **关于我的views.py 的代码如下** ``` from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm # Create your views here. def index(request): ''' 学习笔记的主页 :return: ''' return render(request,'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def new_topic(request): '''添加新主题''' if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form':form} return render(request,'learning_logs/new_topic.html',context) def edit_entry(request, entry_id): """Edit an existing entry.""" entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise Http404 if request.method != 'POST': # Initial request; pre-fill form with the current entry. form = EntryForm(instance=entry) else: # POST data submitted; process data. 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(request, 'learning_logs/edit_entry.html', context) def topic(request, topic_id): """Show a single topic, and all its entries.""" topic = Topic.objects.get(id = topic_id) # Make sure the topic belongs to the current user. 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) def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) ```

问个有关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 提交表单后 函数解析参数报错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)

django怎样在两个VIEWS之间传递数据

``` from django.shortcuts import render from django.views.generic.base import View from datetime import datetime from django.http import HttpResponse from .models import Cschat from tools.cschat_aliyun import AliyunCschat from django.views.decorators.csrf import csrf_exempt import json,time class CschatView(View): def get(self,request): return render(request,'cschat.html') def post(self,request): content = request.POST.get("content","") result = AliyunCschat(content).hash_result() time.sleep(2) with open('aliyun.json','rb') as f: d = json.loads(f.read()) return render(request,'cschat_result.html',{ "contents":d }) class AliyunCallbackView(View): @csrf_exempt def post(self,request): postbody = request.body with open('aliyun.json','wb') as f: f.write(postbody) return HttpResponse(str(postbody)) def get(self,request): return render(request,'aliyun_callback.html',{ "text":"没有结果" }) ``` 应用场景:给阿里云的接口发送POST请求后 阿里云不会直接返回数据 而是把数据返回到另外一个接口(class AliyunCallbackView(View)这个对应的url),我需要在给阿里云发送POST请求后从另一个接口读取阿里云返回的POST数据。 代码中 ``` result = AliyunCschat(content).hash_result() ``` 这一行执行是给阿里云的接口发送POST请求 我现在的写法很有问题,因为没有好的解决办法。 我的做法是把AliyunCallbackView接收到的阿里云POST返回的数据写到aliyun.json这个文件里面,然后等待2秒钟后读取aliyun.json里面的内容,再把结果返回给前端。这样写的问题很多,如果AliyunCallbackView在一秒内接收到多个返回数据,那后面的执行内容就全变了。可以把阿里云POST返回的数据写入数据库,然后使用时间戳查询数据库返回对应的值。这种办法虽然可行但是感觉太麻烦了,请问有什么更好的解决办法?

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c#跨线程停止timer c#批量写入sql数据库 c# 自动安装浏览器 c#语言基础考试题 c# 偏移量打印是什么 c# 绘制曲线图 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行
立即提问