I'm spending hours on this thing.
I have a category page, and inside that page there's list of posts that leads to single post page if I click a particular one.
Single post page is working, single category page is working, but a page inside category page is not working, does this make sense?
def post(request, slug):#this is my view
single_post = get_object_or_404(Post, slug=slug)
single_post.views += 1 # increment the number of views
single_post.save() # and save it
t = loader.get_template('main/post.html')
context_dict = {
'single_post': single_post,
}
c = Context(context_dict)
return HttpResponse(t.render(c))
def category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
posts = Post.objects.filter(category=category)
context_dict['posts'] = posts
context_dict['category'] = category
except Category.DoesNotExist:
pass
return render(request, 'main/category.html', context_dict)
this is my url
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category')
]
And this is my category html
{% extends 'base.html' %}
{% block content %}
<h1>{{category_name}}</h1>
{% if category %}
{%if posts %}
<ul>
{% for post in posts %}
<h3>{{ post.title }}</h3>
{% endfor %}
</ul>
{%else%}
<strong>No Pages </strong>
{% endif %}
{% else %}
{{category_name}} does not exist
{% endif %}
{% endblock %}
Finally post.html
<html>
<head>
<title></title>
<head>
<body>
<h2>{{single_post.title}}</h2>
<p>{{single_post.content}}</p>
<p> Views: {{single_post.views}}
<br>
<p>
{% if single_post.image %}
<img src="/media/{{single_post.image}}">
{% endif %}
</p>
<body>
it gives me 404 error, interesting thing is url that's giving me error is 127.0.0.1:8000/category/hello/adele but 127.0.0.1:8000/adele doesn't give me error. so inside category page, i want the access for 127.0.0.1:8000/adele –
replace {{ post.title }} with {{ post.title }}
The issue is if the reference in anchor doesnt starts with / it means its a relative url and that reference is added to current url. Hope this helps you. Also for further reference please use absolute_url feature of django. Please read this :)
Use the url template tag:
{% for post in posts %}
<h3>{{ post.title }}</h3>
{% endfor %}
This reconstruct the url based on your url configuration, ensuring it is a valid url. Here, 'post' is the name of the url you defined in your urlconf, and slug=post.slug is the parameter you pass to the capturing group in your url regex.
Related
I would like to link this function to the link in the base Templates, but I have this error, what solution could be found? Should I use the Reverse function?
my views
def forumPostList(request, pk):
conversation = get_object_or_404(Conversation, pk=pk)
form_response = PostModelForm()
posts_conversation = Post.objects.filter(conversation=conversation)
context = {"conversation": conversation,
"posts_conversation": posts_conversation,
"form_response": form_response
}
return render(request, "account/forum_post.html", context)
{% extends 'base.html' %}
{% block content %}
<h1>Received messages:</h1>
<hr>
<br>
{% for post in posts_conversation %}
<h3>{{ conversation.title }}</h3>
<p>Posts: {{ post.author_post.posts.count }}</p>
<p>Posts: {{ post.author_post.username }}</p>
{% endfor %}
{% endblock content %}
My base
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{% url 'forum_post' %}">forum_post</a>
</li>
forumPostList view needs to get 'pk' as parameter in url. So for calling it with a link, your link should specify 'pk'.
So you can use url block like this:
{% url 'forum_post' conversation_pk %}
That coversation_pk should be specified somehow.
**Can someone please help me solve this problem I just started learning Django.
I keep getting getting "PAGE NOT FOUND " whenever i open/click the list/entries
In my "entries" folder i have
Css.md
Django.md
Git.md
Python.md
HTML.md**
screenshot of "Page not found"
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry, name="entry"
views.py
from django import forms
class NewEntryForm(forms.Form):
title = forms.CharField(max_length=100)
content = forms.CharField(widget=forms.Textarea)
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def entry(request, entry):
entries = util.get_entry(entry)
if entries is None:
return render(request, "encyclopedia/error.html", {
"message1": "Sorry",
"message2": "your requested page was not found "
})
return render(request, "encyclopedia/index.html", {
"content": entries,
"form": NewEntryForm
})
index.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<h1>All Pages</h1>
<ul>
{% for entry in entries %}
<li></li>
{% endfor %}
</ul>
{% endblock %}
entry.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<div class="container">
<div class="row">
{% if not content%}
<div>Sorry, your requested page was not found </div>
{% else %}
{{ content | safe }}
<div>Edit this entry</div>
{% endif %}
</div>
</div>
{% endblock %}
edit anchor tag in entry.html. URL is given wrong, Do this
<div><a href="{% url 'entry' entry %}>Edit this entry</a></div>
instead of
<div><a href="{% url 'edit' entry %}>Edit this entry</a></div>
you forget to close "".
write this:
<div>Edit this entry</div>
simple.....
I am in the process of making a edit listing system for my website and have run into an issue, the problem I am having is with my edit listing portal which displays all the listings associated with the relevant account. The idea is that people can click on any of the listings and it will take them to the edit listing form, however my edit listing form is suppose to be given a public key when you click on it. My problem is I dont know how to put the listings pk into the url. Could somebody please advise me on what to do?
Thanks
Code -
Listings Portal -
{% extends "base.html" %}
{% block content %}
<h1 class="pageheader">Edit Your Job Listings</h1>
<div class="joblistings">
<p class="jobcounter">There are <b>{{ joblistings.count }}</b> jobs available</p>
{% if joblistings %}
{% for joblisting in joblistings %}
{% if joblisting.active_listing %}
<div class="listings-item">
<a href="{% url 'editlisting' %}"> <--- THIS IS THE URL
<ul>
<li class="listing-title">{{ joblisting.job_title }} - {{ joblisting.business_name }}</li>
<li>Region: {{ joblisting.business_address_suburb }}</li>
<li>Pay Rate: ${{ joblisting.pay_rate }}</li>
<li>Contact Method: {{ joblisting.contact_method }}</li>
</ul>
</a>
</div>
{% endif %}
{% endfor %}
{% else %}
<p>Unfortunately all of the job opportunities have been taken at this moment.</p>
{% endif %}
</div>
{% endblock %}
Edit Listing View -
# This is the view which manages the edit listing page
#login_required(redirect_field_name='login')
def editlisting(request, pk):
post = JobListing.objects.get(pk=pk)
#if str(request.user) != str(post.user):
# return redirect("index")
if request.method == "POST":
print("test")
form = JobListingForm(request.POST, instance=post, force_update=True)
if form.is_valid():
form.save()
return redirect('index')
else:
print("else")
form = JobListingForm(instance=post)
context = {
"form": form
}
return render(request, "editlisting.html", context)
How about this?
Click me
I'm trying to open a specific bootstrap tab on a webpage using page slugs. For example:
www.mysite.domain/profile/#my_courses
will open profile page with courses history tab active
Here is my code:
urls.py
urlpatterns = [
url(r'^profile/$', views.profile, name='profile'),
url(r'^profile/(?P<page_slug>[\w-]+)/$', views.profile, name='profile'),
]
view.py profile
#login_required
def profile(request, page_slug=None):
profile = UserProfile.objects.get(user__username=request.user.username)
courses = Course.objects.filter(trainer__in = [profile]).order_by('start_time')
trainings = Course.objects.filter(students__in = [profile]).order_by('start_time')
return render(request, 'accounts/profile.html', context = {'courses': courses,
'trainings': trainings,
'page_slug': page_slug,})
profile.html
{% extends 'base.html' %}
{% load staticfiles %}
{% load i18n %}
{% block headers %}
{{ block.super }}
<link rel='stylesheet' href='{% static "accounts/css/profile.css" %}'/>
{% endblock %}
{% block content %}
<ul class='nav nav-tabs navbar-inverse'>
<li class='active'><a href= '#profile' data-toggle='tab'>{% trans 'Profile' %}</a></li>
<li><a href='#trainings' data-toggle='tab'>{% trans 'My Trainings' %}</a></li>
{% if user.profile.is_trainer %}
<li><a href='#courses' data-toggle='tab'>{% trans 'My Courses' %}</a></li>
{% endif %}
</ul>
<div id='content' class='tab-content'>
<div class='tab-pane fade active in' id='profile'></div>
<div class='tab-pane fade' id='my_trainings'>
<ul class='courses__container'></ul>
</div>
{% if user.profile.is_trainer %}
<div class='tab-pane fade' id='courses'>
<ul class='courses__container'></ul>
</div>
{% endif %}
</div>
{% endblock %}
Since javascript on user-side can't understand django template tags I can't do this in javascript. How can I add/remove active class in <li> and <div> tags in django template?
In the URL
www.mysite.domain/profile/#my_courses
#my_courses is a fragment, not a slug. URL fragments only exist in the browser, they are not sent to the web server, and so you URL routing and templates will never see them.
When the user visits that url, what is sent to the server is
www.mysite.domain/profile/
And that's the page that is returned. You'd need JavaScript on the page to inspect the full URL (through document.location.href) and update the page accordingly.
A slug, on the other hand, is not separated by a # character, and forms part of the URL that is sent to the server. That can be seen by Django, and inform the view as to what to render in the template. You would need to redesign your URLs to take advantage of that, though.
I am making a simple blog app in Django as a learning exercise. I am able to add posts, see them all on the front page, so it is working so far. Where I am having an issue is creating a view that shows the whole post on a separate page. I want to click the title, and go to a page at the url /post/primary key that has the title and body. When I click on the link, I get a page with just the base.html. Not sure where I am missing anything, here are urls.py, views.py, and post.html:
urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('blog.views',
url(r'^$', 'frontpage'),
url(r'^post/(\d+)/$', 'post'),
)
urlpatterns += patterns('',
url(r'^admin/', include(admin.site.urls)),
)
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from blog.models import *
views.py
def frontpage(request):
posts = Post.objects.all().order_by("-created")
paginator = Paginator(posts, 5)
page = request.GET.get('page', '1')
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render_to_response("list.html", dict(posts=posts, user=request.user))
def post(request, pk):
"""Single Post"""
post = Post.objects.get(pk = pk)
d = dict(post=post, user=request.user)
return render_to_response("post.html", d)
post.html
{% extends "base.html" %}
{% block content %}
<div class ="main">
<ul>
{% for post in posts.object_list %}
<div class = "title">{{ post.title }}</div>
<ul>
<div class="time"> {{ post.created }}</div>
<div class ="body"> {{ post.body|linebreaks }}</div>
</ul>
{% endfor %}
</ul>
</div>
{% endblock %}
Thanks in advance for your help.
I am assuming the page.html is actually the post.html you have in yoru codes sample???You no longer have a collection of posts but instead just have 1 post
This needs to change from: (which is looping through your posts)
{% extends "base.html" %}
{% block content %}
<div class ="main">
<ul>
{% for post in posts.object_list %}
<div class = "title">{{ post.title }}</div>
<ul>
<div class="time"> {{ post.created }}</div>
<div class ="body"> {{ post.body|linebreaks }}</div>
</ul>
{% endfor %}
</ul>
</div>
{% endblock %}
To something like (which just displays your single post):
{% extends "base.html" %}
{% block content %}
<div class ="main">
{{ post.title }}
{{ post.created }}
{{ post.body }}
</div>
{% endblock %}
You have to change urls.py to go to a page at the url /post/primary key.
urlpatterns = patterns('blog.views',
url(r'^$', 'frontpage'),
url(r'^post/(?P<pk>\d+)/$', 'post'),
)