Adding css i js to python templates - python

I have a problem with including css and js files. My index page works fine, but when I try to put the same code to the detail page it doesn't work, not even html wich I wrote on detail.html, just the include files from master.html work. What can be the problem?
master.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-target="#navbar" data-offset="0">
{% include "header.html" %}
{% include "carausel.html" %}
{% block h1 %}{% endblock %}
{% include "footer.html" %}
<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/main.js"></script>
</body>
detail.html
{% extends "master.html" %}
{% block h1 %}
<div class="box first">
<div class="row">
<div class="container">
{% for question in latest_question_list %}
<div class="col-xs-12 col-sm-4 col-md-3">
<div class="center">
<h4>{{ question.naslov }} </h4>
<p>{{ question.opis }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
{% block title %} Detail {% endblock %}
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()

Use absolute paths for all your static links.
<link href="/static/....
<script src="/static/...

Related

Making search bar in django

Im trying to make a search bar in django and watched several youtube totorials and none of those worked. What im trying to do is either make a search bar that redirects to articles/what_you_searched_for or if not possible show up results that include search. If someone has enough time they can tell me how to do both :).
in views.py:
def index(request):
queryset = article.objects.all()
number_of_records = article.objects.count()
random_page = random.randint(1,number_of_records)
context = {
"object_list": queryset,
"random_page": random_page
}
# query = ""
# if request.GET:
# query = request.GET['q']
# context['query'] = str(query)
entries = util.list_entries()
return render(request, "encyclopedia/index.html", context)
#{
#"entries": util.list_entries(),
#"random_page": random_page,
#})
def dynamic_articles_view(request, my_id):
obj = article.objects.get(id= my_id)
number_of_records = article.objects.count()
random_page = random.randint(1,number_of_records)
context = {
"object": obj,
"random_page": random_page
}
return render(request, "encyclopedia/article_detail.html", context)
in index.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1 id="demo" onclick="add_article()">Article</h1>
<ul>
{% for instance in object_list %}
<li>{{instance.title}}</li>
{% endfor %}
</ul>
{% endblock %}
layout.html: ------------ SEARCH BAR HERE ---------
{% 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 = "/articles/{{q}}"> __________EXACTLY HERE ________
<input class="search" type="text" name="q" placeholder="Search...">
</form>
<div>
Home
</div>
<div>
<a href = "/new_article" >Create New Article</a>
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
urls:
from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index, new_article, dynamic_articles_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('new_article/', new_article),
path('home/', index, name = 'home'),
path('articles/<int:my_id>/', dynamic_articles_view, name = 'articless')
]
encyclopedia urls (other folder):
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("", views.new_article, name="new_article")
]
if needed i will comment models and forms but i dont want to make my question to long.
Simplest way is to add a GET form in your template with a search input without setting the action of the form:
<form action="">
<input type="text" name="search" placeholder="Search by title" value="{{request.GET.title}}">
<input type="submit" value="Search">
</form>
Then in the views.py in the you get the value. If it's given, you filter by it:
def dynamic_articles_view(request):
context['object_list'] = article.objects.filter(title__icontains=request.GET.get('search'))
return render(request, "encyclopedia/article_detail.html", context)

