I'm trying to loop through a database and output the results in a django template. I got all that working but it outputs every item as the following in the html:
[u'AMD', u'A10-7700K, 3,4 GHz (3,8 GHz Turbo Boost) FM2+ processor']
[u'\n 3.400 MHz\xa0\n ', u'\n 4 cores\xa0\n ', u'\n FM2+\xa0\n ']
For the record. I want it to output as a normal string without the unicode. I tried a bunch of things but none of it seems to work. I would write down all the things I've tried but I honestly can't even keep track of all of it.
I got the following django files, I'll only write down the relevant pieces:
views.py:
def processoren(request):
processoren = Processoren.objects(categorie__contains='Processor')[:10]
#processoren = json.dumps(list(processoren)
return render_to_response('processoren.html', {'Processoren': processoren},
context_instance=RequestContext(request))
models.py:
from django.db import models
from mongoengine import *
from APc.settings import DBNAME
connect(DBNAME)
class Processoren(Document):
categorie = StringField(max_length=120)
naam = StringField(max_length=500)
subnaam = StringField(max_length=500)
info = StringField(max_length=500)
stock = StringField(max_length=500)
enter code hereprijs = StringField(max_length=120)
processoren.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container">
<div class="col-md-4 col-lg-2">
</div>
<div class="col-md-8 col-lg-10">
<div class=" top-margin">
<h1>Processoren</h1>
{% for processor in Processoren %}
<div class="list-group">
<div class="list-group-item">
<div class="row-picture">
<img class="square" src="http://lorempixel.com/56/56/people/1" alt="icon">
</div>
<div class="row-content">
<h4 class="list-group-item-heading">{{ processor.naam }}</h4>
<p class="list-group-item-text">{{ processor.info }}</p>
<p class="list-group-item-text pull-right">{{ processor.prijs }}</p>
<p class="list-group-item-text pull-right">{{ processor.stock }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
I tried to simply just put str() after processor.naam for example but that doesn't work either. What does work is adding 0 after processor.naam but then I of course only get the first index which would be "AMD". Any help would be appreciated.
This is nothing to do with Unicode. You have a list of items, you need to iterate through them.
{% for name in processor.naam %}{{ name }}{% endfor %}
Not being familiar with MongoEngine in regards to Django, it's fairly simple to convert your unicode values to strings, which will hopefully get you by for the time being until you can address the root of the problem.
objects = Processoren.objects.filter(categorie__contains='Processor')[:10]
processoren = [str(p.naam) for p in objects]
Again, I don't know what methods are available on the query set using that engine, so I've avoided using values_list in this case. Wasn't sure which property you needed to output either so I just used naam
Related
I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ?
I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use.
Any ideas? (I am a beginner in django)
VIEWS.PY
from django.shortcuts import render
import requests
from . import models
def index(request):
return render(request, 'base.html')
def new_search(request): ********NOT IMPORTANT (I THINK)********
search = request.POST.get('search')
models.Search.objects.create(search=search)
objects = models.Object.objects.all()
results = objects.filter(name__contains=search).all()
args = { 'results': results }
return render(request, "my_app/new_search.html", args)
def individual_page(request):
link = request.GET.get('object-link')
objects = models.Object.objects.all()
return render(request, "my_app/individual_page.html")
MY TEMPLATE
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2 style="text-align: center">{{ search | title }}</h2>
<div class="row">
{% for result in results %}
<div class="col s4">
<div class="card medium">
<div class="card-image">
<a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a>
</div>
<div class="card-content">
<p>{{result.name}}</p>
</div>
<div class="card-action">
View listing: Price TEST
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
So, the thing I want to do is: when I press the anchor tag that includes the image, I get redirectioned to another page which contains only that one object's info.
anyone can help me with python django models, here is my code
models.py
class honeymoon(models.Model):
locationh = models.CharField(max_length=100)
imgh = models.ImageField(upload_to='locations')
detailh = models.TextField()
def __str__(self):
return self.locationh
views.py
def top10_honeymoon(request):
context = {
'posth': honeymoon.objects.all()
}
return render(request,'shop/honeymoon.html',context)
html
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
<h2 class="blog_location">{{ posth.locationh }}</h2><br>
<img class="blog_img" src="{{ posth.imgh.url }}"><br>
<p class="blog_details">{{ posth.detailh }}</p><br><br>
</div>
admin.py
admin.site.register(honeymoon)
i'm trying to make model and trying to add some items from admin blog but its not displaying anything in my site, and not even showing the error. data is uploading from admin panel but its not displaying
you have to loop through the instances to see it
{% for obj in posth %}
<h2 class="blog_location">{{ obj.locationh }}</h2><br>
<img class="blog_img" src="{{ obj.imgh.url }}"><br>
<p class="blog_details">{{ obj.detailh }}</p><br><br>
{% endfor %}
try this :
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
{% for post in posth.all %}
<h2 class="blog_location">{{ post.locationh }}</h2><br>
<img class="blog_img" src="{{ post.imgh.url }}"><br>
<p class="blog_details">{{ post.detailh }}</p><br><br>
{% endfor %}
</div>
Django cannot iterate itself. that's why you enable to show data.
You have to use for loop to show data in webpage
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
{% for item in posth %} # add this
<h2 class="blog_location">{{ item.locationh }}</h2><br>
<img class="blog_img" src="{{ item.imgh.url }}"><br>
<p class="blog_details">{{ item.detailh }}</p><br><br>
{% endfor %} # add this
</div>
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 have an HTML page displaying a database populated by emails. I have them displayed in a collapsible, and for each post the timestamp of it is what toggles it and the innards are the email itself. The HTML page is structured like this:
{% extends "base.html" %}
{% block content %}
{% for email in emails %}
<div><button class="btn" data-toggle="collapse" data-target="#demo">{{ email.timestamp }}</button>
<div id="demo" class="collapse">
{{ email.body }}
</div>
{% endfor %}
{% endblock %}
relevant portion of views.py
#app.route('/cruz')
def cruz():
u = Politician.query.get(1)
emails = u.emails.all()
return render_template('cruz.html',title='Ted Cruz',emails=emails)
which produces a webpage that looks like this: http://imgur.com/noqC40E
The problem is that no matter which of those timestamps I click, only the first collapsible opens and closes. I've tried a number of things to fix it, mostly messing around with the HTML page and the for blocks and where I place the {{ email.body }}, but nothing I do seems to work. Can anyone see where this is going wrong?
You are generating the same id attribute for your div each time:
<div id="demo" class="collapse">
You almost certainly need to generate unique ids. You could generate unique ids by adding the loop index perhaps:
<div id="demo-{{loop.index}}" class="collapse">
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 %}