I have this view function for my blog posts.
def home(request):
posts = Post.objects.all().order_by("-pub_date")
paginator = Paginator(posts, 5)
try: page = int(request.GET.get("page", 1))
except ValueError: page = 1
try: posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_page)
return render_to_response("home.html",
dict(posts=posts, user=request.user))
In my main urls.py file, I have the following:
urlpatterns = patterns('',
url(r'^', 'blog.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
)
Also, I didn't create a urls.py file under my app folder.
And I have this in my home.html file.
{% block footer %}
<ul class="pager">
{% if posts.object_list and posts.paginator.num_pages > 1 %}
{% if posts.has_previous %}
<li>Previous</li>
{% endif %}
{% if posts.has_next %}
<li>Next</li>
{% endif %}
</ul>
{% endif %}
</div><!-- /.blog-main -->
{% endblock %}
Up to this point, the homepage (home.html) renders properly on my local server. However, when I click on next page link, it sends me to
127.0.0.1:8000/2
and shows the same page. Also, the previous button is not showing.
Question: Have I done anything wrongly? And how do I direct my views to page 2 properly in the url dispatcher?
Help appreciated. Thank you.
you can use the documentation's version of pagination view.
https://docs.djangoproject.com/en/dev/topics/pagination/
Related
I'm trying to pass an object's id through the url, but its not able to find the page even after it tries the path when it goes through its patterns
Error:
Using the URLconf defined in GroomingService.urls, Django tried these URL patterns, in this order:
admin/
[name='Home']
appointment-Maker/
account/
admin-home
view_appointment/<id>/
login/ [name='Login Page']
registration/ [name='Registration Page']
logout [name='Logout Page']
The current path, adminview_appointment/21/, didn’t match any of these.
GroomingService.urls
#urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', Home_view, name="Home"),
path('appointment-Maker/', include('appointmentApp.urls')),
path('account/', include('accountApp.urls')),
path('admin-home', include('adminApp.urls')),
path('view_appointment/<id>/', viewAppointment_view), #this is the page it is not finding
path('login/', Login_view, name='Login Page'),
path('registration/', Registration_view, name='Registration Page'),
path('logout', Logout_view, name='Logout Page')
]
adminApp/views.py viewAppointment_view
def viewAppointment_view(request, id):
appointments = Appointment.objects.get(id = id)
context = {
'appointments' : appointments
}
return render(request, "admin_templates/viewappointment.html", context)
templates/admin_templates viewappointment.html
{% extends 'base.html' %}
{% block content %}
<a>appointment view</a>
{% endblock %}
templates/admin_templates adminhome.html (the link is clicked through this page)
{% extends 'base.html' %}
{% block content %}
<a>this is the admin page</a>
<br>
{% for a in appointments %}
Client name:{{a.client_dog_name}}<br> {% comment %} this is the link that is clicked {% endcomment %}
{% endfor %}
<br>
<a>find month</a>
<form method="POST">
{% csrf_token %}
{{ monthyear }}
<button class="btn btn-primary" type="submit">click</buttom>
</form>
{% endblock %}
If I'm missing anything please let me know, I had the path at the adminApp/urls.py earlier
urlpatterns = [
path('', views.adminhome_view, name="Admin Home"),
]
but moved it to where it was trying to find the urls. I have no idea why this might not be working.
It should be view_appointment/{{a.id}}, not adminview_appointment/{{a.id}}, but it is better to make use of the {% url … %} template tag [Django-doc]. You can give the view a name:
path('view_appointment/<int:id>/', viewAppointment_view, name='view_appointment'),
and then refer to it in the template:
Client name:{{a.client_dog_name}}<br>
I am a newbie in Elasticsearch, I just try to create a search engine using it in Django. Overall, the engine shows good results. Unfortunately, it loads a large number of the results. Then, I try to paginate it by regular pagination in Django, after that, the page load error object of type 'Search' has no len().
These are my codes:
view.py
from django.shortcuts import render, redirect
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
from django.core.paginator import Paginator
def search_es(request):
return render(request,'search/search.html')
def results(request):
s = Search(using=Elasticsearch())
keyword = request.GET.get('q') # keyword that want to be found
print(keyword)
if keyword:
# posts = s.query('match_phrase_prefix',head_title=keyword)
# if posts.count() == 0:
posts = s.query(
"multi_match",
query=keyword,
fields=['head_title^5', 'description^5', 'description.ngram'],
# type="phrase_prefix",
)
posts = posts[0: 100]
else:
posts = ''
page = request.GET.get('page', 1)
paginator = Paginator(posts, 10)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
context = {
'page_title': keyword,
'posts': users,
'count': posts.count(),
'keyword': keyword,
}
return render(request,'search/results.html',context)
results.html
{% if posts.has_other_pages %}
<ul class="pagination">
{% if posts.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in posts.paginator.page_range %}
{% if posts.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if posts.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
Hope for every possible solution.
Thank you very much.
ElasticSearch provided two parameters you can use for pagination: from and size. You can refer to https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#pagination
for example:
posts = s[0:20].query(
"multi_match",
query=keyword,
fields=['head_title^5', 'description^5', 'description.ngram'],
# type="phrase_prefix",
)
to get first page, and page size is 20.
I have a link to note detail page (s_note) in the user page (username). So as long as I have no entries(notes) in the database for the user the user page renders fine, but as soon as there is a valid note the render fails with the above error and points to ln:6 of user.html.
my urls.py
from django.conf.urls import url
from notes.models import User, Note
from . import views
app_name = 'notes'
urlpatterns = [
url(r'^$', views.index, name='u_index'),
my url
url(r'^signup/$', views.signup, name='u_signup'),
url(r'^(?P<user_id>[\w\-]+)/$', views.user, name='username'),
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-]+)/$', views.note, name='s_note'),
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-]+)/$', views.note, name='s_note')
]
my views
def note(request, user_name, note_t):
nt = Note.objects.get(note_title=note_t)
return render (request, 'notes/detail.html', {'note': nt})
my users.html
<h2>Hi! {{ user.user_n }} Your notes are here.</h2>
{% if allnotes %}
<ul>
{% for note in allnotes %}
<li>{{ note.note_title }}</li>
{% endfor %}
</ul>
{% else %}
<p>You have no notes yet!</p>
{% endif %}
<form method="post" action"">
<table>
{% csrf_token %}
{{ NForm }}
</table>
<input type="submit" value="Create">
</form>
Your url doesn't match for underscores or spaces which your keyword currently contains.
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-]+)/$', views.note, name='s_note'),
should be
url(r'^(?P<user_name>[\w\-]+)/(?P<note_t>[\w\-\_\s]+)/$', views.note, name='s_note'),
although this isn't much of a solution since most spaces would turn into %20's, you should try to remove any spaces from your keywords and update your regex accordingly.
It was a namespacing problem as #Alasdair observed, it sorted with the edit -
'{% url 'notes:s_note'...%}'
in the template.
polls/templates/polls/index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
The above index.html is from Tutorial #3 from Django 1.8. My question is where/how does index.html know which domain to use?
The index.html file will be associated with a view and that view will be associated to a url that will be configured in the urls.py file.
When you upload your project to a server, you will then configure the servers configuration, linking your project to a domain.
Example: myawesomedomain.com
views.py
def HomeView(request):
return render(request, 'index.html', {context})
def ContactView(request):
return render(request, 'contact.html', {context})
urls.py
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.HomeView), # http://myawesomedomain.com
url(r'^contact$', views.ContactView), # http://myawesomedomain.com/contact
)
Am following along on the django tutorial (1.6 python 3.3). Am however stuck in trying to replicate the tutorial in my own test application.
I want to display a list of just 3 hyperlinks on the index page. The hyperlink for now is just the name of listed item.
Views.py
def Index(request):
tables = []
tables.append('Country')
tables.append('County')
tables.append('Registration Body')
return render(request, 'test_app/index.html', {'table_list': tables})
Urls.py
from django.conf.urls import patterns, url
from test_app import views
urlpatterns = patterns('test_app',
#url(r'^Country/', views.Index, name='index'),
url(r'^$', views.Index, name='index'),
)
Index.html
<h1>List of Config Tables in TestApp</h1>
{% if table_list %}
<ul>
{% for tbl_name in table_list %}
<li>{{ tbl_name }}</li>
{% endfor %}
</ul>
{% else %}
<ul>
<p>No table found<p>
</ul>
{% endif %}
With that setup, I get the error:
NoReverseMatch at /test_app/
Reverse for 'index' with arguments '('Country',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['test_app/$']
Something weird is that when I get rid of the tbl_name in href in the index page I am able to get my list but the list DOESN'T have hyperlinks.