小编Str*_*ker的帖子

django admin截断list_display中的文本

需要截断管理列表显示中的文本

管理模型中有以下内容,但仍显示全文。

from django.template.defaultfilters import truncatewords

def get_description(self, obj):
    return truncatewords(obj.description, 10)
get_description.short_description = "description"

class DieTaskAdmin(admin.ModelAdmin):
    list_display =['severity','priority', 'subject', 'status','created',get_description.short_description']

admin.site.register(DieTask, DieTaskAdmin)
Run Code Online (Sandbox Code Playgroud)

即描述字段的原始文本包含超过255个字符。我喜欢只显示前 10 个字符加上...

django admin list display

7
推荐指数
2
解决办法
6611
查看次数

如何修复:错误(use-package):org-projectile:config:符号的函数定义为void:org-projectile:per-repo

运行spacemacs 0.200.9@25.1.1每次启动spacemacs我都会收到以下错误,不知道如何解决它.

Error (use-package): org-projectile :config: Symbol’s function definition is void: org-projectile:per-repo
Run Code Online (Sandbox Code Playgroud)

尝试谷歌搜索问题,一些人建议切换到我不知道该怎么做的开发分支.

谢谢

spacemacs

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

如果有值,如何在django admin中有条件地显示字段?

在admin.py文件中我有一个

 fields = ('name', 'description', ('created_by','created', ),('updated_by', 'updated'))
Run Code Online (Sandbox Code Playgroud)

我如何只显示created,created_by如果是非空白.当我要创建新记录时,created_by,created,updated_by和updated是空白的,我不需要显示它们.

只有当我保存记录时,我才想在django admin中显示这些字段.

django-models django-admin

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

模块“google.cloud.speech_v1p1beta1.types”没有“RecognitionAudio”成员

尝试运行示例代码,但出现此错误”

Module 'google.cloud.speech_v1p1beta1.types' has no 'RecognitionAudio' member
Run Code Online (Sandbox Code Playgroud)

环境:python3x,linux,已安装和更新的 google-cloud lib

pip install --upgrade google-cloud-speech.
Run Code Online (Sandbox Code Playgroud)

安装了以下

  • 谷歌云 (0.34.0)
  • 谷歌云语音(0.36.3)

不知道还有什么要检查的。如果您有任何建议,那就太好了

import argparse
import io

def transcribe_file_with_enhanced_model():
    """Transcribe the given audio file using an enhanced model."""
    # [START speech_transcribe_enhanced_model_beta]
    from google.cloud import speech_v1p1beta1 as speech
    client = speech.SpeechClient()

    speech_file = 'resources/commercial_mono.wav'

    with io.open(speech_file, 'rb') as audio_file:
        content = audio_file.read()

    audio = speech.types.RecognitionAudio(content=content)

    config = speech.types.RecognitionConfig(
        encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=8000,
        language_code='en-US',
        # Enhanced models are only available to projects that
        # opt in for audio …
Run Code Online (Sandbox Code Playgroud)

speech-recognition speech-to-text google-speech-api

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

如何在django admin中显示带有相关对象计数的list_filter?

如何在django admin的list_filter中的每个过滤器之后显示相关对象的计数?

class Application(TimeStampModel):

    name = models.CharField(verbose_name='CI Name', max_length=100, unique=True)
    description = models.TextField(blank=True, help_text="Business application")

class Server(TimeStampModel):
    name = models.CharField(max_length=100, verbose_name='Server Name', unique=True)
    company = models.CharField(max_length=3, choices=constants.COMPANIES.items())
    online = models.BooleanField(default=True, blank=True, verbose_name='OnLine')
    application_members = models.ManyToManyField('Application',through='Rolemembership',
            through_fields = ('server', 'application'),
            )


class Rolemembership(TimeStampModel):

    server = models.ForeignKey(Server, on_delete = models.CASCADE)
    application = models.ForeignKey(Application, on_delete = models.CASCADE)
    name = models.CharField(verbose_name='Server Role', max_length=50, choices=constants.SERVER_ROLE.items())
    roleversion = models.CharField(max_length=100, verbose_name='Version', blank=True)
Run Code Online (Sandbox Code Playgroud)

管理员

@admin.register(Server)
class ServerAdmin(admin.ModelAdmin):

    save_on_top = True
    list_per_page = 30
    list_max_show_all = 500
    inlines = …
Run Code Online (Sandbox Code Playgroud)

django-admin django-modeladmin

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

如何使用 aws cli boto3 在 AWS EC2 中使用 userdata 安装 python3 和 Django

我需要通过 EC2 实例上的用户数据安装 python3 和 django。我知道我可以使用 Cloudformation 或直接在 EC2 上执行此操作,但我需要通过用户数据安装和部署它。我正在创建 VPC 和自动缩放器,但我需要自动安装和部署 python3 和 django。

这是我所拥有的,但似乎不起作用。

    UserData="""#!/bin/bash
            yum install httpd php php-mysql -y
            echo y | sudo yum install python36 python36-virtualenv python36-pip
            sudo pip install --upgrade pip
            python3 -m venv venv
            source ./venv/bin/activate
            pip install django
            pip install --upgrade pip
            yum update -y
            service httpd start
            chkconfig httpd on
            adduser Eteram
Run Code Online (Sandbox Code Playgroud)

我试过用双引号将它们括起来,但仍然不起作用。

我基本上是在尝试安装 python3 和 django 并部署一个测试应用程序,以便能够转到 django 管理 url。

如果我在 EC2 上运行上述命令,它运行得很好。但是当我将它包含在用户数据中时,在我登录到 EC2 并检查云初始化日志后,我看到以下内容:

/var/lib/cloud/instance/scripts/part-001: line 3: echo y …
Run Code Online (Sandbox Code Playgroud)

python django amazon-ec2 amazon-web-services boto3

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

如何在 django admin 中对不存在的字段进行排序/排序

如何在 django admin 中对不存在的字段进行排序。基本上我有服务器和应用程序模型,第三个关系模型将它们链接起来。我看到了您的回复,但不确定将您提到的代码放在哪里。这是模型和admin.py

# Model.py File
class Server(models.Model):
name = models.CharField(max_length=100,  unique=True)
operating_system = models.CharField(max_length=20, choices=constants.OPERATING_SYSTEMS.items())

@property
def number_of_apps(self):
    return ServerApplicationRelationship.objects.filter(server=self).count()

class Application(models.Model):
    name = models.CharField(max_length=100,  unique=True)
hosted_on = models.ManyToManyField(Server, through='ServerApplicationRelationship', blank=True,)

@property
def number_of_servers(self):
    return ServerApplicationRelationship.objects.filter(app=self).count()
# number_of_servers.server_field = 'server__count'

class ServerApplicationRelationship(models.Model):
    server = models.ForeignKey(Server, blank=True, )
    # server_tag = models.ForeignKey(Server, through_fields= 'tags')
    app = models.ForeignKey(Application, blank=True)

# Admin.py file
@admin.register(Application)
class ApplicationAdmin(admin.ModelAdmin):


    inlines = [ApplicationInLine]
    list_display = ['name', 'number_of_servers']
    list_display_links = ['name', 'number_of_servers']

    ordering = ('number_of_servers', 'name') …
Run Code Online (Sandbox Code Playgroud)

django

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

Django Admin List_display更改单元格的背景颜色

如果status = closed,则尝试更改背景颜色.当我尝试下面的代码时,结果以html而不是实际颜色显示.

##Mode.py


from django.template.defaultfilters import truncatechars  # or truncatewords

class TimeStampModel(models.Model):
    created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Created')
    updated = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name='Modified on')

    class Meta:
        abstract = True


class Task(TimeStampModel):

minor = 'MINOR'
normal = 'NORMAL'
important = 'IMPORTANT'
critical = 'CRITICAL'

SEVERITY = (
    (minor, 'Minor'),
    (normal, 'Normal'),
    (important, 'Important'),
    (critical, 'Critical'),
)

low = 'LOW'
high = 'HIGH'
PRIORITY = (
        (low, 'Low'),
        (normal, 'Normal'),
        (high, 'High'),
        )


new = 'New'
in_progress = 'In_Progress'
needs_info = 'Needs …
Run Code Online (Sandbox Code Playgroud)

django list django-admin display

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

有条件地更改django admin list_display中单元格的背景颜色

希望找到一种优雅的方法来有条件地更改 list_filter 中单元格的背景颜色。如果我没有条件,它适用于一种状态,但需要根据不同的状态更改背景颜色。

Django 1.10 版,

蟒蛇 3.5


模型.py

class PlayBook(TimeStampModel):

minor = 'MINOR'
normal = 'NORMAL'
important = 'IMPORTANT'
critical = 'CRITICAL'

SEVERITY = (
    (minor, 'Minor'),
    (normal, 'Normal'),
    (important, 'Important'),
    (critical, 'Critical'),
)

low = 'LOW'
high = 'HIGH'
PRIORITY = (
        (low, 'Low'),
        (normal, 'Normal'),
        (high, 'High'),
        )


new = 'New'
in_progress = 'In_Progress'
needs_info = 'Needs Info'
postponed = 'Postponed'
closed = 'Closed'
STATUS= (
        (new, 'New'),
        (in_progress, 'In Progress'),
        (needs_info, 'Needs Info'),
        (postponed, 'Postponed'),
        (closed, …
Run Code Online (Sandbox Code Playgroud)

django list django-admin display

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

如何在django admin中显示人的时间(x天前或现在)?

如何在django admin中显示在facebook / twitter中使用的时间/日期格式?

from django.db import models
from datetime import datetime


class Course(models.Model):

      date = models.DateTimeField(auto_now_add=True)
      title = models.CharField(max_length=255)
      description = models.TextField()

      def get_date(self):
          time = datetime.now()
          if self.date.day == time.day:
              return str(time.hour - self.date.hour) + " hours ago"
          else:
              if self.month == time.month:
                   return str(time.day - self.date.day) + " days ago"

          return self.date

      def __str__(self):
          return self.title
Run Code Online (Sandbox Code Playgroud)

管理员

  from django.contrib import admin
  from .models import Course   

  @admin.register(Course)
  class CourseAdmin(admin.ModelAdmin):
      list_display = ('title', 'description', 'get_date',)
Run Code Online (Sandbox Code Playgroud)

尝试了多种组合以导入日期/时间,但仍然出现错误,如图所示。 在此处输入图片说明

如果我使用get_date:我得到以下错误:

AttributeError …
Run Code Online (Sandbox Code Playgroud)

django datetime django-admin

2
推荐指数
3
解决办法
1700
查看次数

如何使用多处理来循环浏览一个大的 URL 列表?

问题:检查超过 1000 个 url 的列表并获取 url 返回码 (status_code)。

我的脚本有效,但速度很慢。

我认为必须有一种更好的、pythonic(更漂亮)的方式来做到这一点,在那里我可以产生 10 或 20 个线程来检查 url 并收集响应。(IE:

200 -> www.yahoo.com
404 -> www.badurl.com
...
Run Code Online (Sandbox Code Playgroud)

输入文件:Url10.txt

www.example.com
www.yahoo.com
www.testsite.com
Run Code Online (Sandbox Code Playgroud)

....

import requests

with open("url10.txt") as f:
    urls = f.read().splitlines()

print(urls)
for url in urls:
    url =  'http://'+url   #Add http:// to each url (there has to be a better way to do this)
    try:
        resp = requests.get(url, timeout=1)
        print(len(resp.content), '->', resp.status_code, '->', resp.url)
    except Exception as e:
        print("Error", url)
Run Code Online (Sandbox Code Playgroud)

挑战: 通过多处理提高速度。


多处理

但它不工作。我收到以下错误:(注意:我不确定我是否正确实现了这一点) …

python multithreading multiprocessing python-multiprocessing

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

AWS SDK - 如何使用 Boto3 设置 VPC 名称标签

创建 vpc 时如何使用 AWS 开发工具包指定 VPC 名称标签?我尝试了此处所示的多种选项,但没有成功。

以下是我如何使用 python、boto3 SDK 创建 VPC。

import os
import boto3
import time    
....
....
print('Creating VPC')
# Create new VPC environment
vpc = client.create_vpc(CidrBlock='10.0.0.0/16', InstanceTenancy='default')
client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], EnableDnsSupport={'Value': True})
client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], EnableDnsHostnames={'Value': True})
Run Code Online (Sandbox Code Playgroud)

目前,它创建没有名称标签的 vpc。

我尝试在创建 vpc 期间或修改它时指定标签,如下所示,但没有一个选项起作用。

vpc = client.create_vpc(CidrBlock='10.0.0.0/16', InstanceTenancy='default', Tags="myvpcnametag")
client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], Tags="myvpctag")
Run Code Online (Sandbox Code Playgroud)

amazon-ec2 amazon-web-services amazon-vpc boto3 aws-vpc

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