(NoReverseMatch at / Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:id>/']). please help me to remove this error

It is a multiple image program in which we can add multiple image at one time to see grouped photos. Error during template rendering
In template C:\Users\a\dev\mysite\templates\base.html, error at line 15
I am able to open my admin panel but i am not able to my files. thus please help me to find error:
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
image = models.ImageField(upload_to='products/', null=True, blank=True)
def __str__(self):
return self.title
class PostImage(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/')
def __str__(self):
return self.post.title
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post, PostImage
def blog_view(request):
posts = Post.objects.all()
return render(request, 'blog.html', {'posts':posts})
def detail_view(request, id):
post = get_object_or_404(Post, id=id)
photos = PostImage.objects.filter(post=post)
return render(request, 'detail.html', {
'post':post,
'photos':photos,
})
admin.py
from django.contrib import admin
from .models import Post, PostImage
class PostImageAdmin(admin.StackedInline):
model=PostImage
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
inlines = [PostImageAdmin]
class Meta:
model=Post
#admin.register(PostImage)
class PostImageAdmin(admin.ModelAdmin):
pass
base.html
<!DOCTYPE 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/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous">
<title>Multi Image Tutorial</title>
</head>
<body>
<div class="container py-4">
{% block content %}
{% endblock %}
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
blog.html
{% extends 'base.html' %}
{% block content %}
<div class="row row-cols-1 row-cols-md-2">
{% for post in posts %}
<div class="col mb-4">
<div class="card">
<div class="view overlay">
<img class="card-img-top" src="{{post.image.url}}"
alt="Card image cap" >
<a href="#">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body">
<h4 class="card-title">{{post.title}}</h4>
<p class="card-text">{{post.description}}</p>
Read More
</div>
</div>
<!---card-->
</div>
{% endfor %}
</div>
{% endblock %}
detail.html
{% extends 'base.html' %}
{% block content %}
<div id="carouselExampleIndicators" class="carousel slide" data-mdb-ride="carousel">
<ol class="carousel-indicators">
{% for p in photos %}
<li data-mdb-target="#carouselExampleIndicators" data-mdb-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 %} active {% endif %}"></li>
{% endfor %}
</ol>
<div class="carousel-inner" role="listbox">
{% for p in photos %}
<div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}">
<img
src="https://mdbootstrap.com/img/new/slides/041.jpg"
class="d-block w-100"
alt="First slide"/>
</div>
{% endfor %}
</div>
<a
class="carousel-control-prev"
href="#carouselExampleIndicators"
role="button"
data-mdb-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</a>
<a
class="carousel-control-next"
href="#carouselExampleIndicators"
role="button"
data-mdb-slide="next" >
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</a>
</div>
{% endblock %}
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from posts import views
urlpatterns = [
url(r'^youadmin/', admin.site.urls),
url(r'^', views.blog_view, name='blog'),
url(r'^<int:id>/', views.detail_view, name='detail'),
] + static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You are using the url function which expects you to use regex to capture arguments, to capture an integer your patterns should be like:
urlpatterns = [
url(r'^youadmin/', admin.site.urls),
url(r'^', views.blog_view, name='blog'),
url(r'^(?P<id>\d+)/', views.detail_view, name='detail'),
]
But i would recommend you to use the path function instead, which doesn't require regex:
from django.urls import path
urlpatterns = [
path('youadmin/', admin.site.urls),
path('', views.blog_view, name='blog'),
path('<int:id>/', views.detail_view, name='detail'),
]
You must include a trailing slash at the beginning of your urls like this:
urlpatterns = [
url(r'^/youadmin/', admin.site.urls),
url(r'^/', views.blog_view, name='blog'),
url(r'^/<int:id>/', views.detail_view, name='detail'),
]
It's also possible that an instance of Post with id=1 just doesn't exist.

How to fix NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['post/<int:pk>/']

I have tried everything i found on the internet which was similar to my problem, but it did not help. Please help if you know the answer.
I get an ERROR while trying to set up my post_detail page of my blog.
The ERROR MESSAGE:
Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found.
1 pattern(s) tried: ['post/<int:pk>/']
My post_list.html
{% extends "blog/base.html" %}
{% load static %}
<html>
<head>
<title>Code Reminder</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
</head>
<body>
<div class="page-header">
<h1>Coder Reminder</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-4">
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
My post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h2>{{ post.title }}</h2>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
My base.html
{% load static %}
<html>
<head>
<title>Code Reminder</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
</head>
<body>
<div class="page-header">
<h1>Code Reminder</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
my views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Create your views here.
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, '/home/ud/PycharmProjects/blog/blog/blog/templates/blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, '/home/ud/PycharmProjects/blog/blog/blog/templates/blog/post_detail.html', {'post': post})
My urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url('', views.post_list, name='post_list'),
url('post/<int:pk>/', views.post_detail, name='post_detail'),
]
And finally my myblog/urls.py
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('blog.urls')),
]
Please help me if you know the answer. I really tried everything but i cant find out my mistake.
Regards
The error message says
Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found.
Which shows that the pk is evaluating to the empty string ''.
Your URL tag is
{% url 'post_detail' pk=post.blog.pk %}
That means you are trying to pass the post's blog's pk. But you almost certainly want the post's pk instead:
{% url 'post_detail' pk=post.pk %}
Secondly, you are using the old url() with the path() syntax (new in Django 2.0). Your urls should be:
from django.urls import path
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
The problem might be due to the older version of Python or Django.
Try changing your My urls.py file as follow:
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
Here it will help to parse the address properly. If it still doesn't work the try to replace following in My post_list.html file
Old:
{% url 'post_detail' pk=post.blog.pk %}
New:
{% url 'post_detail' pk=post.pk %}
Hope this will help!

