小编use*_*276的帖子

使用Django中的电子邮件地址或用户名登录用户

我正在尝试创建一个auth后端,以允许我的用户使用他们的电子邮件地址或Django 1.6中的用户名使用自定义用户模型登录.当我使用用户名登录时后端工作,但由于某种原因没有电子邮件.有什么我忘了做的事吗?

from django.conf import settings
from django.contrib.auth.models import User

class EmailOrUsernameModelBackend(object):
    """
    This is a ModelBacked that allows authentication with either a username or an email address.

    """
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, username):
        try:
            return User.objects.get(pk=username)
        except User.DoesNotExist:
            return None
Run Code Online (Sandbox Code Playgroud)

编辑:建议我从ModelBackend继承并在我的设置中安装它在我的设置中我有这个AUTHENTICATION_BACKENDS =('users.backends','django.contrib.auth.backends.ModelBackend',)我已经将后端更改为这个:

from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.backends …
Run Code Online (Sandbox Code Playgroud)

python django django-authentication django-login

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

C中效率的"静态const"与"#define"

我最近想知道什么之间的区别#define,并static constç为什么两种方法存在做同样的事情.我发现有些人在这里有类似的问题:

很多人谈论最佳实践和约定,并给出使用一个在另一个上的实际原因,例如需要将指针传递给常量,我可以用a static const而不是a #define.但是我还没有找到任何人谈论两者效率的比较.

根据我对C预处理器的理解,如果我有这样的声明:

#define CONSTANT 6
Run Code Online (Sandbox Code Playgroud)

我创建一个可以像这样使用的常量值

char[CONSTANT]char[6]在实际编译之前, 它实际上将被替换为此语句.

这对我来说似乎比使用a更有效, static const constant = 6;因为这将创建一个名为constant的变量,它将存在于堆栈中,我认为它会带来更多的行李而不是a #define.假设我需要一个常量,我可以选择使用预处理器#definestatic const语句,没有明显的理由选择一个而不是另一个,哪个更有效?我将如何自己测试呢?

c performance constants c-preprocessor

21
推荐指数
2
解决办法
2万
查看次数

如何使用Django Rest Framework删除对象

我正在尝试使用Django Rest Framework为我的事件规划应用程序编写RESTful API,但是在使用不期望GET HTTP方法的视图时我遇到了一些麻烦.我已经阅读了DRF网站上的教程.根据我在阅读教程和Django网站上基于类的视图文档后的理解,如果有这样的基于类的视图(取自DRF教程)

class SnippetDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        snippet = self.get_object(pk)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Run Code Online (Sandbox Code Playgroud)

视图中的不同方法对应于不同的HTTP请求方法.因此,如果我拥有www.foo.com/bar它将根据发送到该地址的请求方法做两件事.这意味着我不必指定任何其他内容,因为执行的函数是根据发送URL的方法确定的.它是否正确?

我有这个视图,我试图在DRF网站上的示例之后建模

