I am using audiofield in my Django application to allow upload of a .wav file and render it for play.
I am able to succesfully implement it for one upload at a time, showing the player for a single uploaded file
The code is :
def bottom_player(self):
if self.a_file:
file_url = settings.MEDIA_URL + str(self.a_file)
Html5_string = '<div style="position:fixed; top:5em; right:5em; height: 5em; background-color:white;"><audio controls><source src="%s" type="audio/mpeg">%s Your browser does not support the audio element.</audio><br><h3>Audio player will adjust to your screen</h3></div>' % (file_url, os.path.basename(self.a_file.name))
return Html5_string
bottom_player.allow_tags = True
Now, I want to show separate player for multiple uploaded files, so I have created another table having a_file field for upload and a SQL trigger to copy the newly created a_file field value to the previous a_file column in comma separated format
audio-file-NACHY-1698934831.wav, ./audio-file-ABGYT-1890930931.wav
To parse this a_file column values and then show player for each path, the code looks like:
def bottom_player(self):
if self.a_file:
audiolist = self.a_file
filenamelist = audiolist.split(",")
filenamelist
for filename in filenamelist:
file_url = settings.MEDIA_URL + str(filename)
Html5_string += '<div style="position:fixed; top:5em; right:5em; height: 5em; background-color:white;"><audio controls><source src="%s" type="audio/mpeg">%s Your browser does not support the audio element.</audio><br><h3>Audio player will adjust to your screen</h3></div>' % (file_url, os.path.basename(self.filename))
return Html5_string
bottom_player.allow_tags = True
I get "None" in my bottom player field in the Django page.
Related
I wanted to get user input from user using Tkinter's Entry something like this
from Tkinter import *
top = Tk()
label = Label(top, text="Enter your bio")
entry = Entry(top, bd = 2)
def create_new():
new_file = open('file.txt', 'w+')
user_input = str(entry) # I ALSO TRIED WITHOUT str()
new_file.write(user_input) #still doesn't work
button = Button(top, text = "SAVE", fg ="red", command=create_new)
label.pack()
entry.pack()
button.pack()
top.mainloop()
When I add my info in the field and hit SAVE, it does create a new file.txt but it doesn't write my info into the file.txt
file.txt only has some numbers like these
.22775808
.22710272
.22382592
etc...
Any ideas on how can I fix this? Also what do these numbers mean and why are they here?
from tkinter import *
top = Tk()
label = Label(top, text="Enter your bio")
entry = Entry(top, bd = 2)
def create_new():
new_file = open('file.txt', 'w+')
user_input = (entry).get() # I ALSO TRIED WITHOUT str()
new_file.write(user_input) #still doesn't work
button = Button(top, text = "SAVE", fg ="red", command=create_new)
label.pack()
entry.pack()
button.pack()`enter code here`
top.mainloop()
You aren't writing the contents of the Entry, you're writing the Entry itself - which from Python's point of view is just the randomly-generated name of the actual widget which lives in the embedded Tcl/Tk interpreter. Use entry.get() for the actual contents.
You're also forgetting to close the file after you write to it, so anything you do manage to write may not show up immediately.
I am reading a treelist of images like this:
var images = new List<Image>();
MultilistField mlf = context.Item.Fields["Images"];
foreach (var id in mlf.TargetIDs)
{
var item = (MediaItem)Sitecore.Context.Database.GetItem(id);
images.Add(new Image
{
Url = MediaManager.GetMediaUrl(item),
Alt = item.Alt,
Extension = item.Extension,
});
}
The Url and Extension is correct, but I get no Alt text. I want to read the Alt text that is directly on the item in the media library and not in an ImageField.
Any suggestions is appreciated
Your code is correct.
Check if alt text is set on the proper language version of your media item. And check if your media items are published.
Remember that media items (as all the other items in Sitecore) may have versions, so check if the correct version is in your web database.
Update 2:
I am still fighting to get the Icon save on the server.
Here what I am doing:
Item item = Sitecore.Context.Database.GetItem(imageId);
var imageIconUrl = Sitecore.Resources.Images.GetThemedImageSource(item.Appearance.Icon, ImageDimension.id32x32);
if (!string.IsNullOrEmpty(imageIconUrl))
{
// download the icon from the url
var iconFullPath = "e:\\pngIcons\\excelIcon.png";
var webClient = new System.Net.WebClient();
var downloadPath = "http://serverName/" + imageIconUrl;
webClient.DownloadFile(downloadPath, iconFullPath);
}
The variable downloadPath contains following string:
http://serverName/sitecore/shell/themes/standard/~/media/E503BA48C89B422D8400393F1C7086A7.ashx?h=32&thn=1&w=32&db=master
At the end what I can see is a png file but there is nothing in it. I also copy the string I get in variable downloadPath and pasted it in browser and I can see the Icon as follow:
Please let me know what I am doing wrong. Or How I can save the Icon. Thanks!!
Original Question:
The sitecore media item has a field "Media". I am talking about this:
I want to access this field. And the reason is:
If I access it with e.g. item.GetMediaStream() then I will get the complete file. I just want to save this little icon some how on the server. Is it possible ?
To get the icon/thumbnail you can use
var icon = Sitecore.Resources.Media.MediaManager.GetThumbnailUrl(mediaItem);
To get the url of the thumbnail.
If you want the stream of the thumbnail you need to use the MediaData object. Like this:
var mediaItem = new MediaItem(item)
var mediaData = new MediaData(mediaItem);
var iconStream = mediaData.GetThumbnailStream();
if (iconStream.Length < 0)
{
// The stream is empty, its probably a file that Sitecore can't
// generate a thumbnail for. Just use the Icon
var icon = item.Appearance.Icon;
}
This will get the icon or thumbnail of the actual media blob that is attached to the media item. If you just want the icon of the Sitecore item, then use Martins method.
If the stream is empty, then Sitecore can't generate a thumbnail for it, so you can just use the icon file for the media item template. item.Appearance.Icon
Appearance section (of Standard Template) has a field called Icon - this is where you can modify icon for the item. There is also a field called Thumbnail - your excel icon is sitting there
You can access the field programmatically, just mind that it starts with two underscores: __Icon:
var iconField = item.Fields["__Icon"];
var thumbnailField = item.Fields["__Thumbnail"];
Update: As you asked, below is the code that saves either of fields into the file on a drive. I have tested the code and confirm successfully stores icon from thumbnail field into the file:
string mediaItemPath = "/sitecore/media library/Files/ExcelFile";
string mediaFiedlName = "Thumbnail"; // also can be "__Icon"
var item = Sitecore.Context.Database.GetItem(mediaItemPath);
var iconField = item.Fields[mediaFiedlName];
if (iconField.HasBlobStream)
{
var thumb = (ImageField)iconField;
var bl = ((MediaItem)thumb.MediaItem).InnerItem.Fields["blob"];
Stream stream = bl.GetBlobStream();
byte[] buffer = new byte[8192];
using (FileStream fs = File.Create("D:\\you_file_name.ico")) // change your path
{
int length;
do
{
length = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, length);
}
while (length > 0);
fs.Flush();
fs.Close();
}
}
Update 2: If that does not help then I would advise to look around the way how that icon gets generated on Media field in Sitecore. In the worst case you may do the following - right click that icon and see its url. You will have something similar to what I assign to variable below:
string url = "http://test81/sitecore/shell/Applications/-/media/B4F61650CBE84EE396649602C0C48E1B.ashx?bc=White&db=master&h=128&la=en&mw=640&thn=1&vs=1&ts=b8046903-ae57-4f9d-9dd5-b626ee5eee90";
Of course your URL should have your hostname and media prefix and the rest of parameters. Then use Webclient with that modified URL:
WebClient webClient = new WebClient();
webClient.DownloadFile(url, "e:\\you_file_name.ico");
Not ideal, but may work. Note, that the code above should work in a context of already logged user, so you need to authorise you Webclient prior that (many articles on S.O. how to do that).
Please reply if that approach has worked for you (I've spent decent time writing and testing that code in debugger, so would want to know whether that helped)
Currently, I am working on a GUI text editor with python and tkinter. Thanks to the great people at SO (thank you Rinzler), I have managed to modify the font of the text. However, I am unable to save the font and font size to the txt file.
I know that this should be possible as Notepad can modify and save a txt file with a specified font.
This is the code to save to a file:
def file_saveas():
filename = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
if filename is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
text2save = str(textPad.get(1.0, END)) # starts from `1.0`, not `0.0`
filename.write(text2save)
filename.close()
print filename
This is the code (courtesy of Rinzler) to change the font:
def choose_font():
global root, textPad # I hate to use global, but for simplicity
t = Tkinter.Toplevel()
font_name = Tkinter.Label(t, text='Font Name: ')
font_name.grid(row=0, column=0, sticky='nsew')
enter_font = Tkinter.Entry(t)
enter_font.grid(row=0, column=1, sticky='nsew')
font_size = Tkinter.Label(t, text='Font Size: ')
font_size.grid(row=1, column=0, sticky='nsew')
enter_size = Tkinter.Entry(t)
enter_size.grid(row=1, column=1, sticky='nsew')
# associating a lambda with the call to text.config()
# to change the font of text (a Text widget reference)
ok_btn = Tkinter.Button(t, text='Apply Changes',
command=lambda: textPad.config(font=(enter_font.get(),
enter_size.get())))
print font
ok_btn.grid(row=2, column=1, sticky='nsew')
done = Tkinter.Button(t, text='Get rid of Pushy!', command=t.destroy)
done.grid(row=4, column=1, sticky='nsew')
# just to make strechable widgets
# you don't strictly need this
for i in range(2):
t.grid_rowconfigure(i, weight=1)
t.grid_columnconfigure(i, weight=1)
t.grid_rowconfigure(2, weight=1)
Finally, this is the code that reads the font and other configuration information:
font = (fontname, size)
textPad.config(
borderwidth=0,
font=font ,
foreground="green",
background="black",
insertbackground="white", # cursor
selectforeground="blue", # selection
selectbackground="#008000",
wrap="word",
width=64,
undo=True, # Tk 8.4
)
I have searched the internet without coming up with any answers as to why the font and text size are not saved. Any help would be greatly appreciated.
I am using python 2.7.7 , Tkinter, and this is being run on Windows 7.
Any help manipulation an rtf file would also be helpful (currently, I see the tags and not the end format).
There is no support for this in tkinter. You will have to pick a file fomat that supports fonts (rtf, .docx, .html, etc), convert the data in the widget to this format, and then write it to a file.
Notepad can only have a custom font and size for its editor window, it doesn't save it to the file, it just remembers the user's custom settings, and applies them to its window when you use it.
The tkinter text widget can be horrible to save formatting to another format, I've tried converting it to XML to save to a .docx but I haven't been successful. I have used my own format which is a plain text file with an 'index' of the tkinter Text widget tags at the start and their line&column indexes, then a marker for where the document begins, then the document. This cannot hold images though, and it opens with all the formatting index when you open it in another word processor.
XML is ideal for opening and saving the tkinter text contents - use an xml parser to open, then wite a recursive function to add text with tags as you go. (If you want rich text, this, like xml, is an iterative format - elements inside elements, so could be done like i'm describing below for xml, but you need to write your own rich text parser)
import xml.etree.ElementTree as etree
e = etree.fromstring(string)
#create an element tree of the xml file
insert_iter(e)
#call the recursive insert function
def insert_iter(element):
#recursive insert function
text.insert("end", element.text, tagname)
#insert the elements text
for child in element:
insert_iter(child)
#iterate through the element's child elements, calling the recursive function for each
text.insert("end", child.tail, tagname)
#insert the text after the child element
text.tag_config(tagname, **attrib)
#configure the text
'attrib' is a dictionary eg. {"foreground":"red", "underline":True} would make the text you insert have red font and black underline,
'tagname' is a random string, and needs to be automatically created by your program
To save the file, make a function to do the reverse. I wouldn't bother with using the xml library for this - as tkinter outputs the correct format, just write it manually, but make sure to escape it
from xml.sax.saxutils import escape
data = text.dump("1.0", "end")
print(data[0:500]) # print some of the output just to show how the dump method works
output = ''
#get contents of text widget (including all formatting, in order) and create a string to add the output file to
for line in data:
if line[0] == "text":
#add the plain text to the output
output += escape(line[1])
elif line[0] == "tagon":
#add a start xml tag, with attributes for the given tkinter tag
name = 'font'
attrib = ""
tag = #the dictionary you stored in your program when creating this tag
for key in tag:
attrib += "%s='%s' "%(key, escape(tag[key]))
output += "<%s %s>"%(name, attrib)
elif line[0] == "tagoff":
#add a closing xml tag
output += '</%s>'%name
I'm streaming small videos from django view:
def play(request):
filename = settings.VIDEO_URL + extra_path
wrapper = FileWrapper(file(filename, "rb"))
response = HttpResponse(wrapper)
response['Content-Type'] = 'video/mp4'
response['Content-Length'] = os.path.getsize(filename)
return response
And have html code like this:
<video style="display: inline-block; width:500px; height:700px;">
<source type="video/mp4" src="play?v=1111">
<video>
Everything works fine, but i need to get video screenshot from JS for drawing above the video frame in canvas. I'm using it:
var video = document.querySelector('video');
var canvas = document.getElementById('canvas-bg');
var context = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
context.fillRect(0, 0, w, h);
context.drawImage(video, 0, 0, w, h);
It works good in Chrome, but i always getting empty context in Safari after context.drawImage(...).
Before django i used php script, like in this link: Streaming an mp4 through a php file progressively, and safari well worked.
Also if i'm changing:
<source type="video/mp4" src="play?v=1111">
to:
<source type="video/mp4" src="/static/video/myfunnyvideo.mp4">
I can get video context in safari! Why? Can anyone help me please.
Don't know why it happens, maybe some http headers are wrong, but I've found other solution for nginx server (for Apache you can use XSendFile):
def play(request):
extra_path = "myfunnyvideo.mp4"
filename = settings.VIDEO_URL + extra_path
response = HttpResponse(mimetype='video/mp4')
response['Accept-Ranges'] = 'bytes'
response['X-Accel-Redirect'] = filename
return response
and in nginx config (/etc/nginx/sites-available/your-site):
location /videos/ {
internal;
alias /var/www/some-folder/protected-folder;
}