【发布时间】:2021-02-02 20:38:40
【问题描述】:
我知道我对标题的解释很糟糕,看我有一个简单的聊天应用程序,用户可以在其中发送文本/音频/视频/图像并让我呈现这些消息我有一个检查消息类型并呈现它的方法因此,如果它是文本,那么我将在模板中将 safe 设置为 False,否则我将显示该函数将为我提供的 HTML 代码
我真正想要的是:管理面板给我消息 text[:50] 如果是文本,如果是音频,那么我可以对其进行音频预览,如果是图像、视频或文件,那么它将给出我的网址。 有什么办法吗?
这是我的文件,因此您可以更好地理解我在说什么:
models.py:
class Message(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
text = models.TextField(blank=True, null=True)
video = models.FileField(upload_to="chat/room/vid", blank=True, null=True)
image = models.FileField(upload_to="chat/room/img", blank=True, null=True)
file = models.FileField(upload_to="chat/room/file", blank=True, null=True)
audio = models.FileField(upload_to="chat/room/aud", blank=True, null=True)
is_read = models.BooleanField(default=False)
date = models.DateTimeField(auto_now_add=True)
def content(self):
if self.text:
return self.text
elif self.video:
return f"""
<video width="320" height="240" controls>
<source src="{self.video.url}" type="video/mp4">
<source src="{self.video.url}" type="video/mov">
<source src="{self.video.url}" type="video/wmv">
<source src="{self.video.url}" type="video/avi">
<source src="{self.video.url}" type="video/avchd">
Your browser does not support the video tag.
</video>
"""
elif self.image:
return f'<img src="{self.image.url}" alt="">'
elif self.file:
return f'<p><a href="{self.file.url}" download><i class="fas fa-download"></i> {self.filename()}</a></p>'
elif self.audio:
return f"""
<audio controls>
<source src="{self.audio.url}" type="audio/pcm">
<source src="{self.audio.url}" type="audio/wav">
<source src="{self.audio.url}" type="audio/aiff">
<source src="{self.audio.url}" type="audio/mp3">
<source src="{self.audio.url}" type="audio/aac">
<source src="{self.audio.url}" type="audio/ogg">
<source src="{self.audio.url}" type="audio/flac">
<source src="{self.audio.url}" type="audio/wma">
Your browser does not support the audio element.
</audio>
"""
else:
return self.text
这是我的 HTML 模板:
{% for room_message in room_messages %}
{% if room_message.text %}
<p>{{ room_message.content }}</p>
{% else %}
{{ room_message.content|safe }}<br>
{% endif %}
{% endfor %}
现在问题出在哪里?在我的管理面板中,如果没有文本,它会给我“-”作为消息内容
我的 admin.py:
from django.contrib import admin
from .models import Room, Area, Message
admin.site.register(Room)
admin.site.register(Area)
@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
'''Admin View for Message'''
list_display = ('user','room', 'user', 'is_read', 'text')
readonly_fields = ('date',)
【问题讨论】:
-
看起来您在
list_display中设置了text,但没有为video、audio等设置其他字段。您可以尝试包括这些字段,看看会发生什么? -
当我这样做时,管理页面变得非常不干净,我有 4 列并排在一起,只使用了其中的一个,我试图找到一种更清洁的方式,音频也让我下载链接而不是播放它,但图像和视频还可以
标签: python html django django-admin django-admin-actions