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>
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.
I use pagination on scroll by Django EL(Endless) Pagination library in my project.
By default show_more tag show loading word. I want customize it. I use next code but it work incorrect. It show me 9 icons and at the end don't disappear. I am little bit confused. How to fix it?
settings.py:
EL_PAGINATION_LOADING = """<i class='fa fa-cog fa-spin fa-3x fa-fw text-info text-justify endless_loading'>"""
CURRENT SOLUTION:
I found the working solution but I am not sure that its best and clear way to do that.
custom_tags.py:
from django import template
from django.utils.encoding import iri_to_uri
from el_pagination import (settings, utils)
register = template.Library()
#register.inclusion_tag('documents/show_more_info.html', takes_context=True)
def show_more_info(context, label=None, loading=settings.LOADING, class_name=None):
data = utils.get_data_from_context(context)
page = data['page']
if page.has_next():
request = context['request']
page_number = page.next_page_number()
querystring_key = data['querystring_key']
querystring = utils.get_querystring_for_page(
request, page_number, querystring_key,
default_number=data['default_number'])
return {
'label': label,
'loading': loading,
'class_name': class_name,
'path': iri_to_uri(data['override_path'] or request.path),
'querystring': querystring,
'querystring_key': querystring_key,
'request': request,
}
return {}
documents/show_more_info.html:
{% load i18n %}
{% if querystring %}
<div class="endless_container">
<a class="endless_more{% if class_name %} {{ class_name }}{% endif %}" href="{{ path }}{{ querystring }}" data-el-querystring-key="{{ querystring_key }}">
{% if label %}{{ label|safe }}{% else %}{% trans "more" %}{% endif %}
</a>
<div class="endless_loading" style="display: none;">
<div class="alert alert-info infinite-loading text-center">
<i class="fa fa-cog fa-spin fa-3x fa-fw" aria-hidden="true"></i>
</div>
</div>
</div>
{% endif %}
Finally I can use show_more_info tag instead of default show_me tag.
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 %}
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
I am trying to display the image and name in a for loop on my template.
This is what I have on my template for loop, and I thought it should work, but it doesn't
{% for op in tracked_objects %}
{% if op.is_mine %}
<div style="float:left;">
<div>
<img src="{{ op.tracked_object.image }}" alt="">
<a href='{% url track-profile op.tracked_object.id %}'>{{ op.tracked_object }}</a><br>
</div>
</div>
{% endif %}
{% endfor %}
I know that op.is_mine is true because the Name shows.
Here is my views.py:
#login_required
def profile(request):
user = request.user
tracked_objects = user.tracked_object_perms.all().order_by('is_mine',)
context = {
'tracked_objects':tracked_objects,
}
return render_to_response( 'accounts/profile.html' , RequestContext(request, context))
and finally the models.py
name = models.CharField(max_length='140')
image = models.ImageField(upload_to='img/tracked_object_images', null=True, blank=True)
Update
Now when I use the below anser of adding the .url onto the end, I get three broken image icons. Now I have checked the path and it goes to the correct image. Would this be a server issue possibly? Or something along those lines?
Try:
<img src="{{ op.tracked_object.image.url }}" alt="">
See Using django.contrib.staticfiles.