Associate Existing Image File with Django Model - python

I'm creating a basic blog in Django. One of my classes is for the authors. Each contains Name, Position, Biography, etc., and I'm attempting to associate existing images with each author to be used as avatars, essentially.
FileField and ImageField aren't what I want to use as I already have images stored statically elsewhere- I just want to specify each image's path manually in the Django admin as a URL (CharField/TextField, whatever) and have that image served when I call {{ author.photo }} in a template, for example. I also don't necessarily want to source the image path from the class model, as the structure and paths of the existing images may change. Any ideas?

Well you have to save it somewhere in order to map the user and the image....
So I can think of 2 solutions -
Have a field that stores the path. Then you can access it via the template, something like this - <img src="{{author.photo_path}}">
If you're saying the path might change, you can have a user ID for each user, and store his photo with that ID. Then you can simply do <img src="/path/{{author.id}}_picture.gif">
Using the second solution, you can also have the path as a variable in your code, and then pass it to the template, and access the picture like this -
<img src="/{{path}}/{{author.id}}_picture.gif">, which doesn't force you to have a hardcoded path, and once the path changes you only change it once, not in all your model instances/template files

Related

How to add custom HTML elements and images to a blog in Django?

I am trying to create a blog in Django. Most of the tutorials and examples available shows just retrieving some content from the database and displaying it dynamically on the predefined HTML structure.
After looking at some solution I found something called flatpages in Django which provide the facility to write HTML. But its recommended to use it for About Us and Contact Us kind of pages. Should I use this?
I want to do it as I can write my own HTML data for each blog and add some images so that the structure of HTML should not be similar in each blog.
For example, In the case of WordPress, it allows the user to completely write each part of the blog except the heading part and the structure of HTML is not constant always.
I want such functionality. Please help.
What you are looking for is to upload images and embed them as html in your content field. This can be done using a WYSIWYG Editor such as CKEditor. In CK you can write your text, format it and upload files. You could use django-ckeditor to do the heavy lifting for you: https://github.com/django-ckeditor/django-ckeditor
In your template you then have to render your content with safe filter so that the content will be rendered as html:
{{ post.content |safe }}
Have you tried using the static directory? It stores the static content like CSS, Image etc. Create the Static and join it with the BASE_DIR in settings.py file. A full explanation is given here. https://docs.djangoproject.com/en/2.2/howto/static-files/
There are a bunch of packages that already do this. You can refer to Django Packages and pick the one that suits your needs the best.
Mezzanine is one of the most common ones. I personally have not used it.
I've seen Django-cms being used at one of my previous jobs. It was quite powerful, but I personally did not like it a lot.
If you'd like to create your own CMS, you could go for a very basic structure like
class BlogImage(models.Model):
image = models.ImageField()
alt_text = models.CharField(max_length=128)
class BlogPost(models.Model):
title = models.CharField(max_length=512)
content = models.TextField() # be sure to validate that this does not contain bad code
tags = models.ManyToMany(Tag)
Give the users a WYSIWYG editor like CKEditor. If users want to include images the just need to use the URL to it. If they want to upload, give them a modal or some different page to upload the image and copy the link to the image into the HTML markup

How do I automatically upload an automatically created file to a FileField in django? (or equivalent functionality)

I have a method that creates a csv file from a serialized model and writes the file to a data folder. This works - the csv is created, but to do anything with it a user has to manually upload it back in to the app, which is awkward.
I'd like to automate the step of uploading that same file to the UploadFile model in another app within the same project - that is, when it is created, instead of, or in addition to, being written to the file tree, the file is uploaded and stored in a FileField (or location anyway) in an UploadedFile.
EDIT: In this app - a user fills out several forms which, taken together, create a Group. The Group model has a many-2-many relationship to a People model, which has many-2-many relationships to the Attribute and Stats models. Each model has an associated form.
So a user would create a Group, submit it which writes it to the data folder, and then -<(magic happens)>- the Group.name, Group.label, and Group.data are applied to the UploadFileForm which uploads it to the UploadFile model.
I have searched google for something like this and found nothing -- which makes me think I am forming the question incorrectly. Any help is appreciated.
I'll post my code if need be, but a general solution would be helpful enough.
EDIT: I realize now that I can't use 'initial' to populate a FileField in a django mode -- security risk. Since that won't work - I'm out of ideas for how to upload the last file created to a FileField in a django model by any means.

How do I display static images that are in content variable in django?

I have a django site where a portion is basically a CMS. There are large content blocks (like the content of a post) held in a database and within those I need to display images that are in my static files. The content within the content block could be anything just like a regular blog post so there may be images scattered within it.
I am displaying the content in a template using the following
{{content | safe}}
I can display the images if I put the full url but that is not optimal as it doesn't use the advantages of the Django static files system. How do I go about displaying these since I can't use the {% static %} tag for the images that are within the content?
This seems like a place to use a custom filter. There are probably a lot of different ways to do it, but one could look like this:
from django import template
from my_project import settings
register = template.Library()
#register.filter
def img_link(content):
return content.replace('src=','src='+settings.STATIC_URL')
That's assuming you already have the code in your content look something like -- you can adjust the filter to meet however your images are actually written in the content. Because this is relying on the STATIC_URL from your settings, it will adjust whenever the URL is changed, exactly as {% static %} would.
of course, filters can be chained, so you could just write {{content|safe|img_link}} to activate the filter.

Add Derived Field to Django Admin Change Form

I'd like to add a derived field to a default ModelAdmin.fieldsets like I would by specifying a method and adding it to the ModelAdmin.list_display property, but there doesn't seem to be an easy way to do that (if there is ANY way to do that).
The default Django Admin list view seems to have a lot more options than the change form view does.
Let's say I have two fields for a location: latitude and longitude, and instead of displaying them on a change form I want to display a Google Maps Static Map image instead - I already have a method that will return the src url for the image - I just need a way to add that image to the model change form instead of showing those two fields.
If you write a method and add it to ModelAdmin.readonly_fields, it will appear on the change view.
customize admin view http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin

Django.contrib.flatpages without models

I have some flatpages with empty content field and their content inside the template (given with template_name field).
Why I am using django.contrib.flatpages
It allows me to serve (mostly) static pages with minimal URL configuration.
I don't have to write views for each of them.
Why I don't need the model FlatPage
I leave the content empty and just supply a template path. Therefore I can take advantage of having the source in a file;
I can edit the source directly from the file system, without the help of a server (such as admin).
I can take advantage of syntax highlightning and other editor features.
With the model I have to maintain fixtures for flatpages.
So the data for the same entity is in two seperate places.
If I move the content inside the fixture it'll be more difficult to edit.
Even if fixture maintenance was a non-issue I'd still need to dump and load these fixtures again and again during development.
What I am looking for
Basically; getting rid of FlatPage model while maintaining contrib.flatpages functionality. I don't have a clear idea how this should be solved. If there's a clean way of modifying (like add_to_class) FlatPages to get the information somewhere other than the database I'd prefer that. Maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of FlatPages.
If I don't prefer manual editing over admin functionality for flatpages, how can take the database out of the equation?
Using the direct_to_template generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:
r'^foo/(?P<template_name>.+)/$','direct_to_template', {'template': 'foo_index.html'}),
Then import the template in your foo_index.html:
{% include template_name %}

Categories