How to load image from backend (SQL textfield ) directly by using Django? - python

I am trying to make a blogging website. I know django provides argument templates like
{% include images.html with value=sense %}
The above code directly works in HTML and hence everything works. The images are stored in a backend database and connected to everystory by some logic. The user can use the names of the images and call whenever they need to use it
When I try the above code directly in the backend it doesn't work because I think once something is rendered then it doesn't rerender by django HTML
I wish to paste some form of links in the django story backend. such that when it renders in HTML automatically the page should show pics in the appropriate place. If anyone has any idea how to do this kindly let me know.
So when loading stories in the database the user can put some form of links for images in the database and while rendering all images come in a certain format as specified in the block in the blog.So there can be any number of images and the count is not longer fixed as shown in the pics below where I am trying to render a image called sense from the backend which doesn't work.. whereas it directly works in the frontend.
<p>{{object.story_title}}</p>
<p>{{MEDIA_ROOT}}</p>
<p>{{object.story}}</p>
{% include "blogdescription/image.html" with value=sense %}
Thank you for your time.
with regards

Let me start saying that doing exactly what you want is not possible because Jinja will compile and render {{object.story}} and not its content (the include). It does not seem possible to use nested Jinja syntax to load any resources, includes, extends, urls, etc.
Which explains why when you place the include in the template it works but does not inside your model field.
What seems possible is to load an HTML image with a explicit URL to the resource, lets say, the content inside your text field is:
<div style="display: flex; justify-content: center; align-items: center;">
<img src="/static/myimage.jpg" alt="Object Image">
</div>
Template.html (source):
{% block content %}
{{obj.title}}
<br>
{{obj.body|safe}}
{% endblock %}
Alternatively, it is possible to generate a HTML file to render dynamically based on Object.field. Note that this solution is a heavy load on the server, for every request will generate a dynamic file to be rendered.
Obj field value:
{% extends 'base.html' %}
{% block content %}
{{obj.title}}
<hr>
{% include 'includes/image.html' %}
{% endblock %}
views.py:
def story(request, id):
obj = Story.objects.get(id=id)
f = open(f'templates/generated/dynamic_template.html', 'w+')
f.write(obj.body)
f.seek(0)
return render(request, 'generated/dynamic_file.html', {'obj': obj})

Related

How to append specific html to a Django code block using only Python/Django?

I have a form I'm working with in Django.
I have a built in error message I'm trying to get to render on the form.
My first step is to get the error message to render on the form and then I will go into the function and tweak when it shows up.
My problem emerges when it comes to doing it in python.
Normally, my preferred way would be to JQuery for the footer and use JavaScript to append/prepend the HTML. Then set it to show/hide based on conditionals.
However, for this I am wanting to do it in Python to make it easier for the people working w/ me.
Here's an example of the error message HTML I would like to use for appending to something else in JS.
error_field.append('<em for="name" class="form-error-message text-danger">');
Here is an example of the Django Code Block I would like to add it within
{% block form-footer %}
{{ block.super }}
{% endblock %}
What is the easiest way to accomplish this within Python/Django? To be clear, I can figure out the conditional stuff myself. Just the rendering of the specific HTML/CSS error class I have already created. I should be able to do the conditional/function part of this myself.
I can just show you an example, this is a part of my project
views.py
try:
user=User.objects.get(username=username)
except:
messages.info(request,'username does not exist')
return redirect('login')
return render(request,'users/login-register.html')
html
{% if messages %}
{% for i in messages %}
<div class="alert alert--{{i.tags}}">
<p class="alert__message">{{i}}</p>
<button class="alert__close">x</button>
</div>
{% endfor %}
{% endif %}
You can use this anywhere in your html page. This is a common page, and everything in here is extended. And of course this is an example similar to your problem. Check it out if you want

How to exclude a part of a Django template file from processing?

I have a Django template file that has a couple of enormous strings in it (images encoded in Base64). When I use the Django templating engine, it chokes and takes 5 minutes to render the template. Is there a way to exclude a part of a template, with something like:
{% ignore %}
<img src='....'>
{% endignore %}
Does this exist?
Use verbatim tag!
From django docs https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim
verbatim
Stops the template engine from rendering the contents of this block
tag.
A common use is to allow a JavaScript template layer that collides
with Django’s syntax. For example:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}

jinja2: Can I render template tags from an expression?

