需要截断管理列表显示中的文本
管理模型中有以下内容,但仍显示全文。
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 个字符加上...
运行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)
尝试谷歌搜索问题,一些人建议切换到我不知道该怎么做的开发分支.
谢谢
在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中显示这些字段.
尝试运行示例代码,但出现此错误”
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)
安装了以下
不知道还有什么要检查的。如果您有任何建议,那就太好了
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) 如何在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) 我需要通过 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) 如何在 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) 如果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) 希望找到一种优雅的方法来有条件地更改 list_filter 中单元格的背景颜色。如果我没有条件,它适用于一种状态,但需要根据不同的状态更改背景颜色。
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 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) 问题:检查超过 1000 个 url 的列表并获取 url 返回码 (status_code)。
我的脚本有效,但速度很慢。
我认为必须有一种更好的、pythonic(更漂亮)的方式来做到这一点,在那里我可以产生 10 或 20 个线程来检查 url 并收集响应。(IE:
200 -> www.yahoo.com
404 -> www.badurl.com
...
Run Code Online (Sandbox Code Playgroud)
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
创建 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) django ×6
django-admin ×5
display ×3
list ×3
amazon-ec2 ×2
boto3 ×2
python ×2
admin ×1
amazon-vpc ×1
aws-vpc ×1
datetime ×1
spacemacs ×1