class EventDetail(APIView):

    """
    Retrieve, update or …
Run Code Online (Sandbox Code Playgroud)

python django rest django-rest-framework

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

在python脚本中运行powershell脚本,如何让python在运行时打印powershell输出

我正在编写一个python脚本,它检查各种条件并相应地运行一个PowerShell脚本,以帮助我自动从Windows XP迁移到Windows 7. powershell脚本提供自己的输出,为用户提供有关正在发生的事情的更新.我想获取powershell脚本的输出并将其打印为python脚本的输出.我已经环顾了一些似乎想要做同样事情的问题,但它们似乎并不适合我.最初我尝试过使用

import subprocess
subprocess.call(["C:\Users\gu2124\Desktop\helloworld.ps1"])
Run Code Online (Sandbox Code Playgroud)

正如在这里建议的那样,从Python脚本运行PowerShell函数,但我发现这等待程序首先执行而不提供输出所以我发现我需要使用subprocess.Popen()这里所谓的使用 Popen 在Python中执行Powershell脚本,如何获取Powershell脚本的输出并将其更新到网页?所以我试过这个

import subprocess
subprocess.Popen(["C:\Users\gu2124\Desktop\helloworld.ps1"], stdout=sys.stdout)
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

Traceback (most recent call last):
  File "C:\Users\gu2124\Desktop\pstest.py", line 5, in <module>
    subprocess.Popen(["C:\Users\gu2124\Desktop\helloworld.py1"], stdout=sys.stdout)
  File "C:\Python27\lib\subprocess.py", line 701, in __init__
    errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
  File "C:\Python27\lib\subprocess.py", line 848, in _get_handles
    c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  File "<string>", line 523, in __getattr__
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 150, in __getattr__
    return syncreq(self, consts.HANDLE_GETATTR, name)
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 71, in syncreq …
Run Code Online (Sandbox Code Playgroud)

python windows powershell stdout python-2.7

9
推荐指数
3
解决办法
6万
查看次数

实现自定义用户模型时,creatuperuser会出现问题

我试图在Django 1.6中实现我自己的自定义用户模型,但我收到此错误.

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/Users/gabriel/.virtualenvs/hang_server/lib/python3.4/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 141, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'email'
Run Code Online (Sandbox Code Playgroud)

这是我的UserManager

class UserManager(BaseUserManager):

  def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
    now = timezone.now()
    email = self.normalize_email(email)
    user = …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-users

9
推荐指数
1
解决办法
7582
查看次数

virtualenv python3 中的 psycopg2 与 Django 一起使用时出现问题

我有一个 Django 项目,我想将其与 PostgreSQL 数据库一起使用,但我遇到了 psycopg2 的问题。当我尝试运行开发服务器或执行同步数据库时,出现此错误。我的项目位于运行 Python 3.4 和 Django 1.6 的 virtualenv 中。

Traceback (most recent call last):
  File "/home/gabriel/DevSpace/Django_Projects/Kevmo/lib/python3.4/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in <module>
    import psycopg2.extensions
ImportError: No module named 'psycopg2.extensions'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/gabriel/DevSpace/Django_Projects/Kevmo/lib/python3.4/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/home/gabriel/DevSpace/Django_Projects/Kevmo/lib/python3.4/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/gabriel/DevSpace/Django_Projects/Kevmo/lib/python3.4/site-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/gabriel/DevSpace/Django_Projects/Kevmo/lib/python3.4/site-packages/django/core/management/base.py", line 280, …
Run Code Online (Sandbox Code Playgroud)

python django postgresql psycopg2 virtualenv

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

在this关键字上调用函数

所以在我的头文件中,我将这两个变量声明为private

private:

    char* data;

    int len;
Run Code Online (Sandbox Code Playgroud)

并让它访问它

int length() const { return len; }
Run Code Online (Sandbox Code Playgroud)

然后在我的cpp文件中,我试图覆盖字符串实现中的运算符,如下所示:

bool MyString::operator>(const MyString& string)
 {
    //Compare the lengths of each string
    if((this.length()) > (string.length())){
        return 0;
    }
    //The given string is shorter
    return -1;
 }
Run Code Online (Sandbox Code Playgroud)

当我编译这个时,我收到此错误:

mystring.cpp:263:14:错误:请求'this'中的成员'length',这是非类型'MyString*const'

从我可以通过尝试调用.length()on 来判断这是尝试访问此指针上的变量,这导致问题,就像在这个问题中.

那很好,因为我可以这样做:

 bool MyString::operator>(const MyString& string)
 {
    //Compare the lengths of each string
    if((this->len) > (string.length())){
        return 0;
    }
    //The given string is shorter
    return -1;
 }
Run Code Online (Sandbox Code Playgroud)

编译很好,但现在我想知道如何在这个指针上调用一个函数.我认为,因为它是一个指针,我必须先取消引用它,所以我尝试了这个:

bool MyString::operator>=(const MyString& string)
 { …
Run Code Online (Sandbox Code Playgroud)

c++ function this

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

OpenCV HOG 人物检测 - 如何判断检测到的人与之前检测到的人是否是同一个人?

我是 OpenCV 的新手,我正在尝试编写一个程序来检测视频中的人物。我有这段代码,它是 peopleDetect 示例的变体。

def inside(r, q):
    rx, ry, rw, rh = r
    qx, qy, qw, qh = q
    return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh


def draw_detections(img, rects, thickness=1):
    for x, y, w, h in rects:
        # the HOG detector returns slightly larger rectangles than the real objects.
        # so we slightly shrink the rectangles to get a nicer output.
        pad_w, …
Run Code Online (Sandbox Code Playgroud)

python opencv computer-vision opencv3.0

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

git checkout感到困惑

我是git的新手,并试图围绕分支的工作方式.根据文档git checkout

更新工作树中的文件以匹配索引或指定树中的版本.如果>没有给出路径,git checkout也会更新HEAD以将指定的分支设置为>当前分支.

所以据我所知,我工作的目录中的文件(我执行git init的文件)应该根据我所在的分支进行更改.我很困惑,因为当我在分支之间切换时不会发生这种情况.在切换分支之前我正在编辑的编辑存在于我切换到的分支中.我做错了什么或git checkout不能这样工作,我只是误解了文档?

git

4
推荐指数
2
解决办法
2699
查看次数

澄清django syncdb --all选项

我想知道到底是./manage.py syncdb --all做什么的?我最近有一个数据库问题,我可以通过运行此命令来解决,但我不确定它在幕后做了什么.据我所知,syncdb为未安装南方的已安装应用程序创建表格,除非指定了--all选项但是我对实际发生的事情和何时使用感到困惑,因此忽略了南迁移控制下的表格它.我无法在django-admin文档中找到关于该选项的任何内容,并且手册页仅对该选项说了这个.

--all                 Makes syncdb work on all apps, even migrated ones. Be
                        careful!
Run Code Online (Sandbox Code Playgroud)

为什么我需要小心?这究竟是做什么的?是完全删除数据库并重新开始,我认为这会导致我丢失存储在数据库中的所有数据(对吗?),还是会发生其他事情?我正在使用Django 1.6,如果这有所作为.

django django-syncdb django-1.6

3
推荐指数
1
解决办法
653
查看次数