I am having trouble getting my search form to work in Django. When I search anything in the search bar I have set, I get an html page that just has the words Search on it. It's not the html page I set, though. My search template is in my projects templates directory. I am trying to search through my blog posts, and have attached my views and urls code.
This portion of my base template is within a navbar I grabbed from a sample Bootstrap blog template. This is the sample template. I've changed some things within my form.
base.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet" type='text/css'>
{% load static %}
<!-- Navbar here -->
<nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="{% url 'index' %}">ChairBlog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'index' %}active{% endif %}" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'project_index' %}active{% endif %}" href="{% url 'project_index' %}">Projects </a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'blog_index' %}active{% endif %}" href="{% url 'blog_index' %}">Blog </a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action="{% url 'search' %}" method="GET">
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search blog posts...">
<button class="btn my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!-- Jumbotron stuff here -->
<div class="jumbotron d-flex align-items-center" style="margin-top: 56px;">
<div class="container text-center">
{% block jumbo_content %}
{% endblock %}
</div>
</div>
<!-- Main content goes here -->
<div class="container" style="padding-bottom: 200px;">
{% block page_content %}{% endblock %}
</div>
<!-- Footere here -->
<footer style="position: relative;">
<div class= "page-footer bg-dark" style="padding-top: 20px; margin-top: 50px;">
<div class="container" style="display: flex; justify-content: center;">
<div class= "row">
<div class="mb-10 flex-center">
<a class="github" href="https://github.com/ChairMane"><i class="fa fa-github-square fa-2x"></i></a>
</div>
</div>
</div>
<div class="footer-copyright text-center py-3" style="color: white;">Chair Birds Co.</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
Nothing within my blocks shows up when I view it. The tags <p>TEST</p> and <p>Is this working?</p> are not showing up. Neither is the block for the jumbo_content. I have set those correctly in my base.html, because they work with my other pages. It's just the search page it doesn't work on.
search.html
{% extends "base.html" %}
{% load static %}
{% block jumbo_content %}
<h1 class="display-4">Search Results</h1>
{% endblock %}
{% block page_content %}
<p>TEST</p>
{% if query %}
{% if results %}
<ul>
{% for post in results %}
<p>Is this working?</p>
<li>
{{ post.title }}, {{ post.body }}
</li>
{% endfor %}
</ul>
{% else %}
<p>Query returned no results.</p>
{% endif %}
{% endif %}
{% endblock %}
app/views.py
...
def search_posts(request):
query = request.GET.get('q', '')
if query:
queryset = (Q(title__icontains=query) | Q(body__icontains=query))
results = Post.objects.filter(queryset).distinct()
else:
results = []
context = {
'results' : results,
'query' : query
}
return render(request, 'search.html', context)
...
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog_index, name='blog_index'),
path('<int:pk>/', views.blog_detail, name='blog_detail'),
path('<category>/', views.blog_category, name='blog_category'),
path('search/', views.search_posts, name='search'),
]
Here is how the search template is being viewed, I believe. My issues are as shown in the image. The inspector shows nothing within the blocks I've set. I have jumbo_content and page_content, and yet none of what I set within each block shows up.
Can anyone see anything immediately wrong here? I've tried this tutorial as well, and the same thing happens.
EDIT It seems my search_posts(request) function in my views is not even being called when I search something in the search bar. I tried tracebacks, and printing and nothing showed up in my terminal. Am I not correctly calling search_posts(request)?
I finally got my answer. I looked at this post and decided to try something. Apparently, if I change my app/urls.py line from this:
path('search/', views.search_posts, name='search'),
to this:
path('search', views.search_posts, name='search'),
then my whole view works.
Can anyone explain why that is? I had no idea removing a / could help.
Related
When I open http://127.0.0.1:8000/ which is home.html, I am getting:
NoReverseMatch at / and Reverse for 'exam-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['exam/(?P[^/]+)$']
I think the error is due to <str:pk> in urls.py.
The urls.py file is below:
from . import views
from .views import ExamListView, ExamDetailView
app_name='map'
urlpatterns = [
path("", ExamListView.as_view(), name='map-home'),
path("exam/<str:pk>", ExamDetailView.as_view(), name="exam-detail"),
path("login_student/", views.login_student, name='map-login'),
path("register_student", views.register_student, name='map-register'),
path('add_student/', views.add_student, name='add_student'),
path('front/', views.front, name="front"),
]
models.py:
subject = models.TextField(primary_key = True, unique = True)
def __str__(self):
return self.subject
home.html
{% extends "map/base.html" %}
{% block content %}
<p>WELCOME HOME</p>
{% for exam in exams %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'map:exam-detail' exam.subject %}">{{ exam }} </a>
</div>
</div>
</article>
{% endfor %}
{% endblock content %}
base.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'map/main.css' %}">
{% if title %}
<title>{{ title }}</title>
{% else %}
<title> MAP PAGE </title>
{% endif %}
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="/">Project M.A.P</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'map:map-home' %}">Home</a> <!-- no hardcoded links -->
<a class="nav-item nav-link" href="{% url 'map:map-home' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
<a class="nav-item nav-link" href="{% url 'map:map-register' %}">Student</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<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>
</body>
</html>[enter image description here][1]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.urls import reverse
from . models import Student, Exam
from django.views.generic import ListView, DetailView
def home(request):
context = {
'exams': Exam.objects.all()
}
return render(request, 'map/home.html', context)
class ExamListView(ListView): #class based views
model = Exam
template_name = 'map/home.html' #<app>/<model>_<viewtype>.html
context_object_name = 'exams'
ordering = ['subject'] #['-exam']
class ExamDetailView(DetailView):
model = Exam
You missed exam.pk in the home.html
Update your code in this manner,
<div class="article-metadata">
<a class="mr-2" href="{% url 'map:exam-detail'
exam.pk %}">{{ exam }} </a>
</div>
</div>
In
python manage.py shell
from my_app_name.models import Exam
exam = Exam()
exam.subject = ""
exam.save()
I have executed these lines. and I also created exams for subject like "google", "english",..
Now Exam.objects.all() returns
<QuerySet [<Exam: google>, <Exam: english>, <Exam: >]>
The problem is due to having a string of length zero as subject for one of the exam object. Now I deleted that exam using Exam.objects.get(subject="").delete(). Problem solved.
{% url 'map:exam-detail' exam.subject %}
or
{% url 'map:exam-detail' exam %}
or
{% url 'map:exam-detail' exam.pk %}
all these are working now because all are returning the subject. But {% url 'map:exam-detail' exam.id %} won't work. Because I have made subject as primary_key in the Exam model, so Exam model don't have an attribute id(which is added by default when no primary_key is mentioned).
thinking about why it has accepted the empty string as a subject, though I have defined it as primary_key.
Then I wanna read about django.db.models.TextField and just keyed help(TextField) and got
TextField(verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=<class 'django.db.models.fields.NOT_PROVIDED'>, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text='', db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None)
Now tried validators...
The follow up problem link
Thank you all
Mounika
Hi I would like to change the size of my form post box (where the placeholder sits), its quite long. I was wondering how I would change it with my code below:
forms.py
from django import forms
from home.models import Post
class HomeForm(forms.ModelForm):
post = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'How are you feeling?',
}
))
class Meta:
model = Post
fields = ('post',)
home.html:
{% extends 'base.html' %}
{% block body%}
<div class="container">
<br/>
<form method="post">
{% csrf_token %}
{{ form.post }}
<br />
<button type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{ post.post }}</h1>
<p>Posted </b> on {{ post.created }}</p>
{% endfor %}
</div>
{% endblock %}
base.html:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% block head %}
<title>anonmy</title>
{% endblock %}
</head>
<body>
<br>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
{% if user.is_authenticated %}
<ul class="nav navbar-nav">
<li><b>anonmy</b></li>
<li><a href='{% url 'home:categories' %}'>categories</a></li>
<li>profile</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>log out</li>
</ul>
{% else %}
<ul class="nav navbar-nav">
<li>anonmy</li>
<li>login</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>forgotten password?</li>
<li>register</li>
</ul>
{% endif %}
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
</div>
{% block body %}
<h1>Base</h1>
{% endblock %}
</body>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
I know how to change a standard html form, but with ginger two templating/django im unsure.Would I have to add a css file to my project then edit it or do something in forms.py?
Thank you
you just edit it like a standard html file by adding a css file and use the class name you entred in the form attrs
Add this under your model form class
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['post'].widget.attrs.update({'size': '20'})
More about this here: Widgets
I'll start off by saying that I know that this question comes up a lot, but I wasn't able to find a solution in other topics.
I'm getting this error while trying to load a page.
The relevant views:
def index(request):
all_lists = GuestList.objects.all()
guest_list = GuestList()
for glist in all_lists:
guest_list = glist
return render(request, 'guestlist/base.html', {'guest_list': guest_list})
def guestlist(request, list_id):
g_list = get_object_or_404(GuestList, pk=list_id)
return render(request, 'guestlist/guestlist.html', {'g_list': g_list})
guestlist/urls.py:
app_name = 'guestlist'
urlpatterns = [
# /guestlist/
url(r'^$', views.index, name='index'),
# /guestlist/#/
url(r'^(?P<list_id>[0-9]+)/$', views.guestlist, name='guestlist'),
# /guestlist/#/isclose/
url(r'^(?P<list_id>[0-9]+)/isclose/$', views.isclose, name='isclose'),
]
The HTML fragment that the error occurs at:
The template:
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} SitDown {% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="{% static 'guestlist/style.css' %}"/>
<link href="https://fonts.googleapis.com/css?family=Abel|Galdeano" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Header -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'guestlist:index' %}">Sit Down</a>
</div>
<!-- Items -->
<div class="collapse navbar-collapse" id="topNavBar">
<ul class="nav navbar-nav">
<li class="active">
<a href="{% url 'guestlist:guestlist' guest_list.id %}">
<span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span>
Guest List
</a>
</li>
<li class="">
<a href="#">
<span class="glyphicon glyphicon-th" aria-hidden="true"></span>
Seating
</a>
</li>
<li class="">
<a href="#">
<span class="glyphicon glyphicon-check" aria-hidden="true"></span>
Checklist
</a>
</li>
<li class="">
<a href="#">
<span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span>
Help
</a>
</li>
</ul>
<form class="navbar-form navbar-left" role="search" method="get" action="#">
<div class="form-group">
<input type="text" class="form-control" name="q" value="">
</div>
<button type="submit" class="btn btn default">Search</button>
</form>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
Everything seems to be in order. The id is passed and it gets to the function 'guestlist()' like it should but i still get the error.
The view 'index()' renders 'base.html', which the exception occurs at.
Edit:
It seems that when I hardcode the list id like this: <a href="{% url 'guestlist:guestlist' 2 %}"> it works. But when i do it dynamically it doesn't. I checked the variable and both if the instances provide the same url.
1) According to your question title that means GuestList model doesn't have any entry.
2) Always use \d+ in url regex for digit match like: (?P<list_id>\d+)
in HTML, as you are passing a list of guestlist you have to iterate over it
Eg:
def index(request):
guest_list = GuestList.objects.all()
return render(request, 'guestlist/base.html', {'guest_list': guest_list})
and in HTML page
<body>
{% for guest in guest_list %} <-- Start LOOP
<a href="{% url 'guestlist:guestlist' guest.id %}"> <--- Individual Guest ID
{% endfor %} <-- End LOOP
</body>
Now you can get individual ID and pass it along url to your respective guestlist view view, if this is what you want.
Sorry if you tried helping me when I asked this earlier. Had to delete that post because I thought the question was poorly written.
So I have a login view that when I click submit throws the Error:
Exception Type: IOError
Exception Value:
[Errno 22] Invalid argument: u"C:\\Users\\Me\\Desktop\\mysite\\templates\\{'user': <CustomUser: coco>}"
Traceback:
C:\Users\Me\Desktop\mysite\accounts\views.py in login
40. return render('all_posts.html', {'user': request.user}, context_instance=RequestContext(request))
Originally my login view I had:
return HttpResponseRedirect('/')
instead of the current:
return render('all_posts.html', {'user': request.user}, context_instance=RequestContext(request))
and the former sort of worked, in the since that it didn't throw any errors and directed me to the proper url. but in my template; {% if request.user.is_authenticated %} wasn't working.
So I changed it in the hopes of getting my template to display the current user's name (Welcome, coco!), instead now I get this new error.
Here is my views.py
def login(request):
"""
Log in view
"""
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
django_login(request, user)
return render('all_posts.html', {'user': request.user}, context_instance=RequestContext(request))
else:
form = AuthenticationForm()
return render_to_response('login.html', {
'authenticationform': form,
}, context_instance=RequestContext(request))
base.html
<div class="log_bar">
<ul>
{% if request.user.is_authenticated %}
<li>Welcome,</li>
<li>{{ user.username }}</li>
<li>|</li>
<li>Log Out</li>
{% else %}
<li>Please</li>
<li><a data-toggle="modal" data-target="#modal-login" href="">log in</a></li>
<li>or</li>
<li><a data-toggle="modal" data-target="#modal-register" href="">sign up</a></li>
{% endif %}
</ul>
</div><!-- /.log_bar -->
EDIT 1: Login Template
login.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<div class="modal" id="modal-login">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="login/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Log In</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ authenticationform|crispy }}
</div>
<div class="modal-footer">
<input type='submit' class="btn btn-primary" value="Log In" />
</div>
</form>
</div>
</div>
</div>
EDIT 2: all_posts.html
all_posts is empty right now. basically it just extends base.html. I'll post both.
all_posts.html
{% extends "base.html" %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>
EDIT 3: urls.py
from django.conf.urls import url, include
from blog import views
from accounts.views import get_profile, login, logout, register
import accounts
urlpatterns = [
url(r'^textpost$', views.submit_textpost, name='textpost'),
url(r'^linkpost$', views.submit_linkpost, name='linkpost'),
url(r'^$', views.all_posts, name='all_posts'),
url(r'^all$', views.all_posts, name='all_posts'),
url(r'^new$', views.new_posts, name='new_posts'),
url(r'^all/top_hour$', views.top_posts_hour, name='top_hour'),
url(r'^all/top_day$', views.top_posts_day, name='top_day'),
url(r'^all/top_week$', views.top_posts_week, name='top_week'),
url(r'^all/top_month$', views.top_posts_month, name='top_month'),
url(r'^all/top_year$', views.top_posts_year, name='top_year'),
url(r'^all/top_beginning_of_time$', views.top_posts_all, name='top_beginning_of_time'),
url(r'u/(?P<username>[a-zA-Z0-9]+)$', accounts.views.get_profile, name='username'),
url(r'register$', register, name='register'),
url(r'^profile/(?P<username>\w+/$)', get_profile, name='profile'),
url(r'logout/$', logout, name='logout'),
url(r'^login/$', login, name='login'),
url(r'(?P<username>[a-zA-Z0-9]+)/$', views.get_sub, name='sub_url'),
url(r'(?P<username>[a-zA-Z0-9]+)/(?P<title_slug>[a-zA-Z0-9]+)/$', views.get_sub, views.title_slug, name='sub_post'),
url(r'^comments/', include('django_comments_xtd.urls')),
]
base.html full
Side Note* In my nav class="navbar navbar-fixed-left navbar-static-top", notice all the href's are empty, that's because if I try to populate them {% url 'new_posts' %} etc.. it will throws the same Traceback:
'function' object is not iterable. I don't know if it's related, but I thought I should mention. I'm not even concerning myself with that now, I don't want to get ahead of myself. I'm just trying to learn how to do proper login for now.
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<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/base.css' %}">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<TITLE>{% block title %}{% endblock %}</TITLE>
</HEAD>
<BODY>
{% block content %}
{% block navigation %}
<div class="navbar-wrapper">
<div class="post_button" style="width:58px; margin:0 auto;">
Submit a Post
</div> <!-- /.post_button-->
<div class="log_bar">
<ul>
{% if user.is_authenticated %}
<li>Welcome,</li>
<li>{{ user.username }}</li>
<li>|</li>
<li>Log Out</li>
{% else %}
<li>Please</li>
<li><a data-toggle="modal" data-target="#modal-login" href="">log in</a></li>
<li>or</li>
<li><a data-toggle="modal" data-target="#modal-register" href="">sign up</a></li>
{% endif %}
</ul>
</div><!-- /.log_bar -->
<nav class="navbar navbar-fixed-left navbar-static-top">
<div class="container-fluid">
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav ">
<li class="active">Home <span class="sr-only">(current)</span></li>
<li>All</li>
<li>New</li
<li class="dropdown">
Top<span class="caret"></span>
<ul class="dropdown-menu">
<li>hour</li>
<li>24 hrs</li>
<li>week</li>
<li>month</li>
<li>year</li>
<li>beginning of time</li>
<li role="separator" class="divider"></li>
<li>Custom Search</li>
</ul>
</li>
</ul>
</div><!-- /.container-fluid -->
</nav>
<div id="side_bar">
<form class="navbar-form navbar-static-top navbar-right" role="search" id="navBarSearchForm">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" id="search_btn">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
</div><!-- /.side-bar -->
<button class="btn-block" id='hideshow' value='hide/show' style="display: block; height: 100%;"></button>
{% include 'register.html' %}
{% include 'login.html' %}
{% endblock %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.leanModal.js"></script>
{% endblock %}
</BODY>
</HTML>
The first argument of render must be request object, second template name, third context.
return render(request, 'all_posts.html', {'user': request.user})
This is my base.html file:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'css/css/bootstrap.css' %}">
<link rel="stylesheet" href="{% static 'css/css/bootstrap-theme.css' %}">
</head>
</html>
<body>
<nav class="navbar navbar-default"></nav>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Fitbit</li>
{% if user.is_anonymous %}
{% else %}
<li>Log Out</li>
{% endif %}
</div><!--/.navbar-collapse -->
</div>
</nav>
<center>
{% block content %}{% endblock %}
</center>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="css/js/jquery.min.js"> <\/script>')</script>
<script src="/static/css/js/bootstrap.min.js"></script>
<script src="/static/css/js/bootstrap.js"></script>
</body>
</html>
<footer>
<p>© 2016 Hanze Hogeschool Groningen</p>
</footer>
As you can see I'm doing a check if the user is anonymous if he is not anonymous it should show the log out button. But at the moment when I return to the homepage it still shows the Log Out button.
My question is, how do I make it so that the log out will not show on the homepage. According to my own thinking I think django still thinks I'm not anonymous on the homepage.
And this is the image for the problem:
homepage
You should be using is_authenticated instead:
{% if user.is_authenticated %}
<li>Log Out</li>
{% endif %}
And, you are not passing the request context from your view to a template, use render():
return render(request, 'index.html')