Why Django update page and log out didn't work? - django

This is dashboard page with django login
This is analyse page after i login but the user didn#t show up
I click the analyse page when i am anonumoususer, the user didn't change after i login
I don't get the reason why i am logged in but the user did not show up.
Besides when i click logout it doesn't work either.Below is my logout code. I really appreciate it if anyone could help me!!
from django.shortcuts import render,redirect
import hashlib
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import authenticate,get_user_model,login,logout,get_user
from .forms import UserLoginForm,UserRegisterForm
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.template import Template,Context
from .decorators import unauthenticated_user,allowed_users, admin_only
from django.contrib.auth.decorators import login_required
#csrf_exempt
#unauthenticated_user
def login_view(request):
next = request.GET.get('next')
form =UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
else:
return redirect('/home')
context = {
'form': form,
}
return render(request,'users/login.html',context)
def index(request):
return render(request,'users/home.html')
#csrf_exempt
def register_view(request):
next = request.GET.get('next')
register_form = UserRegisterForm(request.POST or None)
if register_form.is_valid():
user = register_form.save(commit=False)
password = register_form.cleaned_data.get('password1')
user.set_password(password)
user.save()
new_user = authenticate(username=user.username,password=password)
login(request, new_user)
if next:
return redirect(next)
return redirect('/userlist')
context = {
'form': register_form,
}
return render(request,'register.html',context)
def logout_view(request):
user = get_user(request)
logout(request)
request.session.flush()
print('you are log out from cms!')
request.user = AnonymousUser
return render(request,'logout.html')
def userlist(request):
User = get_user_model()
result = User.objects.all()
#template = Template('userlist.html')
#html = template.render(Context({'content': result}))
return render(request,'userlist.html',{'content':result})
def adduser(request):
return render(request,'todo.html')
#login_required(login_url='accounts/login/')
def notpermitted(request):
return render(request,'NotPermitted.html')
This is the side bar in template. The sidebar will change based on user roll.
{% load static %}
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="/home">
<div class="sidebar-brand-icon">
<img class="img-responsive center-block" src="{% static 'img/cms.png'%}" alt="" width="72" height="57">
</div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Dashboard -->
<li class="nav-item active">
<a class="nav-link" href="/dashboard">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Function
</div>
<!-- Nav Item - Pages Collapse Menu -->
{% if request.user.is_staff %}
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseFive"
aria-expanded="true" aria-controls="collapseFive">
<i class="fas fa-fw fa-chart-area"></i>
<span>Dataset</span>
</a>
<div id="collapseFive" class="collapse" aria-labelledby="headingFive" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Dataset:</h6>
<a class="collapse-item" href="/adddata">Add Dataset</a>
<a class="collapse-item" href="/datasetlist">Datasets</a>
</div>
</div>
</li>
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseThree"
aria-expanded="true" aria-controls="collapseThree">
<i class="fas fa-fw fa-cog"></i>
<span>historical Data</span>
</a>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Dataset:</h6>
<a class="collapse-item" href="/upload">upload</a>
<a class="collapse-item" href="/home">Rest</a>
</div>
</div>
</li>
{% endif %}
<li class="nav-item">
<a class="nav-link collapsed" href="/processed" data-toggle="collapse" data-target="#collapseTwo"
aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-fw fa-cog"></i>
<span>ProcessedData</span>
</a>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Dataset:</h6>
<a class="collapse-item" href="/processed">list</a>
<a class="collapse-item" href="/processed/opc">opc</a>
<a class="collapse-item" href="/processed/mqtt">mqtt</a>
</div>
</div>
</li>
<!-- Nav Item - Utilities Collapse Menu -->
<li class="nav-item">
<a class="nav-link collapsed" href="/analyse" data-toggle="collapse" data-target="#collapseUtilities"
aria-expanded="true" aria-controls="collapseUtilities">
<i class="fas fa-fw fa-wrench"></i>
<span>Analyse</span>
</a>
<div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities"
data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Methode:</h6>
<a class="collapse-item" href="/analyse/fft">Fast Fourier Methode</a>
<a class="collapse-item" href="/analyse/limit_monitoring">Limit Monitoring</a>
</div>
</div>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
{% if request.user.is_superuser %}
<!-- Heading -->
<div class="sidebar-heading">
Usermanagement
</div>
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseFour"
aria-expanded="true" aria-controls="collapseFour">
<i class="fas fa-fw fa-cog"></i>
<span>Users</span>
</a>
<div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">User:</h6>
<a class="collapse-item" href="/userlist">List</a>
<a class="collapse-item" href="/adduser">add User</a>
</div>
</div>
</li>
{% endif %}
</ul>
This is topbar! the current user will be listed here.
``
<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
<i class="fa fa-bars"></i>
</button>
<!-- Topbar Search -->
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-light border-0 small" placeholder="Search for..."
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - Search Dropdown (Visible Only XS) -->
<li class="nav-item dropdown no-arrow d-sm-none">
<a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-search fa-fw"></i>
</a>
<!-- Dropdown - Messages -->
<div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in"
aria-labelledby="searchDropdown">
<form class="form-inline mr-auto w-100 navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-light border-0 small"
placeholder="Search for..." aria-label="Search"
aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</li>
<!-- Nav Item - Alerts -->
<li class="nav-item dropdown no-arrow mx-1">
<li class="nav-item">Login</li>
<li class="nav-item">Logout</li>
</li>
<div class="topbar-divider d-none d-sm-block"></div>
<!-- Nav Item - User Information -->
<li class="nav-item dropdown no-arrow">
<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mr-2 d-none d-lg-inline text-gray-600 small">Hello, {{ request.user }}</span>
</a>
</li>
</ul>
````
I use request.user to decide the user roll. it seems to be that the page is stored in the browser when i first load this page. So when i update the page after i login in, the page i loaded before didn't change the user in sidebar and topbar. i disabled cookies and cache in my browser but it still doesn't work, hope anyone hat a answer!

