how to display in models img to html in django - html

I tried to display to html changeable profile image with admin. can someone explain please
models in Portfolio app :
class ProfileImage(models.Model):
profile = models.ImageField(("Profile image"), upload_to=None, height_field=None, width_field=None, max_length=None)
this is base html in template folder (i tried this one) :
<img src="{{ portfolio.models.ProfileImage.progile.url }}" alt="profile"><br />

You should first configure your model to store profile pictures. Your ProfileImage model looks correct, but you need to specify where the images should be uploaded using the upload_to argument of ImageField.
Include the model in your admin form by using a ModelForm or manually adding it to the admin's fields list.
In your HTML template, you can display the image using the url attribute of your template's ImageField object.
You have an error in your HTML above, it should be profile.url and not portfolio.models.ProfileImage.profile.url:
<img src="{{ profile.image.url }}" alt="profile">

Related

laravel blade : image display does not work

I want to display an image in view file.
I tried several lines of code.
This is a part of my controller
$filename = time().'.'.$request->logo->extension();
$partner->logo = $request->logo->storeAs(
'partnerLogos',
$filename,
'public'
);
I linked storage folder.
The file is saved in : storage/app/public/partnerLogos/1665127813.jpg
In My view file, I tried 4 different ways to display the image, it only works when I put the file name.
<img src="{{ asset('storage/partnerLogos/'.$partner->logo) }}" alt="">
Result : http://localhost:8000/storage/partnerLogos
{{ asset('storage/partnerLogos/'.$partner->logo) }}
Result : /partnerLogos/1665127813.jpg
<?php print_r($partner->logo); ?>
Result : partnerLogos/1665127813.jpg
<img src="{{asset('storage/partnerLogos/1665127813.jpg')}}" alt="">
Result : image is displayed
If you are storing the images in storage directory, consider that you will not access them via a direct address, since It is not stored in public directory!
You should add images in storage/app/public directory and after that run
php artisan storage:link
It creates symbol link, so the images will be accessible by asset.
for more information check this example

how to display images from nestjs server to Angular

When I upload a product from Angular side, It Post the product with imagepath, and the image is getting stored in the NestJs folder also, but I can not display product with it's image. The product is displaying at frontend but without it's image that is referenced and saved at the backend.
Anguar FrontEnd Code .ts
export class BooksComponent implements OnInit {
BookForm = new FormGroup({
_id: new FormControl(''),
name: new FormControl(''),
author: new FormControl(''),
price: new FormControl(''),
genres_name: new FormControl(''),
coverimage: new FormControl(''),
});
results?: Book[] = [];
searchedText: string = '';
constructor(
private readonly apiService: ApiService,
private router: Router
) {}
ngOnInit() {
this.apiService.getallbooks().subscribe((data) => {
this.results = data;
console.log(this.results);
});
}
Frontend html code.I'm getting all the information but not the image, here I'm providing src in img tag to display images
<div class="grid" *ngFor="let result of results">
<div class="blog-card spring-fever" style="padding: 0.5rem; z-index: 100">
<img
class="image"
src="http://localhost:3000/{{ result.coverimage }}"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
This is the information of the Product that is coming from the backend
And when I try like this src="{{result.coverimage}}" or [src]="result.coverimage" I got error localhost:4200/assets/imagename not found(404). well that is obvoius!. because there is not such path, 4200 is for Angular. but I'm uploading the images at the backend assets folder which is located at localhost:3000/assets/, and we always upload files to backend for dynamic approach from database
In your highlighted part of your post you ask how to display the image, i.e you suspect the problem is in the frontend. However there is a missing part from the provided context. In the line where the html magic happens (The img tag src attribute).
There you are string interpolating a property called coverimage under the results object. We do not see what is inside the coverimage from your backend response in the frontend screenshot. If it is an id of a document then it will not be parsed correctly. The src attribute accepts:
APNG, AVIF, GIF, JPEG, PNG, SVG, and WebP. Or base64 (which seems not the case here).
When you have the image with one of the acceptable supported formats as stated in MDN correct you can map the property to the src attribute either via
1- string interpolation:
<img src="{{imagePath}}" />
2- property binding:
<img [src]="imagePath" />
The second way is more popular, but both work fine.
PS: it is a best practice and accessibility recommended to populate the alt="" property
If you are struggling to display the images coming from server, like I was, or you are struggling with the data that is coming NestJs. Then this might work for you as it worked for me.
So in my case I had a list of books and each book has path for its image. I was using ngFor and set the image src with the path. That is the right way. But the images were not visible and Network was showing images as text/html type. The actual issue here was not the type,the actual issue was in my URL.I had a folder in NestJs server by the name of assets,that is preset at root, and I had set the path for the images(in NestJs file upload code), like this ./assets/. That is also the correct way to set the destination folder.I was able to see the images at browser like this http://localhost:3000/imagename.png,and that means my server configured to server/serve my images over root URL that's why I can access them http://localhost:3000/imagename.png. But my api was returning images in a format that contains ./assets/ in the URL.
So with the following code
<div *ngIf="result.coverimage">
<img
class="image"
src="http://localhost:3000/{{ result.coverimage }}"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
</div>
I am assuming that I'm hitting the Url like this http:localhost:3000/imagename.png. But actually Angular was seeing the URL like this http:localhost:3000/./assets/imagename.png. And this is note the correct URL Format. Urls don't work with . or ,.Also becasue my server is configured at root, this urlhttp;//localhost:3000/assets/imagename.png is also wrong.And root means that, whatever the thing is set at root, that is directly access able after your server's port number. Example http://localhost:YourServerPortNumber/TheThing_Set_at_Root.
So the solution for this issue is the following
src="http://localhost:3000/{{
result.coverimage.replace('./assets/', '')
}}"
With above .replace('./assets/', '') we are removing the ./assets/ and repalcing it with '' empty space. So now URL is in this formathttp://localhost:3000/imagename.png.

