Get image src and alt attribute in Sitecore 6? - sitecore

I use the following to get, for instance, the header of the current page;
Header = Sitecore.Context.Item["Header"]
But how would i go about getting the src url of a image field?
PictureSrc = Sitecore.Context.Item["MyImage"]

You will want to look at leveraging the Sitecore.Resources.Media.MediaManager to get the URL to a media library item.
Before you get there, get the field from the item and cast it to a FileField. Once you have a FileField you can get access to the MediaItem.
Item item = Sitecore.Context.Item;
Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)item.Fields["MyImage"]);
string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem);
string altText = imgField.Alt;
Link to Sitecore Media Item

Related

Updating FilesField() django with S3

I want to update the FileField with new file. All the files are saved on S3.
models.py
class PrescriptionMediaStorage(S3Boto3Storage):
location = settings.AWS_PRESCRIPTION_MEDIA_LOCATION
file_overwrite = True
custom_domain = f'{settings.AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
class UploadPrescription(models.Model):
image = models.FileField(storage=PrescriptionMediaStorage())
For createview i used:
prescription_obj = UploadPrescription.objects.create(image=image)
prescription_obj.image = prescription_obj.image.url
prescription_obj.save()
For Updateview i tried this but it's giving error
UploadPrescription.objects.filter(id=prescription_id).update(image=image)
prescription_obj = UploadPrescription.objects.get(id=prescription_id)
prescription_obj.image = prescription_obj.image.url
prescription_obj.save()
when i tried to open the saved url in image field i got below message
<Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>media/prescription/1STUSERS-BANNER.jpg</Key>
<RequestId>5D1396D45DF8E1F7</RequestId>
<HostId>0Chq0gedgy/o8942zo5JEz2Tp4iE6df51v0o5iY6GnNGKH3bOXb1ee9XKupKY5GYCfvankTGXHI=
</HostId>
</Error>
Okay, not sure what you are doing here, buth this is how to properly use an ImageField - try these changes and see if they resolve your issue:
Don't write a url to the image field of your model. Assuming <the_image_file> is a valid image file, all you need is one line:
views.py
# creates and saves an UploadPresecription with the given image:
prescription_obj = UploadPrescription.objects.create(image=<the_image_file>)
To use the image in an <image> div, you can access the url like so:
template.html
<image src="{{prescription_obj.image.url}}" />
To replace the image on the prescription_obj, you can simply do this:
views.py
prescription_obj = UploadPrescription.objects.get(id=<the_id>)
prescription_obj.image = <the_new_image_file>
prescription_obj.save()
Note, depending on your settings, your S3 bucket may retain a version of the old image but it will no longer be associated with the updated prescription_obj.
Read about the ImageField here:
https://docs.djangoproject.com/en/3.1/topics/files/

Handle a click event in django-tables2