Related

URL automatically changes & it gives me the error of Page not found

"127.0.0.1:8000/adminpanel/edit_gallary/29"
So this is the main problem when I first edit it works properly. But when I want to edit the second time URL automatically changes & it changes this way.
"127.0.0.1:8000/adminpanel/edit_gallary/edit_gallary/29"
This is my views.py file:
def edit_gallary(request,gallaryid):
table = gallary.objects.get(id=gallaryid)
gallary_form = gallaryform(instance=table)
if request.method=='POST':
form = gallaryform(data=request.POST, files=request.FILES, instance=table)
if form.is_valid():
form.save()
table=gallary.objects.all()
return render(request,"gallary1.html",{'table':table})
context = {'gallary_form':gallary_form}
return render(request,'edit_gallary.html',context)
This is my URLS.py file:
path('edit_gallary/<int:gallaryid>',views.edit_gallary,name="edit gallery"),
This is my edit_gallary.html file:
{% extends 'index.html' %}
{% block content %}
<body>
<div class="main-wrapper">
<div class="app" id="app">
<header class="header">
<div class="header-block header-block-collapse d-lg-none d-xl-none">
<button class="collapse-btn" id="sidebar-collapse-btn">
<i class="fa fa-bars"></i>
</button>
</div>
<div class="header-block header-block-nav">
<ul class="nav-profile">
<li class="profile dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button"
aria-haspopup="true" aria-expanded="false">
<div class="img"
style="background-image: url('https://avatars3.githubusercontent.com/u/3959008?v=3&s=40')">
</div>
<span class="name">Admin</span>
</a>
<div class="dropdown-menu profile-dropdown-menu" aria-labelledby="dropdownMenu1">
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">
<i class="fa fa-power-off icon"></i> Logout </a>
</div>
</li>
</ul>
</div>
</header>
<aside class="sidebar">
<div class="sidebar-container">
<div class="sidebar-header">
<div class="brand">
<div class="logo">
<span class="l l1"></span>
<span class="l l2"></span>
<span class="l l3"></span>
<span class="l l4"></span>
<span class="l l5"></span>
</div> Compare school
</div>
</div>
<nav class="menu">
<ul class="sidebar-menu metismenu" id="sidebar-menu">
<li>
<a href="insert_school">
<i class="fa fa-home"></i>Back</a>
</li>
</ul>
</nav>
</div>
</aside>
<div class="sidebar-overlay" id="sidebar-overlay"></div>
<div class="sidebar-mobile-menu-handle" id="sidebar-mobile-menu-handle"></div>
<div class="mobile-menu-handle"></div>
<article class="content responsive-tables-page">
<div class="title-block">
<h1 class="title">Gallary</h1>
<p class="title-description"></p>
</div>
<section class="section">
<div class="row">
<div class="table-responsive">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table class="table table-striped table-bordered">
{{ gallary_form }}
<tr>
<td class="text-right mb-3">
<input type="submit" value="register" class="btn btn-primary" >
</td>
</tr>
</table>
</form>
</div>
</div>
</section>
</article>
</div>
</div>
<script src="js/vendor.js"></script>
<script src="js/app.js"></script>
{% endblock %}
</body>
It seems you need to change 'edit_gallary/<int:gallaryid>' to '<int:gallaryid>/edit_gallary/' in urls.py or just try adding a slash to the route end in your path

