小编Ala*_*air的帖子

在引擎盖下,为用户创建子类和创建一对一字段之间的区别是什么?

我想在我的系统中实现用户.我知道Django已经有了一个身份验证系统,我一直在阅读文档.但我不知道它们之间的区别

from django.contrib.auth.models import User 
class Profile(User):
    # others fields
Run Code Online (Sandbox Code Playgroud)

from django.contrib.auth.models import User 
class Profile(models.Model):
    user = models.OneToOneField(User)
    # others fields 
Run Code Online (Sandbox Code Playgroud)

我不想知道为什么要使用这一个或另一个,但是在引擎盖下会发生什么.有什么不同?

python django

5
推荐指数
1
解决办法
184
查看次数

Django API Post方法返回403错误

我正在尝试设置Django API(POST API端点).我希望有相同的URL路径指向同一个处理不同的函数,因为它是POST或GET.因此,我使用了这样的方法

def handle_post(request):

    dict = {}
    dict['email'] = "test"

    if request.method == "POST":
        return HttpResponse(json.dumps(dict), content_type="application/json")
Run Code Online (Sandbox Code Playgroud)

在url.py中,我有以下代码

router = routers.DefaultRouter()
router.register(r'notes', UsernotesViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^admin/', include(admin_site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^example/postrequest', handle_post),
)
Run Code Online (Sandbox Code Playgroud)

但是当我在URL http://127.0.0.1:8000/example/postrequest?requestid=abc&starthour=10上执行POST时,我无法完成这项工作 .我没有发布任何内容,只是在httpclient上将方法从GET更改为POST以尝试此API.如果我没有将任何内容发布到URL,这样可以吗?

我收到403错误,如下所示:

禁止(403)
CSRF验证失败.请求中止.
您看到此消息是因为此站点在提交表单时需要CSRF cookie.出于安全原因,需要此cookie,以确保您的浏览器不会被第三方劫持.如果您已将浏览器配置为禁用cookie,请重新启用它们,至少对于此站点或"同源"请求.

感谢任何帮助.

python django http-post http-status-code-403

5
推荐指数
1
解决办法
7370
查看次数

Django 完整性错误 1452,无法添加或更新子行:外键约束失败

模型.py:

from django.db import models

class Line(models.Model):
  text = models.CharField(primary_key=True, max_length=255)

class Line2 (models.Model):
  text_line = models.ForeignKey ("Line", primary_key = True)
Run Code Online (Sandbox Code Playgroud)

视图.py:

from django.core.context_processors import csrf
from django.shortcuts import render
import datetime
from models import Line, Line2

def test_page (request):
  if 'uid' in request.POST:
    user_id = request.POST['uid']
    line_query = Line.objects.get (text = user_id)
    new_entry = Line2 (text_line_id = line_query)
    new_entry.save()
    return render(request, "templateFiles/testPage1.html", {"page_result":"Data Entered"});
  else:
    return render(request, "templateFiles/testPage1.html")
Run Code Online (Sandbox Code Playgroud)

模板:

<div id = "header">
  {{ page_result }}
  <form action="http://127.0.0.1:8000/test_page/" method …
Run Code Online (Sandbox Code Playgroud)

python mysql django

5
推荐指数
1
解决办法
1万
查看次数

Django 模板扩展了错误的模板

我的项目中有多个应用程序:

  • 应用程序1/
    • 模板/
      • 基本.html
      • 一些_模板.html
  • 应用2/
    • 模板/
      • 基本.html
      • 概述/
        • 索引.html

app2/templates/overview.index.html 有以下代码:

{% extends 'base.html' %}
Run Code Online (Sandbox Code Playgroud)

所以应该延长app2/templates/base.html

但实际上它延伸了app1/templates/base.html!为什么以及如何解决它?

django django-templates

5
推荐指数
1
解决办法
1457
查看次数

django.db.utils.OperationalError:“ []”附近:语法错误

使用makemigrations命令后,出现此错误,我尝试为此注释不同的列,但无法正常工作

    C:\Users\Rushabh\Desktop\project\MyPrj>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, paper, sessions