Display image from JSON/API in React using JSX

I'm a React noob and I'm making an API request to retrieve JSON from a movie API and then displaying information about the movies, including the movie poster, in my component. I was able to retrieve and display text, but I am having trouble displaying images using JSX and the URL of the database.
I've assigned the images to post.poster_path and I'm attempting to concatenate the rest of the URL to the JSX.
<img src={"https://image.tmdb.org/t/p/w300/"+post.poster_path} alt="Movie Poster"/>
This doesn't work.
poster_path contains the image, I have verfied this in React tools. How do I properly concatenate the rest of the URL to post.poster_path?
If
post.poster_path = 'image.png'
and the whole url is
https://image.tmdb.org/t/p/w300/image.png"
for your image then the img tag will be as follows
<img src={`https://image.tmdb.org/t/p/w300/${post.poster_path}`} alt="Movie Poster"/>
In JSX if you have a value in variable and need to concat with a string you use tick `
eg. {`string ${variableName}`}
and if post.poster_path has the whole path then:
<img src={post.poster_path} alt="Movie Poster"/>

How can you style/modify django file fields?

In my django (1.6) project, I have a form with a FileField for uploading images (It is a FileField and not an ImageField for legacy reasons).
Currently I render the form field in a template by doing {{ form.image }} which renders it with the label, link to the image, clearing checkbox and upload button. This is all good, but I need to style those separate modules.
For the url, I'd like to make it render as:
<a href="url" class="fancybox" rel="group">
<img src="url" alt="product image" class="img-responsive">
</a>
And for the other parts (buttons, checkbox), I want to add CSS classes to them.
I looked at the ClearableFileInput widged which is responsible for rendering the FileField and I am thinking maybe I can achieve this by overriding some methods, but I am not sure what to override to change as little as possible.
How can I achieve this the right way?
The widget accepts an attrs parameter. It's a dictionary that is passed along to be the attributes on the rendered HTML widget. Here are the docs.
Here's the example from the docs with the class specified:
name = forms.TextInput(attrs={'size': 10, 'title': 'Your name', 'class': 'img-responsive'})
If you want build custom widget - you can inherit it from ClearableFileInput override render method and specify custom template_with_initial, it is quite simple

display binary image from db to angular partial view

I was trying to display image which is coming within the json object returning from an web api request. I'm able to display string, number and date/time in my angular partial but couldn't get the image displaying.
here is my json object which contains each field of my topic (model) class
<Topic>
<Body>dsadfsaadsfds</Body>
<Created>2014-06-15T00:00:00</Created>
<Flagged>false</Flagged>
<Id>1022</Id>
<PhotoFile>
iVBORw0KGgoAAAANSUhEUgAAB2wAAAOiCAIAAAAzNbBAAAABiWlDQ1BJQ0MgUHJvZmlsZQAAKBWtkT1LA0EQht+L0SgJGCRoCpEFRSzu5IxFTLTJB5iIRYgKane5nImQj+NyIfoD7Gy0EG0U9S+INhaWYqGFIAjB3yAEAi..........
(I want to post screen shot but i can't due to lack of reputations.....)
</PhotoFile>
<Replies i:nil="true"/>
<Title>csdaadsf</Title>
and here is my angular html partial:
<a data-ng-href="#/message/{{ i.id }}">{{ i.title }}</a>
</div>
<div class="date span2">
{{ i.created | date:"medium" }}
</div>
<div class="contents span12">
{{ i.body }}
</div>
<img ng-alt="" src="{{'data:image'+i.photofile}}" /> </div>
`
Since i can get other attributes working, my angular factory and controller should be working. Are there anything wrong with my syntax in angular partial view for displaying images? Thanks
You shouldn't be using the src attribute when using Angular expression as the value. Use ng-src instead, it will ensure the image don't show up before Angular has a chance to replace the expression.
If the sample payload you've shown is complete, the way you are forming the data URI is incomplete. Depending on the format of the image, the header should look like
data:image/png;base64,[things in the JSON]
You can read more about the format here