why Image is not loading in django template?

I uploaded a picture in the Django database but when I try to show this picture in Django templates, it's not showing anything but showing the image title.
Here is my index.html
{% for value in data %}
<div class="product-box">
<div class="img-wrapper">
<div class="front">
<a href="product-page(no-sidebar).html"><img
src="{{ value.product_img.url }}"
class="img-fluid blur-up lazyload bg-img" alt=""></a>
</div>
<div class="back">
<a href="product-page(no-sidebar).html"><img
src="{{ value.product_img.url }}"
class="img-fluid blur-up lazyload bg-img" alt=""></a>
</div>
<div class="cart-info cart-wrap">
<button data-bs-toggle="modal" data-bs-target="#addtocart"
title="Add to cart"><i class="ti-shopping-cart"></i></button> <a
href="javascript:void(0)" title="Add to Wishlist"><i
class="ti-heart" aria-hidden="true"></i></a> <a href="#"
data-bs-toggle="modal" data-bs-target="#quick-view"
title="Quick View"><i class="ti-search" aria-hidden="true"></i></a>
<a href="compare.html" title="Compare"><i class="ti-reload"
aria-hidden="true"></i></a>
</div>
</div>
<div class="product-detail">
<div class="rating"><i class="fa fa-star"></i> <i class="fa fa-star"></i> <i
class="fa fa-star"></i> <i class="fa fa-star"></i> <i
class="fa fa-star"></i></div>
<a href="product-page(no-sidebar).html">
<h6>{{ value.product_title }}</h6>
</a>
<h4>{{ value.price }}</h4>
<ul class="color-variant">
<li class="bg-light0"></li>
<li class="bg-light1"></li>
<li class="bg-light2"></li>
</ul>
</div>
</div>
{% endfor %}
Here is my views.py
def home(request):
context={
'data': Products.objects.all()
}
return render(request, 'auctionApp/index.html',context)
Just add below code in urls.py file in the project directory:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Flask-Bootstrap navbar not functioning properly

