小编sol*_*oke的帖子

覆盖AppConfig.ready()

试图抓住Django的基础知识.即应用程序如何工作.文档:https://docs.djangoproject.com/en/stable/ref/applications/#methods

在AppConfig类的代码中我们可以读到:

def ready(self):
    """
    Override this method in subclasses to run code when Django starts.
    """
Run Code Online (Sandbox Code Playgroud)

嗯,这是我的例子:

my_app应用/ apps.py

class MyAppConfig(AppConfig):
    name = 'my_app'

    def ready(self):
        print('My app')
Run Code Online (Sandbox Code Playgroud)

我只想让ready方法工作.也就是说,当Django找到my_app时,让它运行ready方法.

该应用程序已在INSTALLED_APPS中注册.

我执行'python manage.py runserver'.什么都没打印出来.

如果我在ready方法中放置一个断点,那么调试器就不会停在那里.

你能帮助我吗:我在这里理解的错误是什么?先感谢您.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'my_app',
]
Run Code Online (Sandbox Code Playgroud)

我创建了一个视图

my_app应用/ views.py

def index(request):
    print('Print index')
Run Code Online (Sandbox Code Playgroud)

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', my_app_views.index, name='home')
]
Run Code Online (Sandbox Code Playgroud)

嗯,这个观点很有效.这意味着该应用程序已注册.

django

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

Django:timezone.now vs timezone.now()

我正在将我的项目从Django 1.8.2升级到1.9.7,我收到了这个警告:

