I am learning django, I added a new app,
the link can be displayed in friendly_link.html,
the code is as follows:
admin.py
from django.contrib import admin
from .models import FriendlyLink
admin.site.register(FriendlyLink)
models.py
from django.db import models
class FriendlyLink(models.Model):
title = models.CharField(max_length=100, default='', verbose_name='title')
url = models.CharField(max_length=100, default='', verbose_name='url')
class Meta:
verbose_name_plural = 'links'
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from .models import FriendlyLink
def friendly_link(request):
friendly_link = FriendlyLink.objects.order_by('title')
context = {'friendly_link': friendly_link}
return render(request, 'friendly_link.html', context)
urls.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^links$', views.friendly_link, name='friendly_link'),
]
friendly_link.html
{% extends "base.html" %}
{% block title %}Links{% endblock %}
{% block content %}
<ul>
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
{% endblock %}
base.html
{% load i18n static %}<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% block content %}{% endblock %}
<footer>
<ul>
<!--This code doesn't work-->
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
</footer>
...
</body>
I want to put the link inside the <footer> element in base.html. How do I change the code? Thank you.
You should really read this documentation page:
https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html
Each block is clickable there and there's a detailed description on how to overwrite each one.
For your problem, you will probably nav_footer
{% block nav_footer %}
{{ block.super }}
...
{% endblock %}
{{ block.super }} is optional and will append your content to the block instead of overwriting it.
Related
I am learning django and I really can't solve this error, I tried modifying every file but I can't find where the issue is.
Error:
OperationalError at /topics/
no such table: pizzas_topic
I have to mention that this exercise is from Python Crash Course 2nd Edition
Thanks
Here is the code from my project:
base.html:
<p>
Pizzeria -
Pizzas
</p>
{% block content %}{% endblock content %}
index.html
{% extends "pizzas/base.html"%}
{% block content %}
<p>Pizzeria</p>
<p>Hi</p>
{% endblock content%}
topic.html
{% extends 'pizzas/base.html' %}
{% block content %}
<p>Topic: {{topic}}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{entry.date_added|date:'M d, Y H:i'}}</p>
<p>{{entry.text|linebreaks}}</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
topics.html
{% extends "pizzas/base.html" %}
{% block content %}
<p> Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics have been addet yet.</li>
{% endfor %}
</ul>
{% endblock content %}
urls.py
"""Defines URL patterns for pizzeria."""
from django.urls import path
from . import views
app_name = 'pizzas'
urlpatterns = [
# Home page
path('',views.index, name='index'),
# Page that shows all pizzas.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
]
views.py
from django.shortcuts import render
from .models import Topic
def index(request):
"""The home page for Learning Log."""
return render(request, 'pizzas/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request,'pizzas/topics.html',context)
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'pizzas/topic.html', context)
Run:
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
I am new to Django and don't understand what really is causing this:
I have a Model Company which has an OneToOneField, creator.
# models.py
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companies'
creator = models.OneToOneField(User, related_name="company", on_delete=models.CASCADE, unique=False, null=True)
name = models.CharField(max_length=50)
I have a TemplateView class to handle get and post requests for creating a Company model:
# views.py
class create_company(TemplateView):
def get(self, request):
form = CompanyCreateForm()
title = "Some form"
return render(request, "form.html", {"form": form, "title": title})
def post(self, request):
form = CompanyCreateForm(request.POST)
if form.is_valid():
comp = form.save(commit=False)
comp.creator = request.user
comp.save()
return redirect('index')
The form is showing correctly also storing when I submit, the problem I am facing is with base.html where I show {% user.company %}; the form template extends it like:
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<form method="post" action="">
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-success" type="submit">Save</button>
</form>
<br>
</div>
<br>
{% endblock %}
and in base.html I access
{% if user.is_authenticated %}
{% user.company %}
{% endif %}
But user.company is not showing even it is set; it shows only when I redirect to index but not when I render the form.
Can someone help me understand what causes this?
{% if request.user.is_authenticated %}
{% request.user.company %}
{% endif %}
you are not sending any context to the base.html, thus only user wont work.
This was the error when I simulated your code.
Error during template rendering
In template /home/user/django/drf_tutorial/snippets/templates/base.html, error at line 2
Invalid block tag on line 2: 'user.company', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
1 {% if user.is_authenticated %}
2 {% user.company %}
3 {% endif %}
4 {% block content %}{% endblock %}
It gives hint that the code to show company should be variable {{ }} instead of tag {% %}. So the base.html template should be as below.
{% if user.is_authenticated %}
{{ user.company }}
{% endif %}
{% block content %}{% endblock %}
I can't expand the template base.html template header.html
Content base.html
<div id="main-container">
<!-- HEADER -->
{% block header %}{% endblock %}
<!-- END HEADER -->
</div>
Content header.html
{% extends "blog/base.html" %}
{% block header %}
<header id="header">
***
</header>
{% endblock %}
The output in the browser get the code:
<div id="main-container">
<!-- HEADER -->
<!-- END HEADER -->
Why not be able to extend the template?
Using {% include "blog/header.html"%} code inserted. using extends no.
Use Django 1.10.1
views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post
from django.shortcuts import render, get_object_or_404
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/index.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404 (Post, pk=pk)
return render(request, 'blog/base.html', {'post': post})
def header(request):
return render(request, 'blog/header.html')
Through
{% include "blog/header.html" %} works. So the way spelled out correctly.
Thought the error here:
def header(request):
return(request, 'blog/header.html')
def header(request):
render(request, 'blog/header.html')
def header(request):
return render_to_response (request, 'blog/header.html')
Not working (((
If you want to extend some template, you should render template with {% extends ... %} tag (in your case header.html), if you want to include something to renedered template, you should use {% include ... %} tag. You can make new template for particular page and ovreload {% block head %}, for example:
base.html:
{% block header %}
{% include 'std_header.html' %}
{% endblock %}
{% block content %}
{% endblock %}
{% block footer%}
{% endblock %}
And particular page, for example landing page will overload default header:
landing.html:
{% extends 'base.html' %}
{% block header %}
{% include 'landing_header.html' %}
{% endblock %}
{% block content %}
<!-- landing page content -->
{% endblock %}
So for view called landing_page you have to render landing.html template.
I think you would have confused between the include and extend in django templates.
Based on your file names, I assume that header.html is the partial which is to be included in the base.html and you are rendering base.html .
Django templating engine does not work this way.
Use include {% include "path/to/header.html" %} in base.html and juse have the header html in header.html.
I am trying to implement end less pagination in Django App but stuck at how to implement twitter like end less scrolling :
My models.py
from django.db import models
from django.contrib import admin
#------------------------------------------------------------------------------
class Book(models.Model):
name = models.CharField(max_length=50)
pub_date = models.DateField(auto_now_add=True)
class bookAdmin(admin.ModelAdmin):
"""Book admin class"""
list_display = ('name','pub_date')
ordering = ('name',)
admin.site.register(Book,bookAdmin)
My views.py :
from models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
#------------------------------------------------------------------------------
def latest_books(request,template = 'latest_books.html',
page_template = 'latest_books_page.html' ):
context = {}
book_list = Book.objects.order_by('-pub_date')
context.update( {'book_list': book_list, 'page_template': page_template,} )
# override the template and use the 'page' style instead.
if request.is_ajax():
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
My 'latest_books.html' template :
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
{% block js %}
{{ block.super }}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="http://yourjavascript.com/337923491/endless.js" charset="utf-8"></script>
<script type="text/javascript" src="http://yourjavascript.com/151379951/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
{% block content %}
<div class="endless_page_template">
{% include page_template %}
</div>
{% endblock %}
</body></html>
My latest_books_page.html :
<h2>Viewing All Entries</h2>
{% load endless %}
<div>
<ul>
{% paginate book_list %}
{% for book in book_list %}
<li>{{ book.name }}</li> {{ book.pub_date }}
{% endfor %}
{% show_pages %}
</ul>
</div>
I am facing two issues first if i use {{ block.super }} as given in tutorial .Django gives this error 'BlockNode' object has no attribute 'context' and if i remove {{ block.super }}. I get simple pagination with next and previous functionality .
Can someone help me please. I want to implement on scroll load pagination...
Please try out my code:
views.py :
from models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
#------------------------------------------------------------------------------
def latest_books(request,template = 'latest_books.html',
page_template = 'latest_books_page.html' ):
context = {}
book_list = Book.objects.order_by('-pub_date')
context.update( {'book_list': book_list, 'page_template': page_template,} )
# override the template and use the 'page' style instead.
if request.is_ajax():
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
latest_books.html :
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<h2>Viewing All Entries</h2>
<div class="endless_page_template">
{% include page_template %}
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}js/endless_on_scroll.js"></script>
<script src="{{ STATIC_URL }}js/endless-pagination.js"></script>
<script>
$.endlessPaginate({paginateOnScroll: true,
endless_on_scroll_margin : 10,
paginateOnScrollChunkSize: 5
});</script>
{% endblock %}
</body></html>
latest_books_page.html :
{% load endless %}
{% paginate 10 book_list %}
{% for book in book_list %}
{{ book.name }}<br> {{ book.pub_date }}<br><br><br>
{% endfor %}
{% show_more "even more" "working" %}
Try out and let me know ... and enter 20-30 entries into your DB to check it out properly ...
You have to include page_template before call the {{block.super}}
<h2>Entries:</h2>
{% include page_template %}
{% block js %}
{{ block.super }}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}endless_pagination/js/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
I am attempting to use markdown to avoid having to type HTML within my wiki form, but for some reason the form is displaying HTML code instead of the intended formatting.
My view function is as follows:
from django.shortcuts import render_to_response
from mywiki.wiki.models import Page
from django.http import HttpResponseRedirect
import markdown
def view_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
except Page.DoesNotExist:
return render_to_response('create.html', {'page_name':page_name})
content = page.content
return render_to_response('view.html', {'page_name':page_name, 'content':markdown.markdown(content)})
This is my view.html template:
{% extends 'base.html' %}
{% load wikilink %}
{% block title %}{{page_name}}{% endblock %}
{% block content %}
<h1>{{page_name}}</h1>
{{content|wikify}}
<hr/>
<a href='/mywiki/{{page_name}}/edit/'>Edit this page?</a>
{% endblock %}
And this is my base.html:
<html>
<head>
<title>{{% block title %}{% endblock %}</title>
</head>
<body>
<div>
Menu: <a href='/mywiki/Start/'>Start Page</a>
</div>
{% block content %}
{% endblock %}
</body>
</html>
I do have markdown installed, and my Django version is 1.4.1 (Mac).
Thanks.
Use Django's safe filter so as for your Html not to be escaped.
{{ content|safe }}
{% autoescape off %}
{{content|wikify}}
{% endautoescape %}
maybe ...