So, here is what I have in my app.py file:
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask( __name__)
Bootstrap(app)
#app.route('/')
def hello():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Here is what I have in my index.html file:
{% extends "bootstrap/base.html" %}
{% block navbar %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</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 active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<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">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</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>
</div>
</nav>
{% endblock %}
{% block content %}
{% endblock %}
First picture is what I expect to see, second picture is what I actually get. I've cleared all cache on my browsers, tried Google Chrome and Mozilla Firefox. Please advise.
Flask boostrap is dead i think the last commit was made over 3 years ago...
https://getbootstrap.com/docs/4.3/getting-started/introduction/
Use that starter template as your base.html and add the navbar there.

Django 2.2 error - Integrity Error, NOT NULL constraint failed

I have a sample Django 2.2 project that has a search bar in the top right corner of the nav bar (taken from the Bootstrapers):
navbar.html:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Navbar</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 active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="/search/">Search</a>
</li>
...
{% endif %}
<li class="nav-item">
<a class="nav-link" href="/a/">A</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/b/">B</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action = '/search/'>
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
It returns "You searched for [search argument]" to the url '/search/' and works fine. I would like to bring it from the nav bar under the 'Search' menu in the nav bar. I have the following:
searches/models.py
from django.db import models
from django.conf import settings
# Create your models here.
class SearchQuery(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null=True, on_delete=models.SET_NULL)
query = models.CharField(max_length=220)
timestamp = models.DateTimeField(auto_now_add=True)
searches/views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from .models import SearchQuery
# Create your views here.
#login_required
# staff_member_required
def search_view(request):
query = request.GET.get('q', None)
user = None
if request.user.is_authenticated:
user = request.user
SearchQuery.objects.create(user=user, query=query)
context = {"query": query}
return render(request, 'searches/view.html',context)
searches/templates/searches/view.html:
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form action = '/search/'>
<input type="search" name="q" aria-label="Search">
<button type="submit">Search</button>
</form>
<div class='row'>
<div class='col-12 col-8 mx-auto'>
<p class='lead'>You searched for {{ query }}</p>
</div>
</div>
{% endif %}
{% endblock %}
When I search from the search bar in the navigational pane, it returns the argument. But when I want to run the search from the search bar and click on the Search tab, I get this:
IntegrityError at /search/
NOT NULL constraint failed: searches_searchquery.query
...
...searches\views.py in search_view
SearchQuery.objects.create(user=user, query=query)
Why am I getting this ?
EDIT:
After making this change in searches/views.py:
query = request.POST.get('q', None)
I get this error in the runtime:
django.db.utils.IntegrityError: NOT NULL constraint failed: searches_searchquery.query
and in the browser:

modal contact form in django does not appear

I am trying to add contact form using bootstrap modal, so far contact modal pops up but with out the form. I have already checked couple of examples on internet but still no luck.
Here is my code from files:
in urls.py
url(r'^contact/$', view=ContactFormView.as_view(), name='contact'),
forms.py
class ContactForm(forms.Form):
firstname = forms.CharField()
lastname = forms.CharField()
sender = forms.EmailField(required=True)
subject = forms.CharField(max_length=100, required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
cc_myself = forms.BooleanField(required=False)
def send_email(self):
# send email using the self.cleaned_data dictionary
pass
views.py
class ContactFormView(FormView):
template_name = 'feedme/contact.html'
form_class = ContactForm
success_url = '/thanks/'
success_message = "Congratulations !"
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super(Contact, self).form_valid(form)
and templates:
contact.html
<!-- Modal -->
<div class="modal fade" id="contact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Formularz kontaktowy</h4>
</div>
<div class="modal-body">
<form id="ContactForm" action="{{ contact }}" method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zamknij</button>
<button type="button" class="btn btn-success" id="add-btn">Wyslij</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
_nav.html
{% include "feedme/contact.html" %}
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/"><span class="glyphicon glyphicon-globe yellow"></span>Polski Kanal</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="{% block navbar_class-nl %}{% endblock %}">Holandia</li>
<li class="{% block navbar_class-de %}{% endblock %}">Niemcy</li>
<li class="{% block navbar_class-en %}{% endblock %}">Anglia</li>
<li class="{% block navbar_class-ie %}{% endblock %}">Irlandia</li>
<li class="{% block navbar_class-es %}{% endblock %}">Hiszpania</li>
</ul>
<div class="col-sm-3 col-md-3">
<form class="navbar-form" role="search" name="input" action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" class="form-control" name="feed_search_string" id="feed_search_string" value="{% if feed_search_string %}{{ feed_search_string }}{% else %}Szukaj{% endif %}">
<div class="input-group-btn">
<button class="btn btn-success" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
<ul class="nav navbar-nav navbar-right">
<li> <span class="glyphicon glyphicon-info-sign white"></span>About</li>
<!-- modal start here -->
<li> <span class="glyphicon glyphicon-envelope white"></span>Kontakt</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
As I mentioned, modal is a popup with header and footer. In fireburg I am seeing csrf_token in modal-body but no form.
Pointing my browser to 127.0.0.1/contact/ form is presented.
Could some one help me with this?