小编mar*_*rue的帖子

我可以在没有测试客户端的情况下访问测试视图的响应上下文吗?

我有一个函数,我从unittest调用.从设置一些调试跟踪,我知道该功能像魅力一样工作,并具有正确准备返回的所有值.

这就是我的testcode的样子(请参阅我的ipdb.set_trace()所在的位置):

@override_settings(REGISTRATION_OPEN=True)
def test_confirm_account(self):
    """ view that let's a user confirm account creation and username
        when loggin in with social_auth """    
    request = self.factory.get('')
    request.user = AnonymousUser()
    request.session={}
    request.session.update({self.pipename:{'backend':'facebook',
                                           'kwargs':{'username':'Chuck Norris','response':{'id':1}}}})

    # this is the function of which i need the context:
    response = confirm_account(request)
    self.assertEqual(response.context['keytotest'],'valuetotest')
Run Code Online (Sandbox Code Playgroud)

根据我从Django文档的这一部分所知,当我使用测试客户端时,我将能够访问response.context.但是当我尝试访问response.context就像我做的那样,我得到了这个:

AttributeError:'HttpResponse'对象没有属性'context'

有没有办法在不使用客户端的情况下获取客户端的特殊HttpResponse对象?

django django-views django-testing

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

使用视图装饰器更新request.POST或request.GET

我尝试将我在模板和js中使用的代码转换为包装函数正在使用的content_type和object_id:

def translate_modelcode(function=None,redirect_field_name=None):
    """
    translate an item-code specified in settings to a content_type
    and the item-id to the object_id
    """

    def _decorator(function):
        def _wrapped_view(request, *args, **kwargs):

            item_code=request.REQUEST.get('item-code',None)
            if item_code:
                object_id = request.REQUEST.get('item-id',None)
                # resolve_modelcode get's the models name from settings
                content_type = resolve_modelcode(item_code)
                ud_dict = {'content_type':content_type,
                          'object_id':object_id}
                if request.method == 'GET':
                    request.GET.update(ud_dict)
                else:
                    request.POST.update(ud_dict)


            return function(request, *args, **kwargs)
        return _wrapped_view

    if function is None:
        return _decorator
    else:
        return _decorator(function)
Run Code Online (Sandbox Code Playgroud)

我被卡住的地方是更新request.POST/request.GET QueryDict.Django报告这些决定是不可改变的.我该如何更新它们?

djangodocs我认为.update将使用那里描述的"最后价值逻辑",我会完全没问题.但那并没有发生.创建副本并将其重新分配给request.GET似乎也不起作用:

request.GET = request.GET.copy().update(ud_dict)
Run Code Online (Sandbox Code Playgroud)

关于这个主题在这里有一个类似的问题,但它从来没有得到令人满意的答案.使用与该问题相同的代码,我只是在更新后得到request.POST或request.GET的null返回: …

python django

7
推荐指数
1
解决办法
5353
查看次数

为什么子进程在这里抛出OSError?

我编写了自己的模块,主要处理django站点的文件字段.搞乱了与mod_wsgi相关的一些事情(通过更新到3.3解决了),我得到了运行的代码.在所有必要的导入之后,在定义任何类或函数之前,我测试sox的可用性,这是我的一些模块函数必不可少的audiocommandlinetool:

sox = 'path/to/sox'
test=subprocess.Popen([sox,'-h'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
error=test.communicate()[1]
if error:
    raise EnvironmentError((1,'Sox not installed properly'),)
Run Code Online (Sandbox Code Playgroud)

这很好.现在我已经从8.04更新了ubuntu到10.04,代码在subprocess.Popen调用行中止,抛出以下错误信息:

File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error  
Run Code Online (Sandbox Code Playgroud)

我已经找到了sox的执行权,我不知道在哪里寻找解决方案.子进程执行权限是否有限?任何提示可能会发生什么?

python django ubuntu mod-wsgi

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

为什么不能从Kivy终止这个Python多处理过程?

我正在尝试从Kivy应用程序中运行django开发服务器.到目前为止,这确实很顺利.

现在我想让用户在服务器运行时继续使用该程序.我的想法是为httpd.serve_forever()创建一个multiprocessing.Process,以避免完全锁定主程序.工作得很好 这是我的internal_django模块中的代码:

import multiprocessing
import os
import time

from wsgiref.simple_server import make_server

def django_wsgi_application():

    PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
    settings_module = "djangosettings"#%s.djangosettings" % PROJECT_ROOT.split(os.sep)[-1]

    os.environ.update({"DJANGO_SETTINGS_MODULE":settings_module})

    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()

    return application


class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class DjangoServer():
    __metaclass__ = Singleton

    def start(self):
        self.httpd = make_server('', 8000, django_wsgi_application())
        self.server = multiprocessing.Process(target=self.httpd.serve_forever)
        self.server.start()
        print "Now serving on port 8000..."
        print "Server Process PID …
Run Code Online (Sandbox Code Playgroud)

python django multiprocessing kivy

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

替换与图像字段关联的文件,而无需django复制它

我有一个表单的userprofile

class profile():
  #the next line is just an abstract
  profile_images='volumes/media/root/userprofile/profile_images/'
  image=models.ImageField(upload_to=profile_images)
Run Code Online (Sandbox Code Playgroud)

在"profile_images"目录中,用户上传的最后5个文件为个人资料图片,即:

image_1
image_2
image_3
image_4
image_5
Run Code Online (Sandbox Code Playgroud)

让我们说当前的profile.image是image_1.现在我想让用户选择以前的图像之一.我写的函数将图像更改为从表单中收到的图像看起来像:

def change_profile_image(userprofile,path_to_new_image):
  f = open(path_to_new_image, 'r')
  userprofile.image = ImageFile(f)
  userprofile.save()
Run Code Online (Sandbox Code Playgroud)

作为示例,用户选择image_3,并且在执行该代码之后,前述目录看起来像:

image_1
image_2
image_3
image_4
image_5
volumes/media/root/userprofile/profile_images/image_3
Run Code Online (Sandbox Code Playgroud)

当然,这不是我想要的.我想要的只是更改与我的配置文件实例的ImageField相关联的文件,而不是Django复制任何文件.
任何想法如何解决?

django

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

模拟用于测试表单的filedata的正确方法是什么?

我正在尝试测试一个自编写的FormField AudioFileFormField,它在存储之前检查文件是否是一个audiofile.为此我已经覆盖了to_python方法.试图测试这个FormField我遇到了一些困难.

到目前为止这是我的TestCase:

from django import forms
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

class TestAudioFileFormField(TestCase):
    """ test the formfield to use for AudioFile Uploads """

    class TestForm(forms.Form):
        audiofilefield = AudioFileFormField()


    def setUp(self):

        self.AUDIOFILE_TEST_ROOT = os.path.dirname(__file__) + '/data/'
        self.files = audiofile_files


    def test_to_python(self):
        """ assign some files to a form and validate the form """

        f = file(self.AUDIOFILE_TEST_ROOT + self.files[0]) 
        file_data = {'audiofilefield':SimpleUploadedFile( self.files[0],f.read() )}
        data = {}

        form = self.TestForm(data,f)
        form.is_valid()
Run Code Online (Sandbox Code Playgroud)

form.is_valid()行引发了一个AttributeError:'file'对象没有属性'get'

当我在form.is_valid()之前插入调试跟踪时,这是我在该交互式会话中得到的:

ipdb> form.is_valid()
AttributeError: 'file' object …
Run Code Online (Sandbox Code Playgroud)

django django-forms django-file-upload

5
推荐指数
2
解决办法
2668
查看次数

如何在JavaScript中以编程方式命名对象"键"?

我想要的是我每天用Python做的事情.在JS中它不起作用,很可能是因为我吮吸JS.

这是我想要的Python代码:

>key = 'just_a_key'
>value = 5
>dict = {key: value}
>dict
{'just_a_key':5}
>dict['just_a_key'}
5
Run Code Online (Sandbox Code Playgroud)

这在JS中不起作用,关键是将命名为'key'.我知道这是因为我不是真的在这里创建一个字典,而是在编写相同代码时使用json创建一个对象.所以我现在的问题是:如何以编程方式在JS中命名对象"keys"(或属性?)?

javascript python json

5
推荐指数
2
解决办法
4017
查看次数

Less是否具有缩短输入类型选择器的功能?

我写过这个css:

.form-group > input[type="text"],
.form-group > input[type="text"]:hover,
.form-group > input[type="text"]:active,
.form-group > input[type="password"],
.form-group > input[type="password"]:hover,
.form-group > input[type="password"]:active,
.form-group > input[type="email"],
.form-group > input[type="email"]:hover,
.form-group > input[type="email"]:active {
    max-width: 400px;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过写作来缩短这一点

.form-group > input[type="text"],
.form-group > input[type="password"],
.form-group > input[type="email"] {
    max-width: 400px;
    &:hover,
    &:active {
    }
}
Run Code Online (Sandbox Code Playgroud)

好吧,第二个代码部分是我真正写的东西,第一个代码只是针对问题的戏剧性,我猜;)

现在我想知道是否有一个功能允许对输入类型选择器进行分组,如下所示:

.form-group > input {
        $:text,password,email
    max-width: 400px;
    &:hover,
    &:active {
    }
}
Run Code Online (Sandbox Code Playgroud)

css less

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

为什么login_required装饰器返回302状态代码?

我有一个视图,允许使用ajax请求动态添加标签.它看起来像这样:

@require_POST
@login_required
def addtag(request):
   """
   a view to create a new tag in the tag database
   """
   some logic here
Run Code Online (Sandbox Code Playgroud)

这就是我的url.py看起来像:

urlpatterns = patterns('',
                       url(r'^addtag/$',addtag, name='addtag'),
                      )
Run Code Online (Sandbox Code Playgroud)

我的测试是这样做的:

def test_addtag(self):
    url='^addtag/$'

    response = self.client.post(url,{'addtag':'"new tag"'})
    self.assertEqual(response.status_code,401)
Run Code Online (Sandbox Code Playgroud)

我希望返回的状态代码是401,因为testclient没有登录.所以第一个装饰器,检查请求是否是一个帖子正在愉快地传递.然后我希望login_required装饰器返回401,但它没有:

AssertionError: 302 != 401
Run Code Online (Sandbox Code Playgroud)

首先我认为login_required装饰器将重定向到某个登录页面.检查一下,我没有settings.LOGIN_REDIRECT_URL指定.那么login_required在这种情况下做了什么?

django django-authentication

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

尽管正则表达式匹配,为什么Django找不到这些网址?

在正则表达式的python文档中,有"."的描述.作用:

(点.)在默认模式下,它匹配除换行之外的任何字符.如果指定了DOTALL标志,则匹配包括换行符在内的任何字符.

对于我在Django中进行的项目,我设置了这个正则表达式:

url(r'^accounts/confirm/(.+)$', confirm,name='confirmation_view')
Run Code Online (Sandbox Code Playgroud)

据我所知,这应该匹配任何以'accounts/confirm /'开头的网址,然后是任意数量的任意字符.然后将这些任意字符作为参数传递给函数"confirm".到现在为止还挺好.

所以这个正则表达式应该匹配

accounts/confirm/fb75c6529af9246e4e048d8a4298882909dc03ee0/
Run Code Online (Sandbox Code Playgroud)

同样如此

accounts/confirm/fb75c6529af9246e4e-048d8a4298882909dc03ee0/
Run Code Online (Sandbox Code Playgroud)

accounts/confirm/fb75c6529af9246e4e=048d8a4298882909dc03ee0/
Run Code Online (Sandbox Code Playgroud)

accounts/confirm/fb75c6529af9246e4e%20048d8a4298882909dc03ee0/
Run Code Online (Sandbox Code Playgroud)

至少,这是我认为它会做的.但它没有,它只匹配第一个.Django一直让我回到404.我不明白,因为表达式的(.+)部分应该表示"匹配除换行符之外的任何字符的一个或多个".

编辑: 正如评论和答案所证明的那样,我得到了正则表达式.所以现在这是一个问题:为什么Django没有返回正确的视图,而是404.在将它传递给该正则表达式之前它是否正在对URL进行一些操作?

python regex django

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