I have a dessert model in django with a property called picture:
class Dessert(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(max_length=1000, blank=True)
picture = models.ImageField(upload_to ='uploads/desserts-pics/', max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(1)])
tags = models.ManyToManyField(Tag, related_name="desserts")
def __str__(self):
return self.name + " ($" + str(self.price) +")"
And i want to show the image in my front with react, like this:
<img src={dessert.picture}>
dessert is an instance of the Dessert model witch i got from a request, but the picture is a file not an image, how the hell do i get the src? sorry, i know it's a silly question but i didn't find the answer anywhere else.
I am not a react user. However, the HTML tag you show (if it's similar) would need some changes to display the image field of your model instance. Let's assume you have a simple view that shows a dessert, like...
def show_dessert(request):
d = Dessert.objects.get(id=1)
context = {'d':d}
return render(request, "pages/my_template.html", context)
With d as your desert object, you would show the image using .url, like:
<img src="{{d.picture.url}}">
Find more information on serving files and photos in Django docs here.
This answer also assumes you have correctly configured your static files settings. More info about that here.
Related
I've been around the Internet the whole day reading about the following issue, in wagtail if I registered the following model for translation like this:
class RecipientsPage(Page):
intro = RichTextField(null=True, blank=True)
banner_image = models.ForeignKey(
"wagtailimages.Image",
on_delete=models.SET_NULL,
related_name="+",
null=True,
blank=False,
help_text=_("the Image shouldn't exceed ") + "1350 * 210",
)
content_panels = Page.content_panels + [
FieldPanel("intro"),
ImageChooserPanel("image"),
]
this is how I registered the model:
#register(RecipientsCountriesPage)
class RecipientsCountriesPage(TranslationOptions):
fields = ("intro",)
It causes a problem, because like this I'll have two slugs following the two titles (The original English one and the Arabic translated one), if I change the Arabic slug manually to equal the English one it'll work, but it's not efficient to do so for each page manually
I've read about the issue a lot like in here:
https://github.com/infoportugal/wagtail-modeltranslation/issues/195
I've found also the following question with no answer
How do you translate the slug value of a page?
I've also read that I can override some of the wagtail Page methods but without further explanation and I'm a bit lost, what's the best way to overcome this issue?
I did it using Django signals
#receiver(pre_save)
def set_arabic_slug_on_new_instance(sender, instance, **kwargs):
if isinstance(instance, Page):
instance.slug_ar = instance.slug_en
I have a simple Django App having database interactions. I need to make the functionality of Video Visiting counter. So that I need to update- increment the counter each time when user visit the video.
I have a video object on template page(video-details.html).
This is how I access the video_file_name.
<h1 id="video1">{{video_obj.video_file_name}}</h1>
I have video model as:
class Video_Mapping(models.Model):
video_file_name = models.CharField(max_length=100)
video_description = models.CharField(max_length=2000, default='Video Description')
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
video_category_id = models.IntegerField(default=1)
video_seen_count = models.IntegerField(default=0)
I want to update the video_seen_count model value on template page.
More info: As I can do similar thing in View like following.
video = Video_Mapping.objects.get(pk=video_id);
video.video_description = description; video.save();
Please suggest me the best way to do it in the video-detail.html template page.
The simplest thing which I have done here is as per #birophilo'suggestion.
I was actually finding the way to increment the video_seen_count value from template(html page).
But after doing more research and try as suggested in comment, I decided to make this increment operation before the template renders(So in the view).
So it worked like:
video.video_screen_count += 1
video.save();
Thanks.
I'm quite confused about how the Blobstore works alongside serving images per entity.
So let's say I have:
class Book(ndb.Model):
title = ndb.StringProperty()
cover_image = ndb.BlobProperty()
How can I output this information in a jinja2 template, like this:
<h1>{{title}}</h1>
{{cover_image}}
My confusion stems from my being unclear about how the Blobstore and the datastore works together. For example: How do we relate a datastore's entity to a Blobstore property (in our example, it would be relating the the cover_image blobproperty to its Book entity)?
A simplified explanation would be much appreciated. Thank you.
What you are looking for is get_serving_url(blob_key, size=None, crop=False, secure_url=None)
Try this method on the blob and you will get an image url.
Docs
You upload the blob and you get a blobkey that you store. Imagine it like another entity's key.
Then having that key you use the get_serving url and several other functions in order to serve a url, resize etc.
You can just use a BlobKeyProperty in your model to maintain a reference between the datastore and the blobstore. For example:
class MyContent (ndb.Model):
Image = ndb.BlobKeyProperty()
Then, if you need to frequently get the associated URL you can even also store the serving URL:
class MyContent (ndb.Model):
Image = ndb.BlobKeyProperty()
ImageServingURL = ndb.StringProperty()
You can create a different handler for getting the images. The way you do that depends on the framework used. Pyramid example (without try and excepts):
#handler /{bookid}/coverimage
def RenderImage(request):
book_key = request.matchdict['bookid']
book = Key(urlsafe=book_key}.get()
cover = book.cover_image
#optional rezising:
cover = images.resize(cover, WIDTH, HEIGHT) #or other image operations
response = Response(content_type="image/jpeg")
response.body = cover
return response
In your template:
<img src="/{{book.key.urlsafe()}}/coverimage" />
Note: you can do a generic image handler for any image property, not only 'cover_image'
I have a image field in the model. I need to make two copies(resized) of that image to another two field(thumb_big and thumb_small). Thumb_big will be 225px width, height could be anything. and thumb_small is 65x50px.
I searched but nothing seems to fit in my problem. I Have installed PIL. Tried django-imagekit, some other snipets.
If you know any link that will be great also, BTW I am a django newbie but you assume that already, right?
here is my model
class Photo(models.Model):
title = models.CharField(max_length=500)
pub_date = models.DateField(auto_now_add=True)
mod_date = models.DateField(auto_now=True)
slug_name = models.SlugField(max_length=500)
image = models.ImageField(upload_to='interview', blank=True)
thumb_big = models.ImageField(upload_to= 'interview/thumbs_big', blank=True)
thumb_small = models.ImageField(upload_to= 'interview/thumbs_small', blank=True)
category = models.CharField(max_length=200, blank=True)
details = models.TextField()
def __unicode__(self):
return self.title
I'm not quite sure why would you need to store thumbnail paths in the database.
There are several django thumbnail applications.
Two of my favorites are:
sorl-thumbnail - https://github.com/sorl/sorl-thumbnail
easy-thumbnails - https://github.com/SmileyChris/easy-thumbnails
Both of them are using template tags for generating thumbnails on the fly,
and display them in your django templates.
They also come with custom database fields to make thumbnail management easier:
http://thumbnail.sorl.net/examples.html#model-examples
http://packages.python.org/easy-thumbnails/usage.html#models
If you really need to save paths to your thumbnails in your model, you can generate both thumbnails in your image upload view, and then assign resulting file paths to corresponding database fields. With easy thumbnail it will look like:
photo = form.save()
from easy_thumbnails.files import get_thumbnailer
thumbnailer = get_thumbnailer(photo.image)
thumb = thumbnailer.get_thumbnail({'size': (100, 100)})
photo.thumb_big = thumb.name
photo.save()
i'm experimenting with django and the builtin admin interface.
I basically want to have a field that is a drop down in the admin UI. The drop down choices should be all the directories available in a specified directory.
If i define a field like this:
test_folder_list = models.FilePathField(path=/some/file/path)
it shows me all the files in the directory, but not the directories.
Does anyone know how i can display the folders?
also i tried doing
test_folder_list = models.charField(max_length=100, choices=SOME_LIST)
where SOME_LIST is a list i populate using some custom code to read the folders in a directory. This works but it doesn't refresh. i.e. the choice list is limited to a snapshot of whatever was there when running the app for the first time.
thanks in advance.
update:
after some thinking and research i discovered what i want may be to either
1. create my own widget that is based on forms.ChoiceField
or
2. pass my list of folders to the choice list when it is rendered to the client
for 1. i tried a custom widget.
my model looks like
class Test1(models.Model):
test_folder_ddl = models.CharField(max_length=100)
then this is my custom widget:
class FolderListDropDown(forms.Select):
def __init__(self, attrs=None, target_path):
target_folder = '/some/file/path'
dir_contents = os.listdir(target_folder)
directories = []
for item in dir_contents:
if os.path.isdir(''.join((target_folder,item,))):
directories.append((item, item),)
folder_list = tuple(directories)
super(FolderListDropDown, self).__init__(attrs=attrs, choices=folder_list)
then i did this in my modelForm
class test1Form(ModelForm):
test_folder_ddl = forms.CharField(widget=FolderListDropDown())
and it didn't seem to work.What i mean by that is django didn't want to use my widget and instead rendered the default textinput you get when you use a CharField.
for 2. I tried this in my ModelForm
class test1Form(ModelForm):
test_folder_ddl = forms.CharField(widget=FolderListDropDown())
test_folder_ddl.choices = {some list}
I also tried
class test1Form(ModelForm):
test_folder_ddl = forms.ChoiceField(choices={some list})
and it would still render the default char field widget.
Anyone know what i'm doing wrong?
Yay solved. after beating my head all day and going through all sorts of examples by people i got this to work.
basically i had the right idea with #2. The steps are
- Create a ModelForm of our model
- override the default form field user for a models.CharField. i.e. we want to explcitly say use a choiceField.
- Then we have to override how the form is instantiated so that we call the thing we want to use to generate our dynamic list of choices
- then in our ModelAdmin make sure we explicitly tell the admin to use our ModelForm
class Test1(models.Model):
test_folder_ddl = models.CharField(max_length=100)
class Test1Form(ModelForm):
test_folder_ddl = forms.choiceField()
def __init__(self, *args, **kwargs):
super(Test1Form, self).__init__(*args, **kwargs)
self.fields['test_folder_ddl'].choices = utility.get_folder_list()
class Test1Admin(admin.ModelAdmin):
form = Test1Form
I use a generator:
see git://gist.github.com/1118279.git
import pysvn
class SVNChoices(DynamicChoice):
"""
Generate a choice from somes files in a svn repo
""""
SVNPATH = 'http://xxxxx.com/svn/project/trunk/choices/'
def generate(self):
def get_login( realm, username, may_save ):
return True, 'XXX', 'xxxxx', True
client = pysvn.Client()
client.callback_get_login = get_login
return [os.path.basename(sql[0].repos_path) for sql in client.list(self.SVNPATH)[1:]]