I am trying to create a blog index page where all the blog post entries are shown. But i want to limit the content of the post body to certain amount (Similar to any blog you see on the internet) so not all the content is visible but when user click on Read More link he can see that particular post in details.
I know how to create page for single article but i am not able to figure out how to limit the post body content. Do i need to change anything in the model or i can do this directly from templates
<h1>{{ post.title }}</h1>
<p>{{ post.post_body }}</p>
Read More
I have declared post body as textfield
post_body = models.TextField()
truncatechars¶
Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis sequence (”...”).
Argument: Number of characters to truncate to
For example:
{{ value|truncatechars:9 }}
If value is "Joel is a slug", the output will be "Joel i...".
docs
You can use Built-in Template tag "truncatewords", like this below:
{{ post.post_body | truncatewords:50 }}
This will show the first 50 words of your post.
Here is the Documentation
Related
So I want to make a blog post with HTML formatting from the admin page directly. For example from the models.py, you see the description is a TextField. When I go to the admin page to make a blog post, I want to be able to add HTML tags to my blog. So the text field will have HTML content. While I call the blog post onto the HTML template I want it to read the description as a HTML file and not just a text field.
models.py
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date = models.DateField()
Blog.description at admin page
<HTML>
<body>
<p>Welcome to my first blog post!!</p>
</body>
</html>
blog.html
<h1>{{ blog.title }}</h1>
<hr>
<p>{{ blog.description }}</p>
Any help is appreciated. Thanks!
You can render it with the |safe template filter [Django-doc]. This will disable escaping HTML fragments, and it will thus no longer convert < to < for example:
<h1>{{ blog.title|safe }}</h1>
<hr>
<p>{{ blog.description|safe }}</p>
You however might want to take a look at the django-ckeditor package [GitHub] which offers a dedicated field, widget, etc. to enable editing the text with respect to rendering.
I'm using CKEditor rich text field for my Django blog app. But not getting the desired output. If I write some heading text, on the front end the output is <h1> Hello </h1>. But I don't want heading tags, I also tried to striptags but in that case, the output is not heading it is simple paragraph text
index.html
{% for posts in post %}
<div>{{posts.content|striptags}}</div>
{% endfor %}
Rich text model
content = RichTextField(blank = True ,null = True)
I guess you want the safe filter, which tells django you know you are doing something a little bit dangerous, and it should not try to protect you.
{% posts.content|safe %}
that will actually render the html (including any malicious javascript a user may have entered (ie i would strongly recomend using a package like bleach or html-sanitizer to only allow specific html tags)
I am learning django from MDN.And i was working on locallibrary.There i got one problem.
I want to send only books on author page but not all book,only current page's author book.
If url is
/author/1
then sent only book of author id 1, not all
In AuthorDetailView i tried context['books']=Book.objects.filter(author__exact=Author.id).
but it give error
**TypeError at /catalog/author/1**
**int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'**
When i write context['books']=Book.objects.filter(author__exact=1)
then it send only authorid 1's book on all page.
on author/2.
so i want to send authorid 2's book on author/2. 3's book on author/3.
But not all books on everypage.
It doesn't make sense to send all objects when needed few.
{% for book in books%}
{% if author.id is book.author.id %}
<li>
{{ book.title }} ({{book.author}})
</li>
{% endif %}
This code do what i wanted but by sending all objects.
I hope you understand what i want.
Here is my models,views https://pastebin.com/yY6M5LUA
filter will send you a queryset not a objects, what you need to do is to get the objects corresponding to the need, for eg, Book.objects.filter(author__exact=Author.id)[0] will give you the first object from the queryset, so you get the object from here.
You are using a DetailView, so you already have the current author in the context. So there's actually no reason to do anything in the view - you can remove your get_context_data method. Instead, you can follow the reverse relationship in the template:
{% for book in author.book_set.all %}
{{ book.title }}
{% endfor %}
I'm using Django to create an application with different types of words / terms. On one page, you may have the title "Terms" and then a list of terms. On another page, you have the exact same thing but for phrases (header, list of phrases).
Is it possible to do something like this -->
Store header and list for terms
Store header and list for phrases
Create one template that is used to show headers and lists on a
page
Call some Django function (not sure if this exists) that uses
the template to generate a page for terms
Use that same Django
function that uses the same template to generate the page for
phrases
The hope is that I can avoid having one large template folder full of pages that are basically doing the same thing. For example, right now, if I wanted to add phrases_in_spanish and phrases_in_french, I'd have to add two new templates that are basically doing the same thing --> showing the header and the list. All I want to do is store the header and list somewhere and have Django do the rest of the work to create the pages. So I could technically have 1,000 pages without having to write 1,000 different template files that are all just showing headers and lists.
Template example:
{% extends "profile/base.html" %}
{% block content %}
<div class="row">
<div class="col-sm-6">
Add a New Term
<p>Terms:</p>
<ul>
{% for term in terms %}
<li><p>{{ term.name }} : {{ term.definition }}</p></li>
Edit Term
Delete Term
{% empty %}
<li>No terms have been added yet.</li>
{% endfor %}
</ul>
</div>
</div>
{% endblock content %}
You don't have to create an html template for each page.
You have to create a URL dispatcher on urls.py:
url(r'^(P<list_name>\w+)/$', views.your_view)
So instead of having many templates that have the same structure, you render only one with the info you want.
So your view should look like this:
def your_view(request, list_name):
list = get_object_or_404(List, pk=list_name)
context = {
'list_info':list.info
}
return render(request, 'your_app/template.html', context)
Of course in this example you need to have a table called List on your database with primary key list_name.
Maybe it would be possible to have a model called something generic like Concept (this could be Terms or Phrases or Headers or something similar) with a related model like ConceptDetail (which could be a list of terms or list of phrases, etc).
Then you have one URL config but different concepts have different PKs which appear in the URL to differenciate them (you can also use slugs in URL as kwargs to make the URLs more readable). For example:
path('concept/', ConceptListView.as_view()),
path('concept/<slug:concept_name>/', ConceptDetailView.as_view()),
As for views and templates, you have a ListView that shows you all the concepts (here you can add filtering and other search options) and then in the DetailView of each concept you could display its related ConceptDetail instances.
Does this sound like something that could help you?
Following is the simple database model i have:
class Notes(db.Model):
text = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
Now in the url handler, i send all the notes to the template as follows:
class MainPage(webapp2.RequestHandler):
def get(self):
notes = Notes.all()
self.render_template("index.html", {'notes':notes})
In the template i am using jinja2 templating engine, i want the id of each of the notes to be printed, so that i can embed an edit link, somewhat like this:
{% for note in notes %}
<p>
{{ note.text }} <br>
{{ note.date }} <br>
(edit )
{% endfor %}
But the trouble is, i dont see anything printed, in place of note.key.id
As per the docs over here key class represents a unique key for a database entity and this has a method id, its a numeric value. for a single note from the collection of notes i want the id of the note.
If i use the django templating engine i get the values {{ notes.key.id }} printed, but with jinja2 i dont see it.
How can i do this?
Well replace the href line with the following:
(edit )
This shall be enough.