Python2.7 + Django 1.11

princesshan 2017-09-29 03:23:09
运行网上一个例子,怎么也同步不了。请高人指点一下。

工程名mysite, app name 是blog

mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
]

mysite 目录与blog目录同级
blog/urls.py
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$', views.archive),
url(r'^create/', views.create),
]


blog/templates/archive.html

<!-- archive.html -->
<!-- archive.html -->
<form action="/blog/views/create/" method="post">
Title:
<input type=text name=title><br>
Body:
<textarea name=body rows=3 cols=60></textarea><br>
<input type=submit>
</form>
<hr>


{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.timestamp }}</p>
<p>{{ post.body }}</p>
<hr>
{% endfor %}


blog/models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

class BlogPost(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
timestamp = models.DateTimeField()

class Meta:
ordering = ('-timestamp',)

# Create your models here.

blog/views.py


# -*- coding: utf-8 -*-
# code for django 1.11
from __future__ import unicode_literals

from django.shortcuts import render

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader, Context
from blog.models import BlogPost

# Create your views here.
from datetime import datetime
from django.shortcuts import render_to_response
from blog.models import BlogPost


def archive(request):

posts = BlogPost.objects.all()[:10]

return render_to_response('archive.html', {'posts': posts})



def create(request):
if request.method == 'POST':
BlogPost(
title=request.POST.get('title'),
body=request.POST.get('body'),
timestamp=datetime.now(),
).save()
return HttpResponseRedirect('/blog/')



运行总是报错:


Page not found (404)
Request Method: POST
Request URL: http://localhost:8080/blog/views/create/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^blog/ ^$
^blog/ ^create/
^admin/
The current path, blog/views/create/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.




...全文
325 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
怒目金刚 2017-10-11
  • 打赏
  • 举报
回复
我用的是python3.6 + Django 1.10,也遇到了这个问题,现在解决了。 参考的是这一篇文章:http://www.cnblogs.com/Rocky_/p/6140362.html,还有2篇官方文档:https://docs.djangoproject.com/en/1.11/ref/csrf/、https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#django.shortcuts.render。参考的文章和官方文档中都提到了,不推荐使用render_to_response方法了,而应该使用render方法。 所以,你应该把archive()视图函数的return 改为:return render(request, 'archive.html', {'posts': posts}),从django.shortcuts中导入的方法也不是render_to_response,而是render。 改为之后记得先刷新页面再重新提交,否则没有效果。
weixin_37408584 2017-10-06
  • 打赏
  • 举报
回复
引用 3 楼 xpresslink 的回复:
把反跨站攻击中间件停用就可以了 改一下settings.py 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', ]
除了楼上这样处理外,在settings.py中不停用'django.middleware.csrf.CsrfViewMiddleware'这个中间件情况下,在html的</form>标签前中加入{% csrf_token %},也可以实现反跨站攻击。
混沌鳄鱼 2017-09-29
  • 打赏
  • 举报
回复
把反跨站攻击中间件停用就可以了 改一下settings.py 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', ]
princesshan 2017-09-29
  • 打赏
  • 举报
回复
@xpresslink 按照你说的内容,确实提示的错误不一样了, 但是出现了下面的错误。 Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. 我修改了模板,模板是这样的。 <!-- archive.html --> <!-- archive.html --> <form action="create/" method="post">{% csrf_token %} Title: <input type=text name=title><br> Body: <textarea name=body rows=3 cols=60></textarea><br> <input type=submit> </form> <hr> {% for post in posts %} <h2>{{ post.title }}</h2> <p>{{ post.timestamp }}</p> <p>{{ post.body }}</p> <hr> {% endfor %} mysite/settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%n9%&%yzg#)#+^hnc*2_ng%dqur%^b#4&ox@xm7ji0z^_7blvs' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.mysite.db'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' 请帮忙看一下是什么问题,可以吗?谢谢。
混沌鳄鱼 2017-09-29
  • 打赏
  • 举报
回复
你改一下blog/templates/archive.html文件中form的action 直接写create/就行了 <!-- archive.html --> <!-- archive.html --> <form action="create/" method="post"> 你试一下,不行再把 mysite/settings.py 文件内容贴上了.

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