How would I return text with template markup from an expression and have the tags rendered by Jinja? It looks like Jinja only makes one pass, and just escapes and dumps the text in without further processing it as part of the template (which would be the right thing 99% of the time). Is there a way to make two passes with the renderer, or render the result of my expression first and pass it to the template?
Simplified Problem
I have included further details below in case there is more to this than I think, but this should be all the information needed for the problem.
If do_render() returns <p>Hello there {{ current_user.name }}</p>, how could I do the following in a template, so that I obtain the value of name?
<div>
{{ do_render() }}
</div>
This renders as <div><p>Hello there {{ current_user.name }}</p></div>, when I want <div><p>Hello there Sam</p></div>.
Complete Problem
I'm using Flask, Flask-Bootstrap, and Flask-Nav with Python 2.7. I could just create the navigation bar myself and none of this would matter, but "autogenerated" sounded so much simpler...
Flask-Bootstrap provides a Flask-Nav compatible renderer; I have subclassed it to modify my navigation bar. I'm trying to add a logon form in the navigation bar, right-aligned. Because the BootstrapRenderer generates the complete navbar, I have to inject my form into it prior to the closing tags (alternatively, I could skip super() and do it all myself).
class MyRenderer(BootstrapRenderer):
def visit_Navbar(self, node):
""" Returns the html for a Bootstrap navigation bar. """
root = super(MyRenderer, self).visit_Navbar(node)
# Replace the navbar style with my custom css
root['class'] = 'navbar navbar-mystyle'
# Here I try injecting a login form. This is the correct position,
# and it inserts properly; it just treats {{, }}, {%, %}
# as nothing special.
elem = root[0][1] # div class="navbar navbar-collapse"
elem.add(
dominate.util.include(
os.path.join(
config.app_path_root, app.template_folder, 'inc/login_form.jinja')))
# I have also tried
# elem.add('{% block nav_right %}{% endblock %}')
# thinking I would use inheritance later (still my preference).
return root
I then register the renderer with Flask-Nav, and render it by inserting {{ nav.main_nav.render() }} into my base template, which my .html files inherit from. All of this works.
My problem is that I only want the login form when the person is not logged in.
The login_form is:
{% if not current_user.is_authenticated() %}
<form class="navbar-form navbar-right" role="search" action="login" method="post">
<div class="form-group"><input type="text" name="username" /></div>
<div class="form-group"><input type="password" name="password" /></div>
</form>
{% else %}
<div class="navbar-right">
Welcome {{ current_user.name }} | Logout
</div>
{% endif %}
My HTML output is identical to the template; neither statements, expressions, nor comments are treated as such.
Other attempts: I have generated the navbar first, then passed it to the template via render_template('index.html', navbar=navbar) but I have the same problem. I have also tried macros. I'm about ready to write my navigation menu in the base template myself and be done with it, but now it feels like that would be giving up.
Other than {% include ... %} and {% extends ... %}, you're not going to be able to have the template system automatically render something that's added to a template during runtime without a bit of customization.
The beautiful part about Jinja 2 is that its API is very powerful and you can do many things without having to feel like your "hacking" the system. To do what your first example is implying, you just need to have the function render the included template snippet snd return a rendered string. If you're expecting the template to be rendered with the context of the parent template, that's not gonna happen automatically, but that's not a problem since you can pass in whatever you need directly in your function call in the template.

Creating a "Recent Posts" list in a sidebar.

I'm working on a simple blog app in Django, and i'm having trouble figuring out how to dynamically generate the five most recent posts in a side bar. Each of my views are class based and they extend a generic template, each view maps to one template which I believe is the correct way to do it. I've looked for a way to do this using template tags, but it seems Django doesn't like you to put any logic inside of your templates.
The problem I believe is that I want this to exist within my base.html because I want the recent posts to be displayed site-wide, is a view even supposed to map to your base.html or does that cause problems, i'm pretty new with this. I don't know how to approach this, whether i'm supposed to create a new view for base.html or if I should use my template tags, or if I should extend an existing view(but if I do that it won't be site wide?).
I essentially want the following(they're ordered in reverse chronological order)
{% for post in post_list[:4] %}
{{ post.title }}
{% endfor %}
You can use a template tag. More specifically, an inclusion tag is what you need. This allows you to insert a rendered snippet anywhere inside your template via a small view-like piece of code.
For example, create a templatetags/blog_tags.py file (it's important that you create the templatetags folder within your app; Django searches for them here by default) in your blog app and add the following:
from django import template
register = template.Library()
#register.inclusion_tag('blog/snippets/recent_posts.html')
def render_recent_blogposts():
return {
# This is just an example query, your actual models may vary
'post_list': BlogPost.objects.all().order_by("published_on")[:4]
}
now create a blog/snippets/recent_posts.html template (it can be anywhere as long as it mathecs the #register.inclusion_tag(...) above.):
<ul>
{% for post in post_list %}
<li> {{ post.title }}</li>
...
{% endfor %}
</ul>
finally, in your original template, you can now render your template tags:
<aside>
{% load blog_tags %}
{% render_recent_blogposts %}
</aside>

Page switching using AJAX in Django

I am trying to create site navigation using AJAX. I have navigation menu with links to different views (using {% url name %} in template). The thing I am trying to do is to load the page content using AJAX. The page content I am trying to load is enclosed in content block ({% block content %}).
I also found this snippet http://djangosnippets.org/snippets/942/, but I want to use the views I have already defined and only get the content using ajax.
Any suggestions?
You should use django-pjax which is built exactly for that kind of thing.
All you will have to do is to, in the base template, include the whole page or just the block content based on whether the request is ajax or not.
django-pjax does the AJAX calls using the jQuery and manipulates history using HTML5 push state API, which is a very good way to do it and also gracefully degrades in IE older versions.
Template tags like {% block content %} are long gone by the time AJAX sees things. What you want to do is create a named <div> in your content block, like:
{% block content %}
<div id="content"></div>
{% endblock content %}
Then you can use something like this (jQuery) code to load the <div> when needed:
$("#content").load(url, data, loadComplete);
where url is the URL you want to load (HTML expected in return), data is the form data (if any; can be omitted), and loadComplete is the optional function to be called when the data is loaded, and is of the form function loadComplete(responseText, textStatus, XMLHttpRequest) {...}. Even if you don't want to use jQuery, you can get the non-minified jQuery source and see how they do it.

Categories