I am starting to use django-tables2 and I have added a column which should allow user to delete a record when the user clicks on the button. The code looks as follows:
class ReviewTable(tables.Table):
delete = tables.LinkColumn('review_delete', args=[tables.A('pk')], orderable=False,
empty_values=(), verbose_name='')
def render_delete(self, record):
url = static('remove.png')
href = '#'
return mark_safe('')
This basically enders the image fine in a column but all I can do is set the link to it. How can I get it to call some method where I can then filter by the record ID and delete the relevant record? Is this the correct way to do this?
When you generate HTML from code, you still have access to onclick events.
return mark_safe(''.format(href, url)
Now your delete_action can be a javascript function that gives you more control. Generated HTML is basically just any old type of HTML, so you can still use jquery event handlers with it
BTW, please note how string formatting has been used in stead of concatenation. This is more pythonic

Facebook Graph api profile picture URL

I'm trying to display the profile pic of the logged in user but for some reason the url gets changed. This is the function i've put together
function testAPI() {
FB.api('/me','GET',{"fields":"picture{url},name"},function(response) {
var url = response.picture.data.url;
console.log(url);
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img href="'+response.picture.data.url+'"/></figure>');
console.log(document.getElementById('status').innerHTML);
});
}
the first console log returns:
"https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p50x50/12036592_10153768750487873_8195289030629933305_n.jpg?oh=5488c4b312a1b077b68243a7998d217e&oe=56BA5DE5&gda=1454718467_89331767e8555ed196c5559340774fbb"
the second returns the correct inner html as the users name diplays but its adding amp; after the & symbols in the url so the profile pic isn't displaying. No idea how to fix this. Any help would be great thanks.
You have incorrect <img/> tag syntax, you should be using src instead of href
Change:
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img href="'+response.picture.data.url+'"/></figure>');
To:
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img src="'+response.picture.data.url+'"/></figure>');

Sitecore PDF Not Downloading

I have a couple of unversioned PDFs in the media library... when I try opening them up from their URLs, it says "Layout not found". When I assign a layout (any layout), it just doesn't render anything.
I've added forcedownload=true to the media library section of the web.config... is there anything I'm missing? I thought this was supposed to download by default
http://testsite.org/sitecore/media%20library/pdfs/Publications/Periodicals/Test
The URL above basically doesn't work
Links to items in the media library are usually prefixed with /~/media/, unless you have changed the value of Media.MediaLinkPrefix in config. The link should be something like:
http://testsite.org/~/media/pdfs/Publications/Periodicals/Test.pdf
Make sure you are generating the URLs using MediaManager.GetMediaUrl()
FileField fileField = Sitecore.Context.Item.Fields["File Field"];
var mediaItem = new MediaItem(fileField.MediaItem);
string url = Sitecore.StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(fileMediaItem));
Always use LinkManager.GetItemUrl() for items and MediaManager.GetMediaUrl() for media items to generate Sitecore URLs.
http://briancaos.wordpress.com/2012/08/24/sitecore-links-with-linkmanager-and-mediamanager/
http://corecompetency.tohams.com/index.php/linking-to-an-image-or-file-in-the-media-library/
You don't have to assign a layout to media item. Make sure you add "/" prefix before the url. Ex: site/~/media/path to pdf.ashx.
Also make sure you have media files published.
//below is the code to specify an Image URL
MediaItem mediaItem = new MediaItem(Sitecore.Context.Database.GetItem("Path"));
if (mediaItem != null)
{
imgBtn.ImageUrl = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
imgBtn.AlternateText = mediaItem.Alt;
}

cloudinary direct upload form is not valid, need to re upload

i am using django and cloudinary direct upload to upload iamges
it is working if the form is valid.
but if my form is not valid, my page reloaded, and then the form will ask the user to upload the image again.
any way to solve this?
my code is attached below.
since i use direct upload, after an image is uploaded. it will be displayed immediately on the front end.
but when the form is invalid and the form is refreshed, the image is gone. ( after your latest update, it is true i do not need to re upload the photo again. but the photo is gone. how to display that again?)
thanks.
<script>
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
var imag_var = $.cloudinary.image(data.result.public_id, {
format : data.result.format,
version : data.result.version,
transformation : 'form_preview'
});
$('.preview').html(imag_var);
$('.status_value').text('Uploaded:' + data.result.public_id);
$('#id_cover_image').val(data.result.public_id);
return true;
});
$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) {
$('.progress').attr({
style : "visibility:show",
});
$('.status_value').text('Uploading...');
});
</script>
The Cloudinary javascript plugin puts the preloaded resource URI in a hidden field.
See here.
From the above one sees that if the field already exists the javascript plugin will populate it. Otherwise, it will create it.
In order to retain that URI across invalid form submissions you should create a hidden field named according to the field name you specified for cloudinary_direct_upload_field and which is populated with the value from the failed submission.
Another way to work around the issue would be to submit the form using an AJAX call. That way the data on page is retained even if validation failed and resubmission is possible. See here for an example of how that may be done.
EDIT:
Version 1.0.12 of the Cloudinary Python client library now adds the hidden field when needed out of the box so resubmissions should work. See the change log.
EDIT 2:
In order to regenerate a preview image in case of form validation error you can add something like this to the javascript code you run on page load (assuming the field name in the form is "image"):
//If form validation failed have the posted preloaded URI from the earlier
//submission so we can show preview
//pull the value from the hidden field
var imageUri = $('#direct_upload input[name="image"]').val();
//preloaded image URI structure
//{resource_type}/{type}/v{version}/{filename}#{signature}
var regex = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
//if there is value and it matches the pattern:
if (imageUri && regex.test(imageUri)) {
var uriParts = regex.exec(imageUri);
var version = uriParts[3];
var filename = uriParts[4];
//reconstruct a viable source
var src = "v" + version + "/" + filename;
//generate a cloudinary image tag and add it to the 'preview' div
$(".preview").append(
$.cloudinary.image(src, {
transformation: "form_preview" //your named transformation
})
);
}