WARNINGS:
my_app.my_model.date_available: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. 
If you want to have the current date as default, use `django.utils.timezone.now
Run Code Online (Sandbox Code Playgroud)

这是my_app/models.py中的行:

from django.utils import timezone
...
class my_model(models.Model):
    ...
    datetime_released = models.DateTimeField(default=timezone.now() )
Run Code Online (Sandbox Code Playgroud)

如果我删除括号而改为使用:

datetime_released = models.DateTimeField(default=timezone.now )
Run Code Online (Sandbox Code Playgroud)

Django警告消失了.这两者有什么区别?


在我的项目的另一个领域,我在queryset过滤器中使用timezone.now():

def date_available(self):
        return self.filter(date_available__lte = timezone.now())
Run Code Online (Sandbox Code Playgroud)

在这里,如果删除括号,则会抛出错误:

TypeError: expected string or buffer


我可以通过添加/删除所需的括号内同时获得这两项工作,但之间有什么区别timezone.now() …

python django timezone

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

413请求实体太大nginx django

我正在制作练习网络服务(客户端的artbook显示网站)客户端可以将artbook图像上传到服务器.

但是当客户端上传太多图像时,我收到以下错误

413 Request Entity Too Large
Run Code Online (Sandbox Code Playgroud)

我尝试client_max_body_size 100M;在nginx.conf中添加

#user  nobody;
#Defines which Linux system user will own and run the Nginx server

worker_processes  1;

#error_log  logs/error.log; #error_log  logs/error.log  notice;
#Specifies the file where server logs.

#pid        logs/nginx.pid;
#nginx will write its master process ID(PID).

events {
    worker_connections  1024;
}


http {
    include       mime.types;

    default_type  application/octet-stream;

    #access_log  logs/access.log  main;

    sendfile        on;

    server {
        listen       80;

        server_name  xxxx.net;
        client_max_body_size 100M;
        keepalive_timeout 5;

        return 301 https://$server_name$request_uri;

    }

    # HTTPS server …
Run Code Online (Sandbox Code Playgroud)

django nginx http-status-code-413

10
推荐指数
2
解决办法
5305
查看次数

无法在Node.js res.body中获取$ http.post请求数据

我正在为项目使用Angular 1.3和node.js 0.12.2.我正在使用node.js api

$http.post("url", request_data){}
Run Code Online (Sandbox Code Playgroud)

在服务器端使用这个:

console.log(req.body)
Run Code Online (Sandbox Code Playgroud)

但每次的API被调用时,它得空对象{}request_data,无法获取的问题是什么.我用过body_parser这样的:

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
Run Code Online (Sandbox Code Playgroud)

还尝试在angular $ http中添加内容类型标头:

headers : {'Content-Type': 'applicatio n/x-www-form-urlencoded'}
Run Code Online (Sandbox Code Playgroud)

但没有得到请求数据.

编辑:

Node.js代码:

router.post('/url',function(req,res){
    console.log(req.body)  
})
Run Code Online (Sandbox Code Playgroud)

注意:Developer Tool的网络选项卡显示正在发送的请求标头中的数据,但node.js服务器未接收到req.body.在POSTman中获取数据是正确的响应.

json http-post node.js angularjs

8
推荐指数
1
解决办法
4367
查看次数

decimal.Decimal(n)%1返回InvalidOperation,DivisionImpossible所有n> = 100

我在django应用程序中使用Decimal对象,并发现了这个奇怪的错误:

ipdb> decimal.Decimal(10) % 1
    Decimal('0')
ipdb> decimal.Decimal(100) % 1
    *** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
ipdb> decimal.Decimal(150) % 1
    *** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
ipdb> decimal.Decimal(79) % 1
    Decimal('0')
ipdb> decimal.Decimal(100.1) % 2
    Decimal('0.10')
ipdb> decimal.Decimal(1000) % 2
    *** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
Run Code Online (Sandbox Code Playgroud)

更神秘的是,在数字变得非常大之前,ipython中不会发生这种情况:

In [23]: decimal.Decimal(10**27) % 1
Out[23]: Decimal('0')

In [24]: decimal.Decimal(10**28) % 1
---------------------------------------------------------------------------
InvalidOperation                          Traceback (most recent call last)
<ipython-input-24-6ceaef82d283> in <module>()
----> 1 decimal.Decimal(10**28) % 1

InvalidOperation: [<class 'decimal.DivisionImpossible'>]
Run Code Online (Sandbox Code Playgroud)

请注意,错误不仅限于ipdb:我发现这是因为Decimal(380)%1打破了我的django应用程序.

描述此错误的文档说:

分裂不可能

如果除数整数或余数运算的整数结果具有太多数字(将比精度长),则会发生这种情况并发出无效操作信号.结果是[0,qNaN].

有任何想法吗?

python django decimal python-3.5

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

Elasticsearch术语查询不会给出任何结果

我是Elasticsearch的新手,我必须执行以下查询:

GET book-lists/book-list/_search
{  
   "query":{  
      "filtered":{  
         "filter":{  
            "bool":{  
               "must":[  
                  {  
                     "term":{  
                        "title":"Sociology"
                     }
                  },
                  {  
                     "term":{  
                        "idOwner":"17xxxxxxxxxxxx45"
                     }
                  }
               ]
            }
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

根据Elasticsearch API,它等同于伪SQL:

SELECT document
FROM   book-lists
WHERE  title = "Sociology"
       AND idOwner = 17xxxxxxxxxxxx45
Run Code Online (Sandbox Code Playgroud)

问题是我的文档看起来像这样:

{  
   "_index":"book-lists",
   "_type":"book-list",
   "_id":"AVBRSvHIXb7carZwcePS",
   "_version":1,
   "_score":1,
   "_source":{  
      "title":"Sociology",
      "books":[  
         {  
            "title":"The Tipping Point: How Little Things Can Make a Big Difference",
            "isRead":true,
            "summary":"lorem ipsum",
            "rating":3.5
         }
      ],
      "numberViews":0,
      "idOwner":"17xxxxxxxxxxxx45"
   }
}
Run Code Online (Sandbox Code Playgroud)

并且上面的Elasticsearch查询不会返回任何内容.

然而,此查询返回上面的文档:

GET book-lists/book-list/_search
{  
   "query":{  
      "filtered":{  
         "filter":{  
            "bool":{ …
Run Code Online (Sandbox Code Playgroud)

elasticsearch

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

django annotate - 条件计数

我有一个名为'StoreItem'的模型和一个名为'QuoteItem'的模型.QuoteItem指向StoreItem.

我正在尝试注释一个计数器,该计数器指出商店项目上有多少引用项目,但是条件适用于报价项目.

我试过这样的事情:

items = items.annotate(
            quote_count=Count(
                Case(
                    When(quoteitem__lookup_date__in=this_week, then=1), 
                    output_field=IntegerField()
                )
            )
        )
Run Code Online (Sandbox Code Playgroud)

'items'是StoreItems的查询集.'this_week'是代表本周的日期列表(这是我尝试应用的过滤器).在我使日期工作之后,我想为这个条件计数添加更多过滤器,但让我们开始吧.

无论如何我得到的更像是一个布尔值 - 如果符合条件的引用项存在,无论我有多少,计数器将是1.否则,将为0.

它看起来是Count(Case())唯一检查是否存在任何项目,如果存在则返回1,而我希望它迭代指向商店项目的所有报价项目并计算它们,如果它们与条件匹配(单独).

我该如何实现?

python django django-models django-filter django-annotate

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

如何跳过特定模型的Django admin中的删除确认页面?

我有一个包含大量数据的模型,Django 创建删除确认页面很长时间。我必须跳过这个过程并在没有任何确认的情况下删除数据。我尝试了一些来自互联网的解决方案,但它不起作用 - 我仍然看到确认页面。

有谁知道怎么做?

python django

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

为什么 widthratio(乘法)在我的模板中不起作用?

我正在使用 Django 2.0 和 Python 3.7。我读过我可以通过使用 widthratio 在模板中进行乘法——django 模板中的乘法而不使用手动创建的模板标签。但是,在我的模板中,我尝试这样做无济于事。我想

 {% if widthratio articlestat.score 1 TRENDING_PCT_FLOOR >= articlestat.weighted_score %}style="font-weight:bold;"{% endif %}
Run Code Online (Sandbox Code Playgroud)

当我的模板用这段代码执行时,它给出了错误......

Unused 'articlestat.score' at end of if expression.
Run Code Online (Sandbox Code Playgroud)

我希望我的 if 表达式说明“articlestat.score”和“TRENDING_PCT_FLOOR”的倍数是否大于“articlestat.weighted_score”,打印出来,但我似乎无法弄清楚如何做到这一点。

django templates multiplication python-3.x

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

通过Sendgrid发送电子邮件时无法获得单个换行符

我正在django.core.mail用来发送电子邮件.我希望在电子邮件的某些位置实现单个换行符,如下所示:

Line 1
Line 2

Line 3
Line 4
Run Code Online (Sandbox Code Playgroud)

我试着这样做使用\nLine 1Line 3,和\n\nLine 2Line 4.

当我发送电子邮件时,会收到这样的信息:

Line 1 Line 2

Line 3 Line 4
Run Code Online (Sandbox Code Playgroud)

根据其他StackOverflow答案的建议,我尝试使用该django.template.loader.render_to_string方法从文件生成相应的字符串,但它生成一个字符串,\n其中包含我放置它们的确切位置,等等发送电子邮件会产生相同的不良结果.

当我将字符串打印到stdout时,它会根据需要显示.

总之,它们\n\n正在工作,但是在\n通过Django发送电子邮件时会转换为空格send_mail.怎么解决这个问题?请注意,这个问题是关于明文电子邮件,而不是HTML电子邮件.

编辑:来源,根据评论的要求:

from django.core.mail import send_mail
send_mail(
    'Test subject',
    'Line 1\nLine 2\n\nLine 3\nLine 4\n\n',
    'noreply@test.com',
    ['myemail@gmail.com'],
)
Run Code Online (Sandbox Code Playgroud)

通过SendGrid使用SMTP发送,如我的settings.py文件中所指定:

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'myusername'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = …
Run Code Online (Sandbox Code Playgroud)

python email django

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