Running migrations:
  Applying paper.0014_auto_20170405_1549...Traceback (most recent call last):
  File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
    return Database.Cursor.execute(self, query)
sqlite3.OperationalError: near "[]": syntax error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 359, in …
Run Code Online (Sandbox Code Playgroud)

django django-migrations

5
推荐指数
1
解决办法
3885
查看次数

django多对多形式显示人类可读

我有以下模型:

CURSES=(('python','Python'),('django','Django'),...)
class Asig(models.Model):
    ...
    name = models.CharField(max_length=100, choices=CURSES)

class Profesor(AbstractUser):
    ...
    asigs = models.ManyToManyField(Asig)
Run Code Online (Sandbox Code Playgroud)

然后,当我使用ModelForm渲染表单时,多对多字段使用'python'字符串而不是'Python'来显示自身,此外,当我查看呈现的html编码时,multiselect选项如下所示:

<option value='1'>python</option>
Run Code Online (Sandbox Code Playgroud)

代替

<option value='python'>Python</option> 
Run Code Online (Sandbox Code Playgroud)

django many-to-many

5
推荐指数
1
解决办法
253
查看次数

Tweeter Oauth:您已通过XXX身份验证,但无权访问该页面。您想登录其他帐户吗?

我只创建了一个简单的 django 应用程序来使用 tweeter 登录,但是当我尝试从我的应用程序登录时,我收到此消息“您已通过 xxx 身份验证,但无权访问此页面。您想登录到不同的页面吗?”帐户?”

显示消息的屏幕截图

我尝试使用用于创建应用程序的帐户和不同的帐户登录,但结果是相同的。有什么办法可以解决这个问题?

我正在使用 django 和 django-allauth 库

django oauth django-allauth

5
推荐指数
1
解决办法
5172
查看次数

不支持在 include() 中指定命名空间而不提供 app_name

我收到这些错误

不支持在 include() 中指定命名空间而不提供 app_name。在包含的模块中设置 app_name 属性,或者传递包含模式列表和 app_name 的 2 元组。

我的代码如下所示

项目名称.urls

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('learning.urls',namespace='learning')),
  ]
Run Code Online (Sandbox Code Playgroud)

应用程序名称.url

from django.urls import path
from learning.views import SendEmail

urlpatterns = [
   path('',SendEmail.as_view(),name='home')
]
Run Code Online (Sandbox Code Playgroud)

python django django-urls

5
推荐指数
1
解决办法
1123
查看次数

在现有表中生成slug字段

我有数据表.是否可以在现有表格上自动生成slug字段?还是有其他选择吗?谢谢这是我的桌子

在此输入图像描述

python django

4
推荐指数
1
解决办法
2075
查看次数

在django中使用分页时如何返回最后一页?

在一个简单的论坛中,我使用本机 django分页我希望用户在他们发布后被定向到线程中的最后一页。

这是视图

@login_required
def topic_reply(request, topic_id):
    tform = PostForm()
    topic = Topic.objects.get(pk=topic_id)
    args = {}
    posts = Post.objects.filter(topic= topic)
    posts =  Paginator(posts,10)


    if request.method == 'POST':
        post = PostForm(request.POST)


        if post.is_valid():
            p = post.save(commit = False)
            p.topic = topic
            p.title = post.cleaned_data['title']
            p.body = post.cleaned_data['body']
            p.creator = request.user

            p.save()

            return HttpResponseRedirect('/forum/topic/%s/?page=%s'  % (topic.slug, posts.page_range[-1]))

    else:
        args.update(csrf(request))
        args['form'] = tform
        args['topic'] = topic
        return render_to_response('myforum/reply.html', args, 
                                  context_instance=RequestContext(request)) 
Run Code Online (Sandbox Code Playgroud)

其中产生:

'Page' object has no attribute 'page_range'
Run Code Online (Sandbox Code Playgroud)

我尝试了其他技巧,例如:

posts = list(Post.objects.filter(topic= …
Run Code Online (Sandbox Code Playgroud)

django django-pagination

4
推荐指数
1
解决办法
5114
查看次数