I have created my blog using Flask-FlatPages and the posts are in Markdown, the challenge I'm having is inserting images in my blog post. The traditional way of inserting images in markdown is not working.
I also tried this without success:
![image]({{ url_for('static', filename="img/my_image.jpg") }})
Here is a quick fix! let's say we have a images folder, and we want to use the images/flower.jpg
Step 1: Put the images folder in the static folder.
Step 2: In the text, link the image with ../static/images/flower.jpg.
for example:
![flower](../static/images/flower.jpg)
or
<img src="../static/images/flower.jpg" alt="flower">
Here is what worked for me. It turns out that FLATPAGES_HTML_RENDERER is needed to achieve this goal.
Here is the code:
def my_renderer(text):
prerendered_body = render_template_string(text)
return pygmented_markdown(prerendered_body)
app = Flask(__name__)
app.config['FLATPAGES_HTML_RENDERER'] = my_renderer
pages = FlatPages(app)
This is also discussed on this post:
https://github.com/SimonSapin/Flask-FlatPages/pull/1
There are nothing wrong during the markdown to html conversion process.
I think it because bleach.clean() function.
You can try to add to allowed_tags.
allowed_tags = ['img']
allowed_attrs = {'img':['src','alt']};
target.body_html = bleach.linkify(bleach.clean(markdown(value,output_format='html'),tags=allowed_tags,attributes=allowed_attrs,strip=True));
Related
I'm building a CMS in flask and I have built a simple wysiwyg editor using execcommands for creating and editing posts, and everything is working. For the insertImage command I'm using an input element to open a directory and choose an image. It works except of course it opens my computers default folder. I want it to open the uploads folder in the static directory where user images are stored in flask. How?
I have searched through flask docs, Python handling files documentation and there's no mention of this. This is a project I'm doing for a class. I'm going above and beyond the requirements for this project but that's how I keep things interesting. I mean it's supposed to be a CMS right. Well, CMS's always have wysiwyg's that open the default "uploads" folder to insert media. Also, when creating my upload functions I found that when uploading files flask needs the absolute path. But when serving them the relative path is necessary.
Any point in the right direction would be greatly appreciated. Thank you.
Here's the structure
<div class="col-md-1 tools">
<a href="#" data-command='insertImage'data-toggle="tooltip" title="Insert Media"><i class='material-icons'>add_photo_alternate</i>
</a>
<div class="editorInputs">
<input type="file" name="media" id="insertImage"
accept="audio/*,video/*,image/*"/>
</div>
</div>
Here's my js script
$('.tools a').mousedown(function(e){
let command = $(this).data('command');
if(command == 'insertImage'){
$(this).next().children('input').trigger('click');
let input = $(this).next().children();
input.on('change', function(e){
let val = $(input).val();
document.execCommand(command, false, val);
})
}
});
Here's how my uploads file is configured in flask
app.config['SITE_UPLOADS'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/static/site/uploads/'
app.config['ADMIN_UPLOADS'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/static/admin/uploads/'
app.config['ALLOWED_IMAGE_EXTENSIONS'] = ['PNG', 'JPG', 'JPEG', 'SVG', 'GIF']
app.config['DATA_FILES'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/data/'
app.config['RELATIVE_PATH_SITE'] = '../static/site/uploads/'
app.config['RELATIVE_PATH_ADMIN'] = '/static/admin/uploads/'
So, I realized that I have to create a function to pull images from the uploads folder, display them, get their URL and pass it to the execcommand. And I did.
First, create the gallery structure with radio buttons to view files. Then put the gallery in a bootstrap modal to fire when the execccomand insertImage link is clicked. Grab the URL of the checked image. pass it to the execcomand function in my js.
On the flask side get a list of all files in the uploads directory with os.listdir(absolute/path/to/directory), returns a python list of the files. Next create file urls and put info in a dict by looping over the filenames in the list and adding the relative path to the filename. Pass the dict to the jinja2 template and populate the gallery.
Finally, execute the js.
Here's my python code and js code.
def get_uploads():
list_images = os.listdir(app.config['ADMIN_UPLOADS'])
images = []
i =0
length = len(list_images)
while i < length:
img = {}
img['name'] = list_images[i]
img['url'] = os.path.join(app.config['RELATIVE_PATH_ADMIN'], list_images[i])
images.append(img)
i+=1
return images
Here's my js.
if(command == 'insertImage'){
$("#uploadsGallery").modal();
$('.ftco-animate').addClass('fadeInUp ftco-animated')
let check = $(this).next().find('input.form-check-input');
let val;
check.on('change', function(e){
val = $(this).val();
});
$('#insertImg').click(function (e) {
r.setStart(editDiv, lastCaretPos);
r.setEnd(editDiv, lastCaretPos);
s.removeAllRanges();
s.addRange(r);
document.execCommand(command, false, val);
check.prop('checked', false);
});
}
Maybe this question has been answered before in one way or another. But I need to ask because I tried to answer it myself I googled it for days but I couldn't figure it out.
I have an app called reception in my Django project.
I figured out everything but this.
I have the link in the html directing to the right urlpattern.
<p><tab1>Reception</tab1></p>
urlpatterns = [..., path('go_to_reception', views.reception, name='go_to_reception'), ...]
And the view is like this
def reception(request):
return render(request, 'reception.html')
now instead of reception.html I want the link to go the reception page. The app page. What do I need to write there. I have tried everything that came to my mind but nothing worked.
the reception is as follows:
http://127.0.0.1:8000/admin/reception/
So how do I point to this.
Please help!
Thanks
So im just going to write the solution that we discussed in the chat:
{% url "admin:app_list" app_label="reception" %}
documentation
Look, this help you? i solve a similar problem in this way
url.py
path('gotoreception', views.reception, name="go_to_reception"),
html
<a href="{% url 'go_to_reception' slug=slug %}"
model
slug = models.SlugField(max_length=255, unique=True)
view
def home(request, slug):
context = {'yourdata':yourdata}
return render(request,'index.html', context)
On the template tag url you need use the name of your path, you can use a slug if you store the field on your db
3ยบ option but not recommended, you can add the value if you have on a variable but is not a good practice
I recommend you this 2 resources:
https://docs.djangoproject.com/en/2.1/ref/utils/
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/
hardcoded way
can you test this?
urls
urlpatterns = [..., path('reception/', views.reception, name='go_to_reception'), ...]
html
and on the link <a href="127.0.0.1/reception/">
is the hardcoded way but in the future you can have troubles or relative urls, 404 on internal pages
Thank you for your answer Matthew,
After your latest comment, I have changed my code to the following:
<p><tab1>Reception</tab1></p>
and in url.py its:
path('reception/', include('reception.urls', namespace='reception-urls')),
in reception.urls.py
app_name = "reception"
and the message now says:
django.urls.exceptions.NoReverseMatch: Reverse for 'go_to_reception' not found. 'go_to_reception' is not a valid view function or pattern name.
I am sorry for going back and forth like this, but I honestly can't make it work.
have you got a view called go_to_rececption in your reception.views or a url named go_to_reception in your reception.urls?.
and no worries just trying to help!!!
I'm facing difficulty to download (the already uploaded) files as I am a newbie in django. Also I could not find a way to do that (the uploaded files are of different formats). May someone post a minimal but complete (Model, View, Template) example code to do so?
So if you alredy have model like:
class MyFile(models.Model):
file_field = models.FileField()
In your view add your uploaded file in template context like:
{'myfile': MyFile.objects.get(id=1)}
In your template just use <a> tag with:
href="{{ myfile.file_field.url }}"
I'm installed Flask-images for resizing some images. My code are like this:
<img src = '{{url_for('showimages', filename = market.thumbnail, width=100, height=100, mode='crop')}}'>
showimages:
#app.route('/image/user/<filename>')
def showthumbnail(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
There are nothing happens and my Chrome devaloper tools said image's url like this:
<img src="/image/user/Untitled-1.png?width=100&height=100&mode=crop">
I know there is another way instead url_for - resized_img_src().
I'm set IMAGES_PATH= os.path.join(APP_ROOT, 'images/').
However this configuration does not work and when I use resized_img_src(), only got broken image icon. I don't have a clue how can fix this.
+Is there any other easy ways to resizing uploaded images?
Your template uses showimages whereas your Flask Python code shows showthumnails, I'll assume this is typo and code actually uses same as template.
Are these really the quote characters you are using in your template? You need to use the single and double quotes or escape the inner single ones. Try this instead:
<img src="{{url_for('showimages', filename=market.thumbnail, width=100, height=100, mode='crop')}}">
I want to divide index page into small stand alone .html parts like:
up_bar.html:
<p><center>
<h1>home</h1>
Menu: home add import
down_bar.html:
<a href="/path/.."/>
and so on.
Now, to build a new page is it possible to embed those pieces into other page using default webpy templator?
Maybe something like that?:
in admin.html:
$def with(some_parameters):
<title>Admin panel</title>
$include('side_bar.html')
... body stuff ...
$include('down_bar.html')
A basic but good introduction to template inheritance can be found here: http://webpy.org/cookbook/layout_template
Found an answer here: http://groups.google.com/group/webpy/msg/ea6da02dfb9eedc4?dmode=source
Some explanation will be great.
I did this to my code
def GET(self,*args):
param= {'name':'jackie'}
view = web.template.frender("views/someview.html")
content = view(**param)
layout = web.template.frender("views/index.html")
return layout(content=content)
now you just insert $:content in index.html