I'm transferring my website from PHP to Django, and now I have to make a sidebar.
I want the entries to come from the DB, and than I want them to become hyperlinks for other pages..
How can I do that?
nav.html
<nav class="menu" id="theMenu">
<div class="menu-wrap" data-spy="scroll">
<h1 class="logo">MY BOOKS</h1>
<i class="icon-remove menu-close"></i>
{% for question in latest_question_list %}
{{ question.naslov }}
{% endfor %}
</div>
<div id="menuToggle"><i class="icon-reorder"></i></div>
</nav>
master2.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="/static/font.min.css" rel="stylesheet">
<link href="/static/bootstrap.min.css" rel="stylesheet">
<link href="/static/font-awesome.min.css "rel="stylesheet">
<link href="/static/main.css" rel="stylesheet">
</head>
<body data-spy="scroll" data-offset="0" data-target="#theMenu">
{% include "nav.html" %}
{% include "header2.html" %}
{% block h1 %}{% endblock %}
<script src="/static/jquery.js"></script>
<script src="/static/bootstrap.min.js"></script>
<script src="/static/jquery.isotope.min.js"></script>
<script src="/static/jquery.prettyPhoto.js"></script>
<script src="/static/main2.js"></script>
</body>
</html>
views.py
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.all()
context = {'latest_question_list': latest_question_list}
return render(request, 'papers/index.html', context)
def detail(request, slug):
question = Question.objects.get(slug=slug)
return render(request, 'papers/detail.html', {'question': question})
urls.py
from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
urlpatterns = [
url(r'^$', 'papers.views.index', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<slug>[\w_-]+)/$', 'papers.views.detail', name='detail'),
]
urlpatterns += staticfiles_urlpatterns()
detail.html
{% extends "master2.html" %}
{% block h1 %}
<div id="g">
<div class="container">
<div class="row">
<h3>{{ question.naslov }}</h3>
<br>
<br>
<div class="col-lg-6 desc "><p>{{ question.opsirnije_text }}</p></div>
<div class="col-lg-4 desc desc-b">
<p>{{ question.opsirnije_text }}</p>
</div>
</div>
</div>
</div>
{% endblock %}
{% block title %} Detail {% endblock %}
You might be looking for the for template tag.
{% for question in latest_question_list %}
{{ question.naslov }}
{% endfor %}
Now, if you want the list of questions to show up on all (or almost all) pages, you could write a template context processor that adds them to all contexts.
Related
my layout:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form action = "{% url 'search' %}" method="GET">
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
<div>
Home
</div>
<div>
Create New Page
</div>
<div>
<a>Random Page </a>
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
my views.py:
def search(request):
result = set()
entries = util.list_entries()
if request.method == 'GET':
query = request.GET.get('q')
if query == '': #If it's nothing
query = 'NONE'
if query in entries:
return redirect(f'wiki/{query}')
else:
results = [entry for entry in entries if query.lower() in entry.lower()]
return render(request, "encyclopedia/index.html", {
"entries": results
})
return render(request, 'encyclopedia/search.html', {'results':result})
my urls:
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name = 'encyclopedia'
urlpatterns = [
path("", views.index, name="index"),
path('newpage/', views.new_page, name = 'newpage'),
path('wiki/<str:title>', views.entry, name = 'entries'),
path('wiki/<str:title>/edit',views.edit, name = 'edit'),
path('search', views.search, name = 'search'),
path('wiki/<str:entry>', views.random_page, name = 'random'),
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
How do i make it work? it worked before but now it just stopped working. The name in the urls matches with the name of a bar
What i have to know about url method?
I also tried to write {% url 'random'%} for a random page but it seems not working at all
When i added this to a random search url stopped working and i do not know why
Versions:
Django 4.1.4, Python 3.10.5
You have declared app_name in your urls.py file that makes it compulsory to add app_name before calling a url in django. Call your urls like this...
href={% url 'app_name:url_name' %}
So your code will be like this...
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form action = "{% url 'encyclopedia:search' %}" method="GET">
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
<div>
Home
</div>
<div>
Create New Page
</div>
<div>
<a>Random Page </a>
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
Basically, what happens here, the list user_data doesn't get passed to the template, I can't figure out why. Does anyone have any ideas please? When I use the search bar I just get the else condition from the template, and it never shows any variable. I also tried to create different variables to pass to the template, but none of them got passed for some reason.
This is in my views.py:
#login_required(login_url='login_user')
def profiles(request):
context = {}
if request.method == "POST":
data = request.POST.get('search_input')
if len(data) > 0:
username_result = NewUser.objects.filter(username__icontains=data).distinct()
email_result = NewUser.objects.filter(email__icontains=data).distinct()
user_data = []
for account in username_result:
user_data.append((account, False))
context['usernames'] = user_data
return render(request, "profiles/search_user.html", context)
else:
return render(request, "profiles/profiles.html")
return render(request, "profiles/profiles.html")
Then my template looks like this:
{% extends 'profiles/base.html' %}
{% block title %}One For All{% endblock %}
{% load static %}
<!-- importing css file -->
{% block style %}<link rel="stylesheet" type="text/css" href="{% static 'css/search_user.css'
%}">{% endblock %}
{% block content %}
<!-- navigation bar -->
<div class="navBar">
<!-- logo and logo spacers -->
<div class="logo_spacer"></div>
<div class="logo"></div>
<!-- Sign Up Button -->
<a class="homeBtn" href="{% url 'profiles' %}">Home</a>
{% if is_self %}
<a class="settingsBtn" href="{% url 'settings' user=user.username %}">Profile Settings</a>
{% else %}
<a class="settingsBtn" href="{% url 'user_profile' username=user.username %}">My Profile</a>
{% endif %}
<p>Top Menu</p>
</div>
<!-- main body of login page -->
<div class="main">
{% if user_data %}
<p>We find users</p>
{% for account in user_data %}
<div>
<a class="profile-link" href="{% url 'user_profile' username=user.0.username %}">
<!--<img class="img-fluid profile-image" src="{{account.0.avatar.url}}" alt="">--></a>
</div>
{% endfor %}
{% else %}
<p>This is when user_data doesn't exist or doesn't get passed to template: {{ user_data }} </p>
{{ user_data }}
{% endif %}
</div>
<div class="bottom">
<p>Bottom</p>
</div>
{% endblock %}
{% block js_block %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('logout/', views.logoutUser, name='logout'),
path('post/', views.post, name='post'),
path('', views.profiles, name='profiles'),
path('search_user/', views.profiles, name='profiles'),
path('UserProfile/<str:username>/', views.user_profile, name='user_profile'),
path('Settings/<str:user>/', views.settings, name='settings'),
]
In the view you set:
context['usernames'] = user_data
But in the template you reference:
{% if user_data %}
<p>We find users</p>
{% for account in user_data %}
user_data doesn't exist in the context - you need to reference usernames instead, or change the view to call it user_data
Im really lost about this, im trying to understand a django inheritance template about
I have a layout with a navbar and html structure:
todos/templates/todos/layout.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<title>Practice Django</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark justify-content-between">
<div>
<a class="navbar-brand" href="/">Django app</a>
Page 1
Page 2
</div>
<form action="" class="form-inline">
<input
type="search"
placeholder="Search Todo"
aria-label="Search"
class="form-control mr-sm-2"
/>
<button type="submit" class="btn btn-outline-success my-2 my-sm-0">
Search
</button>
</form>
</nav>
<div class="container">
{% block content %} {% endblock %}
</div>
</body>
</html>
then im trying to setup a index page with a grid, a column for show todos and the another one for create a new todo.
todos/templates/todos/base.html
{% block content %}
<h1 class="text-center">Base Page</h1>
<div class="row">
<div class="col">
{% block todolist %}
{% include 'todos/todos_list.html' %}
{% endblock %}
</div>
<div class="col">
{% block addtodo %}
{% include 'todos/add_todo.html' %}
{% endblock %}
</div>
</div>
{% endblock %}
todos/templates/todos/add_todo.html
{% extends 'todos/base.html' %}
{% block addtodo %}
<h3 class="text-center">subpage addtodo</h3>
{% endblock %}
todos/templates/todos/todos_list.html
{% extends 'todos/base.html' %}
{% block todolist %}
<h3 class="text-center">subpage todolist</h3>
{% endblock %}
For try to understand it, i made a same classes for both views, todo_list and add_todo from different class sources.
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader
from django.views.generic import ListView, DetailView
from .models import Todo
class TodoList(ListView):
template_name = 'todos/todos_list.html'
context_object_name= 'todos'
# Lo que devuelve esta funcion se añade al context object name
def get_queryset(self):
return Todo.objects.all()
class AddTodo(ListView):
template_name = 'todos/add_todo.html'
context_object_name= 'todos'
# Lo que devuelve esta funcion se añade al context object name
def get_queryset(self):
return Todo.objects.all()
My urls.py i guess, to show both classes in index pages, the same route url
from django.urls import path
from . import views
urlpatterns = [
path('', views.TodoList.as_view(), name='todolist'),
path('', views.AddTodo.as_view(), name='addtodo')
]
But this does not work, with this error:
RecursionError at /
maximum recursion depth exceeded while calling a Python object
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.1
Exception Type: RecursionError
Exception Value:
maximum recursion depth exceeded while calling a Python object
Exception Location: /home/adrian/.local/lib/python3.8/site-packages/django/utils/functional.py, line 241, in inner
Python Executable: /usr/bin/python3
Python Version: 3.8.2
Python Path:
['/home/adrian/code/python/practice',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/adrian/.local/lib/python3.8/site-packages',
'/usr/local/lib/python3.8/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Thu, 24 Sep 2020 16:43:24 +0000
I was thinking to make both operations (show todo list and add a new todo form) with the same class, but i dont know how do it that properly, the object its show a both classes, templates in the same route, in this case in root /.
Any clues about? thanks in advance
You should not use {% include %}, since then you end up with infinite recursion. You can for example make a base:
{% block content %}
<h1 class="text-center">Base Page</h1>
<div class="row">
<div class="col">
{% block items %}
{% endblock %}
</div>
<div class="col">
{% block otheritems %}
{% endblock %}
</div>
</div>
{% endblock %}
If you later use {% extend … %} [Django-doc], it means you take the entire template of the one your refer to, but for the blocks you specify and the "child template", you render another value. So your child can look for example as:
{% extends 'todos/base.html' %}
{% block items %}
<h3 class="text-center">subpage addtodo</h3>
{% endblock %}
{% extends 'todos/base.html' %}
{% block items %}
<h3 class="text-center">subpage todolist</h3>
{% endblock %}
Here you will thus render the <h1 class=""> part in the child templates. The only thing that will differ is that the part in the block {% block items %} … {% endblock %} by the content you provide.
Here it however looks like you want two views to provide content for the same page. That is not how it works. A view is the logic that maps a request to a response. A view does not per se renders a template, nor does it only renders maximum one template. A view can render as much templates as you want.
If you thus want a single page with two items to fill in, you make a view, that renders for example a template that fills in the two blocks. So we thus define a single URL pattern for this path:
from django.urls import path
from . import views
urlpatterns = [
path('', views.TodoList.as_view(), name='add_todo'),
]
and in the view, we allow one to also access the list of todos:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader
from django.views.generic import ListView, DetailView
from .models import Todo
class TodoList(CreateVieww):
template_name = 'todos/todos_list.html'
model = Todo
fields = '__all__'
def todos(self):
return Todo.objects.all()
in the template, we finally fill in two blocks: one with the Todos, and one with the form:
{% extends 'todos/base.html' %}
{% block items %}
{% for todo in view.todos %}
{{ todo }}
{% endfor %}
{% endblock %}
{% block otheritems %}
<form method="post" action="{% url 'add_todo' %}">
{{ form }}
</form>
{% endblock %}
Hi guys I am studying django framework using "django by example" book. The problem I am facing is that the template language does not work even I copy and pasted source code from book and/or github.
A blog application that has post model and is inside the mysite project.
You can see the code in picture and the result too:
Inside blog\templates\blog .
blog\templates\blog\base.html
<!-- its base.html -->
{% load staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>My blog</h2>
<p>This is my blog.</p>
</div>
</body>
</html>
Its the list that extends base.html and located in blog\template\blog\post:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
Here is views.py
from django.shortcuts import render, get_list_or_404
from .models import Post
def post_list(request):
posts=Post.published.all()
return render(request,'blog/post/list.html',{'posts':posts})
def post_detail(request, year, month, day, post):
post=get_list_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request,'blog/post/detail.html',
{'post':post})
I am trying to implement the django-registration-redux and have used templates written by Andres available at https://github.com/macdhuibh/django-registration-templates . But the problem is whever i run anything i get the NoReverseMatch Error.
I tried to render the base.html template to check the error and i got error on line 12.
and the base.html is as
{% load i18n %}
<html lang="en">
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
<title>{% block title %}User test{% endblock %}</title>
</head>
<body>
<div id="header">
{% block header %}
{% trans "Home" %} |
{% if user.is_authenticated %}
{% trans "Logged in" %}: {{ user.username }}
({% trans "Log out" %} |
{% trans "Change password" %})
{% else %}
{% trans "Log in" %}
{% endif %}
<hr />
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
<div id="footer">
{% block footer %}
<hr />
{% endblock %}
</div>
</body>
</html>
index.html is as
{% extends "base.html" %}
{% load i18n %}
{% block content %}
Index page
{% endblock %}
and the urls.py as
from django.conf.urls import url
from . import views
app_name = 'forum'
urlpatterns = [
url(r'^$', views.index, name='index'),
]
and i get the error as in the below image:
Error
You probably need to specify the app name in the tag:
{% trans "Home" %}