I have the same code on localhost and on server (thanks to mercurial), but it works a little bit different. I want to render category and its subcategories in template using this code:
views.py:
def category(request, category_slug):
try:
category = Category.objects.get(slug=category_slug)
except:
raise Http404
subcats = category.get_children()
return render_to_response('catalogue.html',
{'category': category,
'subcats': subcats,
'header_template':'common/includes/header_%s.html' % flixwood_settings.CURRENT_SITE
},
context_instance=RequestContext(request))
template:
<div class='subcats'>
{% for subcat in subcats %}
{% ifequal subcat.level 1 %}
<div class="item">
<img src="{% thumbnail subcat.image 66x66 %}" class="thumb">
{{ subcat.category }}
{{ subcat.short_description|safe }}
<div class="clear_left"></div>
</div>
{% cycle '' '' '<div class="clear_left"></div>'|safe %}
{% endifequal %}
{% endfor %}
</div>
but however this code works perfectly on localhost (subcategories are rendering right) - it doesn't work on server, and the {{ subcats|length }} returns 0.
I compared values from MySQL bases on localhost and on server - they are right and inheritance should work. The funniest thing is that the same query works perfectly in manage.py shell on server.
What the hack is wrong with it?
The problem was solved - it was in .pyc files, which are recreating only after apache is restarted. That's why the right code in .py files didn't work.
Related
When I requested tag_list view the posts variable didn't list out the data.
And after changing its position above self_entries view, everything worked fine.
But now I cannot get self_entries view data.
What I am missing here?
After changing the position everything falls as expected but the view which lies at the bottom doesn't display the data at all.
more views at the top
#app.route('/entries')
#login_required
def list():
posts = models.Journal.select().order_by(models.Journal.created_at.desc())
return render_template("entries.html", posts=posts)
# This View Works as expected
#app.route('/entries/<username>')
#login_required
def self_entries(username):
posts = (models.Journal
.select(models.User, models.Journal)
.join(models.User)
.where(models.User.username**username)
.order_by(models.Journal.created_at.desc())
)
# for post in posts:
# print(post.title + str(post.created_at.date()) + post.tag)
return render_template("entries.html", posts=posts)
# This view doesn't... the page displays as empty
#app.route('/entries/<tag>')
#login_required
def tag_list(tag):
posts = (models.Journal
.select()
.where(models.Journal.tag == tag)
.order_by(models.Journal.created_at.desc())
)
return render_template("entries.html", posts=posts)
more views at the bottom
entries.html
{% extends "layout.html" %}
{% block content %}
<div>
<div>
<h1>{{ hi }}</h1>
{% for post in posts %}
<article>
<h2>{{ post.title }}</h2>
<time datetime="{{ post.created_at }}">{{ post.created_at.date() }}</time>
<h3><a href="{{ url_for('tag_list', tag=post.tag) }}" >{{ post.tag }}</a><h3>
</article>
{% endfor %}
</div>
</div>
{% endblock %}
Ok got it. Both the route below are using the similar API ie. '/entries/', so there is a conflict. so change either one.
#app.route('/entries/<username>')
#app.route('/entries/<tag>')
changed #app.route('/entries/<tag>') to #app.route('/entry/<tag>') it works.
I've created my own theme for Pelican and I've been using it for a while to build my site. I've decided to start blogging again so I'm only now adding the blog features to the site.
I've created my own blog.html template to render the content in the way I want. I started by copying and pasting the code from the 'simple' theme that comes with Pelican to get me started, but even though it is unchanged I'm getting an 'articles_page' is undefined error when I try to build.
Where is the article_page variable set from? I tried adding to my pelicanconf.py file but it didn't help.
{% extends 'base.html' %}
{% block title %}{{ page.title }} — Ricky White{% endblock title %}
{% block content %}
<section class="wrapper">
<div class="container">
<div class="row">
<div class="col">
<ol id="post-list">
{% for article in articles_page.object_list %}
<li><article class="hentry">
<header> <h2 class="entry-title">{{ article.title }}</h2> </header>
<footer class="post-info">
<time class="published" datetime="{{ article.date.isoformat() }}"> {{ article.locale_date }} </time>
<address class="vcard author">By
{% for author in article.authors %}
<a class="url fn" href="{{ SITEURL }}/{{ author.url }}">{{ author }}</a>
{% endfor %}
</address>
</footer><!-- /.post-info -->
<div class="entry-content"> {{ article.summary }} </div><!-- /.entry-content -->
</article></li>
{% endfor %}
</ol><!-- /#posts-list -->
{% if articles_page.has_other_pages() %}
{% include 'pagination.html' %}
{% endif %}
</div>
</div>
</div>
</section>
{% endblock content %}
You must have referenced your template from one of the articles using:
Template: blog
If you remove that reference and add the following lines to your pelicanconf.py, Pelican will generate blog.html directly from your template file:
DIRECT_TEMPLATES = ['index', 'blog']
PAGINATED_DIRECT_TEMPLATES = ['blog']
(Do not forget to empty your output folder before running pelican. Tested on Pelican 3.7.1)
For the sake of future visitors who might come here looking for an answer like I did:
The problem can have a good number of very diverse reasons. In my case it was not a problem with the configuration of the pelican tooling, but rather an error in the metadata of some of my content pages. I had not included the correct category, date or tag fields. You'd never guess that from the error message now, would you?
I found this question looking for the same error.
In my case the reason was an issue which has been closed but not merged in the current release of the Attila theme. More precisely: the error is caused by a template in the templates folder of the theme which has a wrong reference inside it. In the specific case, inside the page template there was a wrong reference to article.
Changing the template manually fixed the issue:
--- a/attila-1.3/templates/page.html
+++ b/attila-1.3/templates/page.html
## -21,8 +21,8 ##
{% else %}
{% set selected_cover = SITEURL+"/"+HEADER_COVER %}
{% endif %}
-{% elif article.color %}
- {% set selected_color = article.color %}
+{% elif page.color %}
+ {% set selected_color = page.color %}
{% elif HEADER_COLOR %}
{% set selected_color = HEADER_COLOR %}
{% endif %}
I hope this helps debugging similar errors.
The page variable articles_page is set in only one place: Writer._get_localcontext and there is a guard condition:
if paginated and template_name in self.settings['PAGINATED_TEMPLATES']:
# ... code ...
paginated_kwargs.update(
{'%s_paginator' % key: paginator,
'%s_page' % key: page, # <-- Creates `article_page`
'%s_previous_page' % key: previous_page,
'%s_next_page' % key: next_page})
If this problem crops up, the easiest solution is to make sure the guard condition evaluates to True. Most likely, the problem is that template_name is not in PAGINATED_TEMPLATES in your configuration file. I opened writers.py, added a print(f"template_name is {template_name}") and got my answer (I didn't have author : None in my PAGINATED_TEMPLATES dictionary).
I've got some basic experience building websites using a LAMP stack. I've also got some experience with data processing using Python. I'm trying to get a grip on the mongodb-flask-python thing, so I fired everything up using this boilerplate: https://github.com/hansonkd/FlaskBootstrapSecurity
All is well.
To experiment, I tried declaring a variable and printing it...
I get this error message:
TemplateSyntaxError: Encountered unknown tag 'x'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
Here's my main index.html page
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12">
Hello World, at {{ now }}, {{ now|time_ago }}
</div>
</div>
<div class="row-center">
<div class="col">
{% x = [0,1,2,3,4,5] %}
{% for number in x}
<li> {% print(number) %}
{% endfor %}
</div>
</div>
{% endblock %}
I love learning new things, but man, can I ever get hung up for hours on the simplest of things... any help would be greatly appreciated!!!
Flask uses Jinja as its default templating engine.
The templating language is python-esque, but is not python. This is different from something like a phtml file, which is php interspersed with html.
Check the jinja documentation for more of what you can do, but here's how you set a variable within a template:
{% set x = [0,1,2,3,4,5] %}
http://jinja.pocoo.org/docs/2.9/templates/#assignments
Try this:
{% set x = [0,1,2,3,4,5] %}
See Jinja docs.
I want to have my url pattern like the below pattern:
host:8000/archive/2/
I define page_kwarg in my view but I still receive: host:8000/en/2
Code form main url.py file:
url(_(r'^archive'), include('events.urls_archive', namespace='archive')),
start edit1
and link form main site to my app:
<a href="{% url 'archive:list' %}" title="{% trans 'Archive' %}">
{% trans 'Archive' %}
</a>
end edit1
start edit2
This is the url in my app urls_archive.py:
urlpatterns = [
url('^/(?P<page>\d+)/$', ArchiveListView.as_view(), name="list"),
url('^/(?P<slug>[-\w]+)/(?P<pk>\d+)$', ArchiveDetailView.as_view(), name="detail"),
]
end edit2
The code for my view:
class ArchiveListView(ListView):
model = Booking
queryset = Booking.objects.filter(period__type='archive').order_by('-date_start')
paginate_by = 80
page_kwarg = 'page'
Here is my template code:
{% if is_paginated %}
{% if page_obj.has_previous %}
<h4>Previous</h4>
{% endif %}
<span class="arrow header"><h4>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</h4></span>
{% if page_obj.has_next %}
<h4>Next</h4>
{% endif %}
{% endif %}
Please provide any help.
Thanks.
page_kwarg sets the key that the page number is passed in as. It doesn't affect how it is used in the page. For some reason, you are outputting that directly as /{{ page_obj.previous_page_number }}, which resolves to just /2. You should output it in the same format as it is passed in:
?page={{ page_obj.previous_page_number}}
Edit
If you want your page number to be specified as part of the path arguments, you should use the url tag, like any other URL:
{% url 'archive' page=page_obj.previous_page_number %}
I tried to show similar posts to an article in an aside column. A feauture sites like youtube and even stack overflow. Not having anyone to ask about it, I assumed articles listed on the side were ones with similar tags. But it's not working its saying nothing matches. this is what I had in my post_detail.html:
{% block content %}
<div class="row" style="margin-top: 70px">
<div class="col-sm-8">
{% if instance.image %}
<img src='{{ instance.image.url }}' class="img-responsive" />
{% endif %}
<p>Share on:
<a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}">
Facebook
</a>
<a href="https://twitter.com/home?status={{ instance.content | truncatechars:80 | urlify }}%20{{ request.build_absolute_uri }}">
Twitter
</a>
<a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'></a>
<a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}&title={{
instance.title }}&summary={{ share_string }}&source={{ request.build_absolute_uri }}">
Linkedin
</a>
</p>
<h1>{{ title }}<small>{% if instance.draft %}<span style="color:red"> Draft</span>{% endif %} {{instance.publish}}</small></h1>
{% if instance.user.get_full_name %}
<p>By {{ instance.user.get_full_name }}</p>
{% else %}
<p>Author {{ instance.user }}</p>
{% endif %}
<p><a href='{% url "posts:list" %}'>Back</a></p>
<p><a href='{% url "posts:delete" instance.id %}'>delete</a></p>
<p>{{instance.content | linebreaks }}</p>
<hr>
</div>
<div class="panel panel-default pull-right" style="height: 1000px">
<div class="panel-heading">
<h3 class="panel-title">Similar Articles</h3>
</div>
==========right here====================
<div class="panel-body">
{% for tag in instance.tags.all %}
<h4> {{ tag.title }} </h4><hr>
{% endfor %}
</div>
==========right here====================
</div>
</div>
{% endblock content %}
and this is my view
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
context = {
"title": "detail",
"instance": instance,
"share_string": share_string,
}
return render(request, "posts/post_detail.html", context)
if this approach is beyond syntax correction and needs to be rewritten. I don't mind writing it over the correct way. This is my second month working with Django. To me this way made sense but it's not working. And are sites like youtube which has a video and similar videos to the right of the main video, are those videos there because they share similar tags? any and all help is welcome.
In the long run and to not reinvent the wheel using a reusable Django application already tried and tested is the sensible approach. In your case there is such app: django-taggit
and is easy to use:
You install it
pip install django-taggit
Add it to your installed apps:
INSTALLED_APPS = [
...
'taggit',
]
Add its custom manager to the model on which you want tags
from django.db import models
from taggit.managers import TaggableManager
class YourModel(models.Model):
# ... fields here
tags = TaggableManager()
and you can use it in your views:
all_tabs = instance.tags.all()
It even has a similar_objects() method which:
Returns a list (not a lazy QuerySet) of other objects tagged similarly
to this one, ordered with most similar first.
EDIT
To retrieve similar posts you should use:
similar_posts = instance.tags.similar_objects()
and to get only the first, let's say, 5 similar posts:
similar_posts = instance.tags.similar_objects()[:5]
where instance is a instance of the Post model.
you should let us know what is not matching.
your post_detail tries to find a Post with a tag's slug.
instance = get_object_or_404(Post, slug=slug)
I doubt that's what you intended.
get_object_or_404 either tries to find an exact match or raise error.
Since your original post has the tag, you will be getting the same post or multiple.
The following block of code is not what you said you wanted either.
{% for tag in instance.tags.all %}
<h4> {{ tag.title }} </h4><hr>
{% endfor %}
It lists all tags of the original post, doesn't list related post (via tag)
If you want to show related post, and you intent to use tag to define relatedness, define a method in your post model to return such related posts.
def get_related_posts_by_tags(self):
return Post.objects.filter(tags__in=self.tags.all())
are those videos there because they share similar tags?
Not sure how they judge the relatedness, you should ask that in a separate question.
If I have to guess, it would be more than just tag comparison though.
** edit
Actually, proper term for relatedness is similarity.
You might find further info by googling document similarity.
{% for post in instance.get_related_post_by_tag %}
// href to post.absolute_url
{% endfor %}