Django logout button bootstrap navbar - django

I want to add a logout button to my bootstrap navbar but it doesn't look right.
{# template.html #}
<nav class="navbar navbar-light">
<div class="container">
<div class="navbar-expand">
<ul class="navbar-nav mr-auto">
{% if user.is_authenticated %}
<li class="nav-item">
{{ user.get_username }}
</li>
<form class="form-inline nav-item" action="{% url 'account_logout' %}" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-info">Log out</button>
</form>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'account_login' %}">Log in</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'account_signup' %}">Sign up</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
is there any way to make the button look like a bootstrap nav-link ? If not, how do I make it an anchor that will POST to Django's logout endpoint?

This should work
<li class="nav-item">
<a class="nav-link" href="#"
onClick="document.getElementById('logoutform').submit()">
Logout
</a>
</li>
<form id="logoutform" method="POST" action="{% url 'account_logout' %}">
{% csrf_token %}
<input type="hidden">
</form>

You don't need a form. Simply replace the form with this:
Logout

Related

Django template Syntax Error Invalid block tag

Iam New To Django : i Made a Simple Website Following Python Crash Course Book , iam getting this Error and i can't find The Problem ,
Here is the error:
Here is the login.html :
{% extends "learning_logs/base.html" %} {% load bootstrap4 %} {% block
page_header %}
<h2>Log in to your account</h2>
{% endblock page_header %} {% block content %}
<form method="post" action="{% url 'users:login' %}" class="form">
{% csrf_token %} {% bootstrap_form form %} {% buttons %}
<button name="submit" class="btn btn-primary">Log in</button>
{% endbuttons %}
<button name="submit">Log in</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}" />
</form>
{% endblock content %}
And here is base.html that login extends:
{% load bootstrap4 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Learning Log</title>
{% bootstrap_css %} {% bootstrap_javascript jquery='full' %}
</head>
<body>
<nav class="navbar navbar-expand-md navbar-light bg-light mb-4 border">
<a class="navbar-brand" tag="a" href="{% url 'learning_logs:index' %}">
Learning Log</a
>
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarCollapse"
aria-controls="navbarCollapse"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{% url 'learning_logs:topics' %}"
>Topics</a
>
</li>
</ul>
<ul class="navbar-nav ml-auto">
{% if user.is_authenticated %}
<li class="nav-item">
<span class="navbar-texxt">Hello,{{user.username}}</span>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'users:logout' %}">Log out</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'users:register'%}">Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'users:login'%}">Log in</a>
</li>
{% endif %}
</ul>
</div>
</nav>
<main role="main" class="container">
<div class="pb-2 mb-2 border-bottom">
{% block page_header %} {% endblock page_header %}
</div>
<div>{% block content %} {% endblock content %}</div>
</main>
</body>
</html>
i tried looking for any syntax writing like answered questions here did like leaving epty space between { and % but i couldn't find anything helpful ,
Try to remove the line break in the end of line 1.
I mean, you should replace
{% extends "learning_logs/base.html "%} {% load bootstrap4 %} {% block
page_header %}
with
{% extends "learning_logs/base.html "%} {% load bootstrap4 %} {% block page_header %}
Replace
{% endblock page_header %}
To
{% endblock %}
And apply this to your other end blocks
it was a Problem with Preetier Code Formatter Every time i save the could would Go wrong , So i Changed To Default Html Formatter, Hope this helps Someone in the Future as it's quite hidden

403 Forbidden CSRF cookie not set even when it is in the form

When I attempt to log in to my django website, I always get a 403 Forbidden CSRF cookie not set error. When viewed via developer tools, the CSRF token was in the form response, but there were no cookies. I have django.middleware.csrf.CsrfViewMiddleware in my middleware, and I am using the standard django.contrib.auth.views.LoginView.
Here is my template:
{% extends 'base/formbase.html' %}
{% block title %}Login{% endblock title %}
{% block menuid %}menu-login{% endblock menuid %}
{% block submitname %}Login{% endblock submitname %}
{% block extra %}
<div class="alert alert-danger">
Forgot Your Password?
</div>
<div class="alert alert-secondary">
Don't have an account? Sign Up!
</div>
{% endblock extra %}
base/formbase.html:
{% extends 'base/base.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="row justify-content-center">
<div class="col-6">
<div class="card">
<div class="card-body">
{% block form %}
<h2>{% block title %}{% endblock title %}</h2>
<form method="post" novalidate>
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">{% block submitname %}{% endblock submitname %}
</button>
</form>
{% endblock form %}
</div>
{% block extra %}{% endblock extra %}
</div>
</div>
</div>
{% endblock body %}
base/base.html:
<!DOCTYPE html>
{% load base_extra %}
<html lang="en">
<head>
{% settings gamename "GAME_NAME" %}
<meta charset="UTF-8">
<title>{{ gamename }} - {% block title %}{% endblock title %}</title>
{% block head %}{% endblock head %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% settings debug "DEBUG" %}
{% if debug %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/latest/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://unpkg.com/#popperjs/core/dist/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/latest/js/bootstrap.js"></script>
{% else %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://unpkg.com/#popperjs/core/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/latest/js/bootstrap.min.js"></script>
{% endif %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="{% url 'index' %}">{{ gamename }}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item" id="menu-home">
<a class="nav-link" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" id="menu-gamelist">
<a class="nav-link" href="{% url 'game:game_list' %}">Game List</a>
</li>
<li class="nav-item" id="menu-leaderboard">
<a class="nav-link" href="{% url 'user_list' %}">Leaderboard</a>
</li>
{% if request.user.is_staff %}
<li class="nav-item" id="menu-admin">
<a class="nav-link" href="{% url 'admin:index' %}">Admin</a>
</li>
{% endif %}
</ul>
<!--
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
-->
<ul class="navbar-nav ml-auto">
{% if request.user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
{{ request.user }}
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'user' user.pk %}">Profile</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{% url 'logout' %}">Log out</a>
</div>
</li>
<li class="nav-item">
<div class="nav-link">${{ request.user.gameinfo.money }}</div>
</li>
{% else %}
<li class="nav-item" id="menu-signup">
<a class="nav-link" href="{% url 'signup' %}">Sign Up</a>
</li>
<li class="nav-item" id="menu-login">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
{% endif %}
</ul>
</div>
</nav>
<div class="mx-3 mt-2">
<script>
try {
document.getElementById("{% block menuid %} {% endblock menuid %}").classList.add("active");
}
catch {}
</script>
{% block body %}
{% endblock body %}
</div>
</body>
</html>
Adding the #csrf_protect decorator does not solve the problem.
This may occur if you have CSRF_COOKIE_SECURE = True explanation in the docs Or if you have CSRF_COOKIE_HTTPONLY = True explanation or if you wish to just disable the csrf token you can add the #csrf_exempt decorator to the view

Why I am getting a filter error for my template tag?

I'm not sure why I am getting this filter error. I looked up other peoples similar issues with this, and I am definitely loading my template tag, I restarted the server, I have a template tags folder with an init.py file and the file that holds my tag, so , what am I doing wrong here?
error is at {{ request.user|unread_messages }}, Invalid filter: 'unread_messages'
unread_message_counter.py
from django import template
from dating_app import models
register = template.Library()
#register.simple_tag
def unread_messages(user):
return user.InstantMessage.filter(viewed=False).count()
**base.htmnl **
{% load bootstrap4 %}
{% load unread_messages_counter %}
<!-- Navbar is located in this file -->
<!doctype html>
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
{% block head %}
<title>Basee</title>
{% endblock %}
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{% url 'dating_app:home' %}">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<!-- Below is login/registration links and the logic-->
{% if user.is_authenticated %}
Hello, {{ user.username }}
<ul class="mylinks">
<div>
<li>My Profile</li>
<li>log out</li>
<div>
</ul>
<li class="nav-item">
<a class="nav-link" href="{% url 'dating_app:view_matches' user.id %}">Matches</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'dating_app:conversations' user.id %}">Inbox</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'dating_app:mingle' %}">Mingle</a>
</li>
<li class="nav-item">
{{ request.user|unread_messages }}
</li>
{% else %}
<div>
log in
<br>
register
</div>
{% endif %}
This is not a template tag [Django-doc], this is a template filter [Django-doc]. A tag would mean you render this as {% unread_messages … %}. You thus can make it a filter with:
from django import template
from dating_app import models
register = template.Library()
#register.filter
def unread_messages(user):
return user.InstantMessage.filter(viewed=False).count()
Or you can work with a tag, by keeping the #registered.simple_tag, and render this with {% unread_messages request.user %}.
I believe the problem is the name used to load the tag.
Instead of:
{% load unread_messages_counter %}
Try:
{% load unread_messages %}

Active Tag in for extended templates

I'm a newbie to Django and want some help on template inheritance.
I want to set "class="active" for the current active page but how do I do with template inheritance,as it generalizes it for all the pages but the active should change on changing current active page.
I know this question might be silly but I don't know the answer still.
I have no idea what to do for this case.
Extended html
<ul class="navbar-nav mr-auto">
<li class="nav-item mx-3">
<a class="nav-link" {% if '/Homepage/' in request.path %} class ="active" {% endif %} href="{% url 'success' %}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item mx-3">
<a class="nav-link" {% if '/booking/' in request.path %} class ="active" {% endif %} href="{% url 'booking' %}">Make a Booking</a>
</li>
<li class="nav-item mx-3">
<a class="nav-link" {% if '/Hsitory/' in request.path %} class ="active" {% endif %} href="{% url 'History' %}">History</a>
</li>
<li class="nav-item mx-3">
<a class="nav-link" {% if '/pending/' in request.get_full_path %} class ="active" {% endif %} href="{% url 'pending' %}">Pending requests</a>
</li>
</ul>
urls.py
urlpatterns = [
path('', views.loginpage, name="loginpage"),
path("failed/", views.failed, name="failed"),
path("Homepage/", views.success, name="success"),
path("loggedout/", views.loggedout, name="logout"),
path("booking/", views.booking, name="booking"),
path("pending/", views.pending, name="pending"),
path("History/", views.History, name="History"),
path("Register/", views.Register, name="Register"),
]
I expect the active class might get applied to only current active pages.
You can try like this.
<a class="nav-link" {% if '/Homepage/' in request.path %} class ="active" {% endif %} href="/Homepage/">Home <span class="sr-only">(current)</span></a>
Also better use the django url template tag
EDIT: I think you are providing wrong url patterns
You can also do this
{% url 'homepage' as url %}
<a {% if request.path == url %} class="active"{% endif %} href="{{ url }}" >Homepage</a>
You have two class attribute in your anchor tag so you can change this to
<a class="nav-link{% if request.path == url %} active{% endif %}">Home <span class="sr-only">(current)</span></a>
Extended Html
<li class="nav-item mx-3">
{% url 'success' as Homepage %}
{% if request.path != Homepage %} <a class="nav-link" href="{% url 'success' %}">Home <span
class="sr-only">(current)</span></a>
{% else %}
<a class="nav-link active" href="{{ Homepage }}">Home <span class="sr-only">(current)</span></a>
{% endif %}
</li>
<li class="nav-item mx-3">
{% url 'booking' as booking %}
{% if request.path != booking %} <a class="nav-link" href="{{ booking }}">Make a Booking</a>
{% else %}
<a class="nav-link active" href="{{ booking }}">Make a Booking</a>
{% endif %}
</li>
<li class="nav-item mx-3">
{% url 'History' as History %}
{% if request.path != History %} <a class="nav-link" href="{{ History }}">History</a>
{% else %}
<a class="nav-link active" href="{{ History }}">History</a>
{% endif %}
</li>
<li class="nav-item mx-3">
{% url 'pending' as pending %}
{% if request.path != pending %} <a class="nav-link" href="{{ pending }}">Pending requests</a>
</li>
{% else %}
<a class="nav-link active " href="{{ pending }}">Pending requests</a>
{% endif %}
</li>
Used request.path for the solution

Py 3.6 // Django 2.1.4 : Accessing User Profile mysteriously changes the status of user.is_authenticated to True

I have been having this problem for 2 weeks now I can't seem to solve it.
I have a social website where user's can upload their resumes for recruiters to see.
And when I access some user's profile, the Navbar acts as if I am logged in, which I am not.
I tried fixing this issue by using get_queryset() ,it worked but I couldn't manage to display user's profile data.
so I stuck with get().
Here's a visual explanation:
As you can see the navbar says Home/Login/Signin
Now if I access John Doe's Profile, the navbar will switch to Home/Profile/Logout:
Here's my code;
views.py:
class HomeProfile(ListView):
"Di splays all active users in db"
template_name = 'profile/home_profile.html'
queryset = MyModel.objects.filter(is_active=True)
class Get_Profile(DetailView):
"fetches user's profile"
def get(self, request, pk):
user = MyModel.objects.get(pk=pk)
return render(request, 'profile/profile.html', {'user':user})
urls.py
urlpatterns = [
path('homepage/profiles/', user_view.HomeProfile.as_view(), name='homepage'),
path('homepage/profile/<int:pk>/', user_view.Get_Profile.as_view(), name='user-profile'),
]
base_test.html
<nav class="navbar navbar-expand-sm navbar-dark bg-dark sticky-top">
<a class="navbar-brand" href="{% url 'home' %}">Navbar</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="{% url 'homepage' %}">Home<span class="sr-only">(current)</span></a>
</li>
{% if not user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'signup' %}">Sign Up</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="#">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Log Out</a>
</li>
{% endif %}
</ul>
</div>
</nav>
home_profile.html
<!-- this is the home template that displays all active users -->
{% extends 'base_test.html' %}
{% block title %} My Site | Profiles {% endblock title %}
{% block content %}
<div class="card-columns text-center padding">
{% for user in mymodel_list %}
<div class="card">
<img class="rounded-circle" src="{{user.profile.image.url}}" width=150 height=150>
<div class="card-body">
<h5 class="card-title">Full name : {{user.get_full_name}}</h5>
<p class="crad-text">Occupation/job : {{user.profile.occupation}}</p>
<a type="button" href="{% url 'user-profile' user.pk %}" style="color:whitesmoke;" class="btn btn-primary btn-sm">Profile</a>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
{% block footer %}
{% endblock footer %}
profile.html
<!-- user profile template -->
{% extends 'base_test.html' %}
{% load custom_tags %}
{% block title %} My Site | {{user.get_full_name}} {% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-8 order-lg-2 padding">
<div class="tab-content">
<div class="tab-pane active" id="profile">
<div class="row">
<div class="col-lg-12">
<h6><strong>About</strong></h6>
<p>
{{user.profile.bio}}
</p>
<hr>
</div>
<div class="col-lg-12">
<h6><strong>Skills</strong></h6>
{% for skill in user.profile.skills|split:',' %}
<span class="badge badge-primary">{{skill}}</span>
{% endfor %}
<hr>
<h6><strong>Hobbies</strong></h6>
<p>
{% for hobbie in user.profile.hobbies|split:',' %}
<span class="badge badge-success">{{hobbie}}</span>
{% endfor %}
</p>
<hr>
</div>
<!-- removes the social part -->
</div>
</div>
</div>
</div>
<div class="col-lg-4 order-lg-1 padding">
<h1 class="mb-3 text-center">{{user.get_full_name}}</h1>
<hr>
<img src="{{user.profile.image.url}}" class="mx-auto img-fluid rounded-circle d-block" alt="avatar" width=150><br>
<div class="text-center">
<h4>{{user.profile.school}}</h4>
<p><strong>Hometown :</strong> {{ user.profile.hometown}}</p>
<p><strong>Current City:</strong> {{user.profile.location}}<p>
<p><strong>Occupation/Job:</strong> {{user.profile.occupation}}<p><br>
<hr>
<button type="button" class="btn btn-outline-success btn-md">View CV</button>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block footer %}
{% endblock footer %}
I don't know What is causing this strange behaviour!!
Actually, you are mixing up with request.user and your user object for resume. You should change the context variable name from user to something else. for example:
class Get_Profile(DetailView):
"fetches user's profile"
def get(self, request, pk):
user = MyModel.objects.get(pk=pk)
return render(request, 'profile/profile.html', {'profile':user}) # <-- Here
You've used the same variable name, user, for the user whose profile you are viewing as for the one who is actually using the site. You need to pick another name.
(Also, unrelated, but you don't need to - and shouldn't - define the get method in your detail view.)