I have a trouble with Django

I have the following problem in my Django project :
Error during template rendering
In template
/home/didier/Documents/Projects/inventory/inv/templates/index.html,
error at line 11 NoReverseMatch at /element Reverse for
'elements.views.element_detail' with arguments '()' and keyword
arguments '{u'pk': 1}' not found. 0 pattern(s) tried: []
Views.py is:
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render, get_object_or_404
from .models import Element
def hello(request):
element = Element.objects.order_by('id')
template = loader.get_template('index.html')
title = 'Element list - RegiX'
context = {
'element': element,
'title': title
}
return HttpResponse(template.render(context, request))
ref element_detail(request, pk):
element = get_object_or_404(Element, pk=pk)
template = loader.get_template('element_detail.html')
context = {
'element': element
}
return HttpResponse(template.render(context, request))
Urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^element$', views.hello, name='hello'),
url(r'^detail/(?P<pk>[0-9]+)/$', views.element_detail, name='detail'),
]
index.html:
{% extends 'base.html' %}
{% load staticfiles %}
{% block page_title %}
Element list | RegiX
{% endblock %}
{% block content %}
<h2>Hello</h2>
{% for el in element %}
<li>
{{ el.manufacturer }} ::
<a href="{% url 'elements.views.element_detail' pk=el.pk %}">
{{ el.model }}
</a>
{{ el.date_purchase }} ::
<img src="{{ el.image.url }}">
</li>
{% endfor %}
{% endblock %}
base.html extend to index.html:
<!DOCTYPE html>
<html lang="en">
<head>
{% load staticfiles %}
<meta charset="UTF-8">
<title>{% block page_title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/base.css' %}">
</head>
<body>
<header>
<strong>RegiX Enterprise</strong>
</header>
<section>
{% block login_content %}
{% endblock %}
{% block content %}
{% endblock %}
</section>
<footer><small>RegiX :: powered By Didier Zúñiga</small></footer>
</body>
</html>
Urls.py of settings:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('elements.urls', namespace='elements')),
url(r'^', include('userprofiles.urls', namespace='userprofiles')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I hope you can help me, thanks
Your URL reverse in the template is wrong. By giving it the name detail within a namespace, you need use that name to reverse the URL, not the name of the view.
So this:
<a href="{% url 'elements.views.element_detail' pk=el.pk %}">
Should be:
<a href="{% url 'elements.detail' pk=el.pk %}">

What should I write for my detail view to inhert DB fields for my Django template?

I am new in Python. I have a problem with fetching DB fields to my Django template. File detail.html successfully extends my master.html, but it doesn't get anything I wrote under {% block h1 %} {% endblock %}
What should I write under views.py to make it work?
detail.html
{% extends "master2.html" %}
{% block h1 %}
<div class="box first">
<div class="row">
<div class="container">
{% for question in latest_question_list %}
<div class="col-xs-12 col-sm-4 col-md-3">
<div class="center">
<h4>{{ question.naslov }} </h4>
<p>{{ question.opis }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
{% block title %} Detail {% endblock %}
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})
index.html
{% extends "master.html" %}
{% block h1 %}
<div class="box first">
<div class="row">
<div class="container">
{% for question in latest_question_list %}
<div class="col-xs-12 col-sm-4 col-md-3">
<div class="center">
<h4>{{ question.naslov }} </h4>
<p>{{ question.opis }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
{% block title %} Index {% endblock %}
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-target="#navbar" data-offset="0">
{% include "header.html" %}
{% include "carausel.html" %}
{% block h1 %}{% endblock %}
{% include "footer.html" %}
{% include "nav.html" %}
<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/main.js"></script>
</body>
</html>
master.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-target="#navbar" data-offset="0">
{% include "header.html" %}
{% include "carausel.html" %}
{% block h1 %}{% endblock %}
{% include "footer.html" %}
<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/main.js"></script>
</body>
</html>
You loop over latest_question_list, but pass {'question': question} in the context
{% extends "master.html" %}
of index.html to be changed to
{% extends "master2.html" %}

Categories

Resources