小编Pro*_*eus的帖子

Django:在所有queryset对象上运行一个方法

我想知道以下是否可行以及是否有人可以解释如何.我正在使用Django REST Framework

我有一个模型,在那个模型中我有一个名为Product的类.产品具有名为is_product_safe_for_user的方法.它需要用户对象和自我(产品).

model.py

class Product(models.Model):

    title = models.CharField(max_length=60, help_text="Title of the product.")
    for_age = models.CharField(max_length=2,)

    def is_product_safe_for_user(self, user):
        if self.for_age > user.age
        return "OK"
Run Code Online (Sandbox Code Playgroud)

(忽略上面的语法,它只是为了给你一个想法)

我想要做的是运行方法为所有的queryset对象,如下所示,但我不知道如何...

class ProductListWithAge(generics.ListAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    model = Product
    serializer_class = ProductSerializer

    def get_queryset(self):

      Product.is_product_safe_for_user(self,user)

       # then somehow apply this to my queryset

        return Product.objects.filter()
Run Code Online (Sandbox Code Playgroud)

还有一些时候我想在一个对象上运行methoud.

或者它应该进入Serializer?如果是这样的话......

class ProductSerializer(serializers.ModelSerializer):

    safe = serializers.Field(Product='is_product_safe_for_user(self,user)')

    class Meta:
        model = Product
        fields = ('id', 'title', 'active', 'safe')
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework

2
推荐指数
1
解决办法
2358
查看次数

Django芹菜减少时间,5小时完成1000个任务

我正在开发环境中运行,所以这在生产中可能有所不同,但是当我从Django Celery运行任务时,它似乎每隔10-20秒才从代理中获取任务.我只是在这一点上进行测试但是假设我发送大约1000个任务,这意味着它需要花费5个多小时才能完成.

这是正常的吗?应该更快吗?或者我做错了什么?

这是我的任务

class SendMessage(Task):
    name = "Sending SMS"
    max_retries = 10
    default_retry_delay = 3

    def run(self, message_id, gateway_id=None, **kwargs):
        logging.debug("About to send a message.")

        # Because we don't always have control over transactions
        # in our calling code, we will retry up to 10 times, every 3
        # seconds, in order to try to allow for the commit to the database
        # to finish. That gives the server 30 seconds to write all of
        # the data to …
Run Code Online (Sandbox Code Playgroud)

django django-celery

2
推荐指数
1
解决办法
285
查看次数

Backbone Marionette在模板示例中渲染模型

我正在将我的主干示例转换为现在扩展Marionette.我发现很难理解用模板实现同样的东西.让我解释.

这是我用来渲染模板的方式

在视图渲染功能中:

campaign.fetch({
 var template = _.template(campaignTemplate, {campaign: campaign});
 that.$el.html(template);  
Run Code Online (Sandbox Code Playgroud)

使用backbone.marionette我不知道如何做同样的事情,这是我没有任何喜悦的尝试:

  var campaginView = Backbone.Marionette.ItemView.extend({



        initialize: function (options) {
            // campaign id passed from the URL Route
            this.campaign_id = options.id;
        },

        model: new CampaginModel({
            id: this.campaign_id
        }),

        template: campaignTemplate({
           campaign: this.model.fetch() 
        }),



    }); // end campagin view
Run Code Online (Sandbox Code Playgroud)

*我做错了什么?下划线甚至没有!*

javascript jquery backbone.js marionette

2
推荐指数
1
解决办法
5003
查看次数

骨干传递参数到模型URL

在我的控制器中,我将一个名为"url"的参数传递给视图.这成功传递给initialize函数.接下来,当我创建模型时,我想将相同的参数传递给模型以用作rooturl.

以下是我尝试但我收到以下错误消息:

A "url" property or function must be specified 
Run Code Online (Sandbox Code Playgroud)

这似乎没有传递给模型的参数(未定义)或者我没有在模型中正确调用它.我在这里做错了什么?

注意:初始化函数视图中的console.log(options.url)确认参数已成功从控制器传递到视图,问题是从视图到未定义的模型.

控制器:

var myview = new NewView({
           url:"api/"
       })**
Run Code Online (Sandbox Code Playgroud)

视图:

  var myview = Backbone.Marionette.ItemView.extend({

        initialize: function (options) {
            this.url = options.url;
            this.model.fetch();
        },


    model: new myModel({
            url: this.url
        }),
Run Code Online (Sandbox Code Playgroud)

基于myModel:

var myModel = Backbone.Model.extend({
  urlRoot: function(){ return this.get('url') }

});
Run Code Online (Sandbox Code Playgroud)

javascript backbone.js marionette

2
推荐指数
1
解决办法
4485
查看次数

Django 查询集转为 json

有没有办法将我的查询集解压为 json?

例如:

test.objects.all()

return self.create_response(request, {
   'objects': test,


 })
Run Code Online (Sandbox Code Playgroud)

即类似的东西test.tojson()

python django

2
推荐指数
1
解决办法
5757
查看次数

Gunicorn 和 Supervisor 错误文件没有可执行权限

我正在尝试运行此命令:

sudo supervisorctl start gunicorn_process
Run Code Online (Sandbox Code Playgroud)

在 Ubuntu 上,我收到此错误:

在此处输入图片说明

如您所见,文件“确实”具有可执行权限。

gunicorn_process 文件:

[program:gunicorn_process]
command=/srv/domain wsgi:application
directory=/srv/domain
user=root
Run Code Online (Sandbox Code Playgroud)

python django supervisord gunicorn

2
推荐指数
1
解决办法
5771
查看次数

Python链式比较

我有这个代码:

if self.date: # check date is not NoneType
    if self.live and self.date <= now and self.date >= now:
         return True
return False
Run Code Online (Sandbox Code Playgroud)

我的IDE说:这看起来应该简化,即Python链式比较.

什么是链式比较,如何简化?

python django

2
推荐指数
1
解决办法
1292
查看次数

Django 脆皮形式将密码显示为明文

Crispy 表单目前将我的密码字段显示为明文。我尝试了以下操作,但仍然无法使用 type=password。

Fieldset(
            'Enter a password.',
            PrependedText('password', '<i class="fa fa-key"></i>',
                          placeholder='Password',
                          autocomplete='off',
                          widget=forms.PasswordInput,
                          ),
        ),
Run Code Online (Sandbox Code Playgroud)

我也累type="password"了没有效果。

我没有错误。

python django django-crispy-forms

2
推荐指数
1
解决办法
2347
查看次数

Python中的函数继承是否可行?

我知道Python类可以继承其他类,如下所示:

class A(object):
  pass

class B(A):
  pass
Run Code Online (Sandbox Code Playgroud)

但是,这可能与功能有关吗?例如,在Fab文件中,我目前有两个函数,它们执行一些相同的操作.我想要一个基本功能,所以我可以停止重复设置.

例如:

def environment_base():
    #settings for both environment1 and environment2 here

def environment1():
    pass

def environment1():
    pass
Run Code Online (Sandbox Code Playgroud)

我知道这是什么类,但Fabric没有给我选择使用类进行设置.

这是我的实际用例.我有一个Fabric文件,它有两个环境i..e fab environment1 commandfab environment2 command

def environment1():
     settings = get_settings(local_path)
     env.git_key = settings['GIT_KEY']
     env.hosts = get_hosts_list(local_path)

def environment1():
    settings = get_settings(local_path)
    env.hosts = get_hosts_list(local_path)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这两个功能都具有一些相同的设置,并且不符合"不要重复自己"的原则.

python

2
推荐指数
1
解决办法
51
查看次数

使用 Pillow 在 Python 中将数组转换为图像(tif)

我正在尝试将 anarray转换为图像(tif)进行压缩(它将在另一端撤消)。然而,我在第一个障碍上摔倒了......

我有以下几点:

pillow_image = Image.fromarray(image_data)
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误:

  File "/Users/workspace/test-app/env/lib/python2.7/site-packages/PIL/Image.py",
Run Code Online (Sandbox Code Playgroud)

第 2155 行,在 fromarray arr = obj 中。array_interface AttributeError: 'tuple' 对象没有属性 ' array_interface '

我在这里做错了什么?

python arrays python-imaging-library pillow

2
推荐指数
1
解决办法
5188
查看次数