Intro: I am using this https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html to add infinite scroll with django. Just in case anyone wants the detailed code its on Github.It is a very simple code
https://github.com/sibtc/simple-infinite-scroll
The issue: I have a total of 8 posts. I can see 3 posts in my homepage. Ideally as soon as I scroll down more 3 posts should show. I know the views are fine as the print statement in the view works and it is showing only 3 posts. Usually if there is a problem loading infinite scroll the More link should show. But that is not showing as well. Where am I going wrong
What I have done so far:
In my static folder. I made a folder called js and added 3 files in it
infinite.min.js, jquery-3.1.1.min.js, jquery.waypoints.min.js
I copied the code exactly from the github in my files
Below is my view:
class Homepage(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super(Homepage, self).get_context_data(**kwargs)
all_posts = Post.objects.all()
page = self.request.GET.get('page', 1)
paginator = Paginator(all_posts, 3)
try:
posts = paginator.page(page)
print(posts)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context['post_list'] = posts
return context
Below is my base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %} Infinite Scroll{% endblock %}</title>
<meta name="description" content="{% block metadescription %}{% endblock %}">
{% load staticfiles %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default".....> #navbar
<div class="container">
<div>
{% block body %}
{% endblock %}
</div>
{% include 'footer.html' %}
</div>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
{% block javascript %}{% endblock %}
</body>
</html>
Below I have my home.html:
{% extends 'base.html' %}
{% load staticfiles %}
{% block javascript %}
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function ($items) {
$('.loading').hide();
}
});
</script>
{% endblock %}
{% block body %}
<div class="col-md-6" style="background-color:white;">
<div class="infinite-container">
{% for post in post_list %}
<div class="infinite-item">
<div class="list-group"....>
</div>
{% endfor %}
</div>
<div class="loading" style="display: none;">
Loading...
</div>
{% if post_list.has_next %} #I also tried {% if page_obj.hasnext %}
<a class="infinite-more-link" href="?page={{ post_list.next_page_number }}">More</a>
{% endif %}
</div>
{% endblock %}
Where am I going wrong. I have checked and rechecked the code again and again
In your home.html place following block after body block
{% block javascript %}
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function ($items) {
$('.loading').hide();
}
});
</script>
{% endblock %}
view.py
Class
class ArticlesView(ListView):
model = Article
paginate_by = 5
context_object_name = 'articles'
template_name = 'blog/articles.html'
Def
def home(request):
numbers_list = range(1, 1000)
page = request.GET.get('page', 1)
paginator = Paginator(numbers_list, 20)
try:
numbers = paginator.page(page)
except PageNotAnInteger:
numbers = paginator.page(1)
except EmptyPage:
numbers = paginator.page(paginator.num_pages)
return render(request, 'blog/home.html', {'numbers': numbers})
Related
I am trying to use django-views-breadcrumbs to add breadcrumbs to a site. I can get it to work with some views but I am getting an error with a particular listview. When I attempt to visit this listview page I see the error.
The error appears to be related to a need for the correct context. So far I have not been able to figure this out.
The error:
NoReverseMatch at /projects/project/1/notes/
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Request Method: GET
Request URL: http://co1.localhost:8000/projects/project/1/notes/
Django Version: 3.1.14
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Exception Location: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages/django/urls/resolvers.py, line 689, in _reverse_with_prefix
Python Executable: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/bin/python
Python Version: 3.9.6
Python Path:
['/Users/user/Desktop/otools',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages']
Server time: Sun, 20 Feb 2022 15:52:17 +0000
The list view:
class ProjectNotesList(ListBreadcrumbMixin,ListView):
model = ProjectNotes
template_name = 'company_accounts/project_notes.html'
comments = ProjectNotes.comments
def related_project(self, **kwargs):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
notes = ProjectNotes.objects.all
return notes
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
return context
commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments'))
The urls.py
from django.urls import path, include
from .views import CompanyProjects, CompanyProjectsDetailView, TodoCreateView, ProjectNotesList, ProjectNotesCreateView, ProjectCreateView, ProjectNotesDetailView, CompanyCompletedProjects, CompanyPausedProjects, TodosList, ProjectTodosDetailView, ProjectDocumentsList, ProjectDocumentsCreateView, ProjectDocumentsDetailView
from . import views
app_name = 'company_project'
urlpatterns = [
path('', CompanyProjects.as_view(), name='project_list'),
path('completed_projects', CompanyCompletedProjects.as_view(), name='completed_projects'),
path('paused_projects', CompanyPausedProjects.as_view(), name='paused_projects'),
path('add_project/', ProjectCreateView.as_view(), name='add_project'),
path('project/<int:pk>/', CompanyProjectsDetailView.as_view(), name='project_detail'),
path('project/<int:pk>/todos/', TodosList.as_view(), name='project_todos'),
path('project/<int:project_pk>/todo/<int:pk>/', ProjectTodosDetailView.as_view(), name='project_todo_detail'),
path('project/<int:pk>/add_todo/', TodoCreateView.as_view(), name='add_todo'),
path('project/<int:pk>/add_project_note/', ProjectNotesCreateView.as_view(), name='add_project_note'),
path('project/<int:pk>/notes/', ProjectNotesList.as_view(), name='projectnotes_list'),
#path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(),
# name='add_project_note_comment'),
path('project/<int:project_pk>/note/<int:pk>/', ProjectNotesDetailView.as_view(), name='project_note_detail'),
path('project/<int:pk>/documents/', ProjectDocumentsList.as_view(), name='project_documents'),
path('project/<int:pk>/add_project_document/', ProjectDocumentsCreateView.as_view(), name='add_project_document'),
path('project/<int:project_pk>/document/<int:pk>/', ProjectDocumentsDetailView.as_view(), name='project_document_detail'),
]
The base and page templates:
base
<!DOCTYPE html>
{% load static %}
{% load view_breadcrumbs %}
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Site{% endblock title %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link type="text/x-scss" href="{% static 'bootstrap/scss/bootstrap.scss' %}" rel="stylesheet" media="screen">
<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
<link rel="shortcut icon" type="image/png" href="{% static 'core_images/OH_favicon.png' %}"/>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-VJRXH7YFXZ"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-VJRXH7YFXZ');
</script>
</head>
<body>
<wrapper class="d-flex flex-column">
{% include 'nav.html' %}
<main class="flex-fill">
<div class="row">
<div class="col-12">
<br />
{% block breadcrumbs %}
{% render_breadcrumbs 'view_breadcrumbs/bootstrap4.html' %}
{% endblock breadcrumbs %}
{% block messages %}{% endblock messages %}
</div>
</div>
{% block content %}
<h1>Hello</h1>
{% endblock content %}
</main>
{% include 'footer.html' %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
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.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</wrapper>
</body>
</html>
page
<!-- templates/company_accounts/project_notes.html -->
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<div class="general-section-header">
<div class="header-add-new">
<a class="btn btn-success" href="{% url 'company_project:add_project_note' project.pk %}" role="button">Add Note</a>
</div>
<h1>Notes for {{ project }}</h1>
</div>
{% if project.notes.all %}
{% for note in project.notes.all %}
<div class ="projectnotes-entry">
<div class="col-sm-8">
<div class="row-sm-6">
<div class="card mb-2">
<div class="card-body">
<div class="card-title">{{ note.title }}</div>
<div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }}
<div>{{ note.comments.all.count }} comments</div>
read more</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p>No notes have been have been added yet.</p>
{% endif %}
</div>
{% endblock content %}
There is a demo included with the breadcrumb app the provides some insight. However I have not been able to figure out how to add necessaryt context using code from the demo.
The demo code:
class TestListsView(ListBreadcrumbMixin, ListView):
model = TestModel
template_name = "demo/test-list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
view_paths = []
for instance in self.object_list:
view_paths.append(
(
instance.name,
detail_instance_view_url(instance),
),
)
context["view_paths"] = view_paths
return context
Firstly, i am not an ultra expert about Django objects or structures, i learn with numerous and various curses and i try during the development of my website to reach the must clear and efficient code in my Django project.
Now i try to make a date range picker in bootstrap 4 (4.1.3)
I will obtain the same result as this tool django-bootstrap-datepicker-plus, i trying to follow the example code but i dont know how to add this tool on my django project.
For now i cant successfully render the daterangepicker on the template.
I share the files that concerns by this tool.
models.py
class Event(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateField()
end_date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
start_datetime = models.DateTimeField()
end_datetime = models.DateTimeField()
start_month = models.DateField()
end_month = models.DateField()
start_year = models.DateField()
end_year = models.DateField()
def __str__(self):
return self.name
forms.py
from bootstrap_datepicker_plus import DatePickerInput
from bootstrap_datepicker_plus import TimePickerInput
from bootstrap_datepicker_plus import DateTimePickerInput
from bootstrap_datepicker_plus import MonthPickerInput
from bootstrap_datepicker_plus import YearPickerInput
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = [
'start_date', 'end_date',
'start_time', 'end_time',
'start_datetime', 'end_datetime',
'start_month', 'end_month',
'start_year', 'end_year',
]
widgets = {
'start_date': DatePickerInput(options={'format': 'YYYY-MM-DD', 'debug': True}).start_of('event active days'),
'end_date': DatePickerInput(options={'format': 'MM/DD/YYYY'}).end_of('event active days'),
'start_datetime': DateTimePickerInput(options={'debug': True}).start_of('event active dtime'),
'end_datetime': DateTimePickerInput().end_of('event active dtime'),
'start_time': TimePickerInput(options={'debug': True}).start_of('event active time'),
'end_time': TimePickerInput().end_of('event active time'),
'start_month': MonthPickerInput().start_of('active month'),
'end_month': MonthPickerInput().end_of('active month'),
'start_year': YearPickerInput().start_of('active year'),
'end_year': YearPickerInput().end_of('active year'),
}
views.py
#login_required
def visual_general(request):
....
# get data for the table of django-tables2 and other stuff
....
# Get data
data = create_data_table_general(samples, references, strains, analyzepipelines, sts, id_access_list)
# Add data to the table
table = GeneralTable(data)
form_date_range = EventForm()
return render(request, 'visual/visual_general.html', {'table': table, 'form_date_range': form_date_range})
urls.py
# -*- coding: utf-8 -*-
# Library Django
from django.conf.urls import url
# Inner functions
from . import views
urlpatterns = [
url(r'^visual/General', views.visual_general, name="visual_general"),
]
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}MySite{% endblock %}</title>
{% load static %}
{% block head %}
<link rel="stylesheet" type="text/css" href="{% static 'css/menu.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}" />
{% endblock %}
{% block css %}
<!-- blueimp Gallery styles -->
<link rel="stylesheet" href="/static/css/blueimp-gallery.min.css">
<!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
<link rel="stylesheet" href="/static/css/jquery.fileupload-ui.css">
<!-- CSS adjustments for browsers with JavaScript disabled -->
<noscript><link rel="stylesheet" href="/static/css/jquery.fileupload-ui-noscript.css"></noscript>
{% endblock %}
{% block bootstrap_css %}
<link rel="stylesheet" href="{% static 'bootstrap-4.1.3/css/bootstrap.min.css' %}"/>
{% endblock %}
{% block bootstrap_js %}
<script src="{% static 'jquery/jquery3.min.js' %}"></script>
<script src="{% static 'js/popper.min.js' %}"></script>
<script src="{% static 'bootstrap-4.1.3/js/bootstrap.min.js' %}"></script>
{% endblock %}
</head>
<body>
<br />
<section id="content">
{% block content %}
<h1>No content set</h1>
{% endblock %}
</section>
</body>
</html>
visual_general.html
{% extends "base.html" %}
{% load django_tables2 %}
{% load static %}
{% block title %} Visual of data {% endblock%}
{% block content %}
<div id="form">
<form
id="test"
action="{% url 'visual_general' %}"
method="get">
{% csrf_token %}
<div
class="well"
style="margin: 2px; padding: 1px 20px 0 40px; position: relative; top: 0; background: #B8C1C8;">
<div class="row">
{{form_date_range.media}}
<div class="row">
<div class="form-group col-sm-8 col-md-6">
<center>
<input
class="button"
type="submit"
value="Filter" />
</center>
</div>
</div>
</div>
</div>
</form>
</div>
{% endblock %}
Thanks in advance for anyone can help me to add a date range picker or for any tips or comment on my code.
I found this project https://github.com/chhantyal/taggit-selectize and it seems to do what I want, but the example app is incomplete, so I don't know how to use it. What I basically want is that users will be able to write their own tags for a post, and that if they are typing one that has been used before by someone else, it will show up in autocomplete. I also want a search function that will use the autocomplete in the same manner. I'm sure it's not very complicated but the readme only explains how to install and what some things mean, and I was looking for a very minimal working example that makes the autocomplete work.
Thanks in advance.
I have a very specific use case. I hope my example does not over-complicate things (I add extra fields to my Taggit model). Please be aware you may need to load css and js in your html, as per this issue. I am using Django Crispy Forms.
In my app settings:
TAGGIT_TAGS_FROM_STRING = "taggit_selectize.utils.parse_tags"
TAGGIT_STRING_FROM_TAGS = "taggit_selectize.utils.join_tags"
TAGGIT_SELECTIZE_THROUGH = "jobsboard.models.SkillTags"
TAGGIT_CASE_INSENSITIVE = True
TAGGIT_SELECTIZE = {
"MINIMUM_QUERY_LENGTH": 2,
"RECOMMENDATION_LIMIT": 10,
"CSS_FILENAMES": ("taggit_selectize/css/selectize.django.css",),
"JS_FILENAMES": ("taggit_selectize/js/selectize.js",),
"DIACRITICS": True,
"CREATE": False,
"PERSIST": True,
"OPEN_ON_FOCUS": True,
"HIDE_SELECTED": True,
"CLOSE_AFTER_SELECT": False,
"LOAD_THROTTLE": 300,
"PRELOAD": False,
"ADD_PRECEDENCE": False,
"SELECT_ON_TAB": False,
"REMOVE_BUTTON": True,
"RESTORE_ON_BACKSPACE": False,
"DRAG_DROP": False,
"DELIMITER": ",",
}
In my jobsboard/models.py:
from taggit.models import TagBase, GenericTaggedItemBase
from taggit_selectize.managers import TaggableManager
class SkillTags(TagBase):
LANGUAGE = "la"
STATISTICS = "st"
CODING = "co"
DISCIPLINE = "di"
TYPES = (
(LANGUAGE, "language"),
(STATISTICS, "statistics"),
(CODING, "coding"),
(DISCIPLINE, "discipline"),
)
type = models.CharField(choices=TYPES, default=DISCIPLINE, max_length=2)
creator = models.ForeignKey(User, null=True)
class TaggedModel(GenericTaggedItemBase):
tag = models.ForeignKey(SkillTags, related_name="%(app_label)s_%(class)s_items")
class Job(TimeStampedModel):
tags = TaggableManager(_("skillset required"), blank=True, through=TaggedModel)
In my urls:
url(r'^hirer/new/$', NewJobView.as_view(), name='hirer_new_job')
In my jobsboard/views.py:
class NewJobView(FormView):
template_name = 'jobsboard/new_edit_job.html'
form_class = NewAndEditJobForm
In my jobsboard/forms.py:
class NewAndEditJobForm(ModelForm):
class Meta:
model = Job
fields = ('tags',)
For my jobsboard/templates/jobsboard/new_edit_job.html:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{{ block.super }}
{% crispy form %}
{% endblock content %}
for my templates/base.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
{% block css %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Your stuff: Third-party CSS libraries go here -->
{% endblock %}
{% block extrahead %}
{% endblock %}
</head>
<body>
{% block content %}
{% endblock content %}
{% block javascript %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
{% endblock javascript %}
</body>
</html>
I shall try and give an example as lean as possible:
app/models.py:
from django.db import models
from taggit_selectize.managers import TaggableManager
class Post(models.Model):
name = models.CharField(max_length=100)
tags = TaggableManager()
app/views.py:
from app.models import Post
from django.views.generic import UpdateView
class PostEdit(UpdateView):
model = Post
fields = ['name', 'tags' ]
success_url = '/'
app/templates/app/post_form.html:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Speichern">
</form>
{% endblock %}
{% block css %}
{{ block.super }}
<link href="{% static "taggit_selectize/css/selectize.django.css" %}" type="text/css" media="all" rel="stylesheet"/>
{% endblock %}
{% block javascript %}
{{ block.super }}
<script src="{% static "taggit_selectize/js/selectize.js" %}"></script>
{% endblock %}
and a templates/base.html:
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<script src="{% static 'vendor/js/jquery-3.3.1.min.js' %}"></script>
<!-- IMPORTANT: get jquery loaded ASAP. if you load it too late you get JS errors from the taggit-selectize. -->
{% block css %}
{% endblock %}
</head>
<body>
{% block content %}
{% endblock %}
{% block javascript %}
{% endblock %}
</body>
</html>
Important Note: I was having the same problems up until the point where I moved the jquery-loading up into the header.
In my models.py file I have defined StandardPage class to which I want to add transenter code herelations.In this class I have defined these:
class StandardPage(TranslatablePage,Page):
introduction = models.TextField(
help_text='Text to describe the page',
blank=True)
image = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
help_text='Landscape mode only; horizontal width between 1000px and 3000px.'
)
video_url = models.URLField(null=True,blank=True)
body = StreamField([
( 'main_content',blocks.ListBlock(BaseStreamBlock() ,label = 'content') )]
, blank=True,
null=True,
verbose_name="Page body" )
content_panels = Page.content_panels + [
FieldPanel('introduction', classname="full"),
StreamFieldPanel('body'),
ImageChooserPanel('image'),
FieldPanel('video_url'), ]
#property
def standard_page(self):
return self.get_parent().specific
def get_context(self, request):
language = request.LANGUAGE_CODE
standard_page = request.site.standard_page
pages = TranslatablePage.objects.live().filter(language__code=language).specific().child_of(standard_page)
context['pages'] = self.standard_page
return context
While template base.html contains:
{% load i18n %}
{% load wagtailtrans_tags wagtailcore_tags wagtailuserbar %}
{% load static %}
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<title>
{% block title_suffix %}
{% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %}
{% endblock %}
</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{# Global stylesheets #}
<link rel="stylesheet" type="text/css" href="{% static 'css/mysite.css' %}">
<link href="{% static 'css/bootstrap.min.css' %}" type="text/css" rel="stylesheet" />
<link href="{% static 'fonts/font-awesome-4.7.0/css/font-awesome.min.css' %}" type="text/css" rel="stylesheet" />
<link href="{% static 'css/streamfields.css' %}" type="text/css" rel="stylesheet" />
{% block extra_css %}
{# Override this in templates to add extra stylesheets #}
{% endblock %}
</head>
<body class="{% block body_class %}{% endblock %}">
{% wagtailuserbar %}
{% get_translations page homepage_fallback=False include_self=False as translations %}
{% for language, page in translations.items %}
<link rel="alternate" href="{{ page.full_url }}" hreflang="{{ language.code }}">
{% endfor %}
{% block content %}
{% endblock %}
{# Global javascript #}
<script type="text/javascript" src="{% static 'js/mysite.js' %}"></script>
<script type="text/javascript" src="{% static 'js/jquery-2.2.3.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
{% block extra_js %}
{# Override this in templates to add extra javascript #}
{% endblock %}
</body>
</html>
and my template 'standard_page.html' contains:
{% extends "base.html" %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block content%}
{% include "base/include/header.html" %}
<div class="container">
<div class="row">
<div class="col-md-7">
{{ page.body }}
</div>
</div>
</div>
{% endblock %}
Not rendering content on the page.It's showing Welcome to your new Wagtail site! even though I published all the languages of a particular page.But the title of the page is displaying in different languages mentioned
I am new to django & wagtail. How to rectify this, not getting.
Any help?
Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't.
Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :)
Model defined in models.py:
from django.db import models
from django.utils import timezone
# Create your models here.
class Propaganda(models.Model):
slogan = models.CharField(max_length=140, blank=True, null=True)
def __str__(self):
return self.slogan
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Christopher's weblog</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Blog site.">
<!-- Let's get the static files where we use them, but this could be before the html tag -->
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- <link rel="stylesheet" href="{% static 'blog/css/cupar.css' %}" type="text/css" /> -->
</head>
<body>
<section class="hero is-success is-bold">
<div class="hero-body">
<div class="container">
{% block slogan %}
{% for propaganda in propagandas %}
<h6>{{ propaganda.slogan }} it's</h6>
{% endfor %}
{% endblock %}
<h1 class="title" style="display: inline-block;">
<span class="icon">
<i class="fa fa-home"></i>
</span>
The Guide
</h1>
{% if user.is_authenticated %}
<div class="field">
<div class="control">
<a href="{% url 'post_new' %}" class="button is-warning is-pulled-right">
<span class="icon">
<i class="fa fa-plus-square"></i>
</span>
<span>New post</span>
</a>
</div>
</div>
{% endif %}
</div><!-- #container -->
</div>
</section>
<!-- content under header in here-> -->
{% block content %}
{% endblock %}
</body>
</html>
views.py
from django.template import RequestContext
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Propaganda
from .forms import PostForm
from django.utils import timezone
# Create your views here.
def post_list(request):
posts = Post.objects.all()
propagandas = Propaganda.objects.all().order_by('?')[:1]
return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})
post_detail.html (where the model does not appear):
{% extends 'blog/header.html' %}
{% block content %}
some html / form that has nothing to do with the header.
{% endblock %}
post_list.html (the 'index' page where the model works fine)
{% extends "blog/header.html" %}
{% block content %}
{% for post in posts %}
<section class="section">
more html
{% endblock %}
need to pass the data from each view function that is required in the header you are extending (re-using) in each template.
def post_detil(request, id):
posts = Post.objects.all()
propagandas = Propaganda.objects.all().order_by('?')[:1]
# ... add in other stuff relevant to post details ...
post = Post.objects.get(pk=id)
return render(request, 'blog/post_detail.html', {'posts': posts, 'propagandas': propagandas, 'post': post})
Stick with it #Rin and Len, you'll get there :)
First: Why are you not showing the view of post_detail. Isn't that the one that does not work?
Second: Even though you are extending a base template you still have to pass the appropriate context in order to generate the desired dynamic data.
I hope it helps.