I am getting the next NoReverseMatch error:
NoReverseMatch at /
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.11.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name.
Exception Location: /home/ivan/.local/lib/python2.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497
Python Executable: /usr/bin/python
Python Version: 2.7.12
Python Path:
['/home/ivan/My_website/essostrade (copy 1)',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/home/ivan/.local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/wx-3.0-gtk2']
Server time: Fri, 25 Aug 2017 22:51:14 +0000
But the thing is that there is no 'logout' neither in the highlighted main.js line in the template, nor somewhere else in the templates.
Here are my templates:
main.html:
{% extends "base.html" %}
{% load staticfiles %}
{% block additional_css %}
<link type="text/css" href="{% static "main.css" %}" rel="stylesheet">
{% endblock %}
{% block content %}
<div id="header">
<h1>Браавосская лавочка</h1>
</div>
<!-- <div id="leftmenu">
<ul>
{% url "main" as page_url %}
<li><a href="{{ page_url }}"{% if page_url == current_url %} class="current"{% endif %}>Главная</a></li>
{% if user.is_authenticated %}
<li class="indented">Админка</li>
<li class="indented">Выйти</li>
{% endif %}
</ul>
</div> -->
<div id="main">
{% block main %}
{% endblock %}
</div>
<div id="footer">
<p>Все права принадлежат Матери Драконов</p>
</div>
{% endblock %}
mainpage.html:
{% extends "main.html" %}
{% block title %}Главная страница{% endblock %}
{% block main %}
<h2>Удивительные товары со всего Вестероса</h2>
<p>Фирма веников не вяжет, фирма делает гробы</p>
{% endblock %}
here is my views.py file:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.views.generic import TemplateView
from generic.mixins import CategoryListMixin
from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django import forms
class MainPageView(TemplateView, CategoryListMixin):
template_name = "mainpage.html"
class LoginView(TemplateView):
template_name = "login_logout.html"
isLoggedIn = False
class PageNumberMixin(CategoryListMixin):
def get_context_data(self, **kwargs):
context = super(PageNumberMixin, self).get_context_data(**kwargs)
try:
context["pn"] = self.request.GET["page"]
except KeyError:
context["pn"] = "1"
return context
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
And here is my urls.py file:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include
from main.views import LoginView, MainPageView
from main.views import signup
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', MainPageView.as_view(), name='main'),
url(r'^signup/$', signup, name='signup'),
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
I really don't know where did this 'logout' appear from.
Your main.html template is trying to reverse the URL logout, but you haven't added a URL pattern for the logout view.
{% url "logout" %}
from django.contrib.auth.views import LogoutView
url(r'^logout/$', LogoutView.as_view(), name='logout'),
You'll have to either create a registration/logged_out.html template to display, or set LOGOUT_REDIRECT_URL in your settings.
Related
I've created an app where you can make comment (which sends a form to a database and saves it) if you're login on only, but when I press the button "Create" instead of redirecting me to the page where it show all the comments, it logs me out and bring me back to the "log out" view (which is / )
the create Template:
{% extends 'base.html' %}
{% block content %}
<div class="create_comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
The Views of Create:
#login_required(login_url='/userprofile/login/')
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
form.save()
return redirect('/usercomments')
else:
form = forms.CreateComment()
return render(request,'usercomments/comments_create.html', {'form':form})
Log out view:
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/')
else:
pass
usercomments Urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
userprofile urls.py:
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]
I created a simple login logout app using the Out of the box django LoginView and LogoutView. In my app, I can signup using CreateView, list the users using ListView and get user details using DetailView.
I am seeing issues with login and logout when I click the browser's back button.
Issues:
Upon login, I am redirected to index page. However when I click the back button, I land back at login page and can login with other valid user.
Upon logout, I am redirected to index page. However when I click the back button, I can view the logged-in data such as the list page and details page.
The code for my app (accounts) is :
settings.py
<code>
LOGIN_REDIRECT_URL = "/accounts/"
LOGOUT_REDIRECT_URL = "/accounts/"
project urls.py
<code>
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
path("accounts/", include("accounts.urls")),
]
app urls.py
<code>
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts_app'
urlpatterns = [
path("", views.IndexPage_cview.as_view(), name="index_curl"),
path("login/", auth_views.LoginView.as_view(),name='login'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("signup/", views.SignUp_cview.as_view(), name="signup_curl"),
path("super/", views.adminlist_cview.as_view(), name="super_curl"),
path("superdetail/<int:pk>", views.admindetail_cview.as_view(),
name="super_detail_curl"),
]
app views.py
<code>
from django.contrib.auth import login, logout
from django.urls import reverse_lazy
from django.views.generic import TemplateView,CreateView, ListView,
DetailView
from django.contrib import auth
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404
from . import forms
class IndexPage_cview(TemplateView):
template_name = "accounts/index.html"
class SignUp_cview(CreateView):
form_class = forms.UserCreate_cform
success_url = reverse_lazy("login") #redirect to /accounts/login/
template_name = "accounts/signup.html"
class adminlist_cview(LoginRequiredMixin,ListView):
template_name = 'accounts/super_list.html'
model= auth.models.User
def get_queryset(self):
return auth.models.User.objects.order_by('username')
class admindetail_cview(LoginRequiredMixin,DetailView):
template_name = 'accounts/super_detail.html'
model= auth.models.User
def get_object(self):
return get_object_or_404(auth.models.User, pk=self.kwargs.get("pk"))
app model.py
<code>
from django.contrib import auth
from django.db import models
class User_cmodel(auth.models.User):
def __str__(self):
return "#{}".format(self.username)
app form.py
<code>
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreate_cform(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
base.html
<div class="container">
Home
<ul >
{% if user.is_authenticated %}
{% if request.user.is_superuser %}
<li><a href="{% url 'admin:index' %}" >Admin</a></li>
<li><a href="{% url 'accounts_app:super_curl' %}>Db List</a></li>
{% endif %}
<li><a href="{% url 'accounts_app:logout' %}>Log out</a></li>
{% else %}
<li><a href="{% url 'accounts_app:login'%}" >Log in</a></li>
<li>Sign up</li>
{% endif %}
</ul>
</div>
<div class="container mycontent">
{% block content %}
{% endblock %}
</div>
login.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<h1>Login</h1>
<form method="POST" >
{% csrf_token %}
{% form %}
<input type="submit" value="Login" >
</form>
</div>
{% endblock %}
No where in the code, you are making the views available only for logged in user. All your views are accessible by anybody.
If you are using custom Auth backend you can use #login_required decorator from django.contrib.auth.decorators. To ensure the user is logged in before going to the view.
You should read this. https://docs.djangoproject.com/en/2.1/topics/auth/default/#authenticating-users
The error is Reverse for 'django_with_ocr.ocr.views.list' not found. 'django_with_ocr.ocr.views.list' is not a valid view function or pattern name
Exception value here is not a valid function or pattern name.
There is also an error 'charmap' codec can't encode character '\ufb01' in position 843: character maps to
views.py
from django.shortcuts import render
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Document
from .forms import DocumentForm
from django.http import HttpResponse
import csv
import ipdb
from Cython.Compiler.Buffer import context
try:
import Image
except ImportError:
from PIL import Image
import pytesseract
global i
i = 0
def list(request):
global i
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
i += 1
# import ipdb;ipdb.set_trace()
d = Document.objects.get(id=i)
#print d.docfile
k=pytesseract.image_to_string(Image.open(d.docfile))
#print k
handle = open('data.txt', 'a+')
handle.write(k)
handle.close()
txt_file = r"data.txt"
csv_file = r'mycsv.csv'
in_txt = csv.reader(open(txt_file, "r"), delimiter = ' ')
out_csv = csv.writer(open(csv_file, 'w', encoding='utf-8'))
out_csv.writerows(in_txt)
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('django_with_ocr.ocr.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render(request,
'list.html',
{'documents': documents, 'form': form},
context
)
url.py
from django.urls import path
from . import views
urlpatterns = [
path('list/', views.list,name='list' ),
]
list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>OCR Converter</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
</body>
</html>
URL for the project is
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('ocr/', include('ocr.urls')),
path('', RedirectView.as_view(url='/ocr/list/', permanent=True)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You are calling
return HttpResponseRedirect(reverse('django_with_ocr.ocr.views.list'))
You just have to call the url by its app name and url name (assuminng that ocr is the name of your app)
return HttpResponseRedirect(reverse('ocr:list'))
EDIT
Add
app_name = 'ocr'
urlpatterns = [
path('list/', views.list,name='list' ),
]
I want to execute a javascript at the time of login and logout. I tried to use
user_logged_in.connect(myfunction) singal that executes at the time of login. I returned HttpResponse in myfunction but thats not working.
Other option is is_authenticated() but that just check if user is logged in ,does not check if login session is just starting.
Is there any way to render data to template using user.logged_in() signal or any other way through i can achieve this ?
For a login action, you can make use of a generic FormView, and add the message in success_message bring to you by the SuccessMessageMixin, in views.py file:
from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView
class LoginView(SuccessMessageMixin, FormView):
form_class = AuthenticationForm
template_name = 'login.html'
success_url = reverse_lazy('home') # url's name to redirect
success_message = 'Welcome back %(username)s!' # A welcome message
def form_valid(self, form):
user = form.get_user()
login(self.request, user)
return super(LoginView, self).form_valid(form)
And for the logout is enough with a function view, and the django messages framework:
from django.contrib.auth.views import logout
from django.http import HttpResponseRedirect
def logout_view(request):
logout(request)
messages.success(request, u"You have logout successfully!") # custom message for success logout
return HttpResponseRedirect('/')
Add the urls to your urls.py file:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import LoginView, logout_view
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', logout_view, name='logout'),
)
When the action occurs the messages object is available in the template, so just use a loop to show the messages, index.html:
<body>
{% if user.is_authenticated %}
log out
{% else %}
login
{% endif %}
Some content
{% if messages %}
{% for message in messages %}
<div id='message-alert' class='alert alert-success'>
{{ message }}
</div>
{% endfor %}
{% endif %}
more content
</body>
You also need to render the login form in login.html:
{% if user.is_authenticated %}
<p>You are authenticated as <span class="text-success">{{ user.username }}</span></p>
Log out
{% else %}
<form method="post">
{{ form.as_p }}
{% csrf_token %}
<button class="btn">Login</button>
</form>
{% endif %}
Note: the css classes come from bootstrap, if it's the case GOOD, else just use your own.
I need your help. I am a django beginner and I am unable to use linkcolumn from django-tables2. I am really disappointed because I am sure it's really simple but until now, it doesn't work. I thank you in advance for the time granted to my problem and beg your pardon if it's stupid of simplicity ;-)
Sum up:
index.html returns a django-tables2 table and everything is ok
I want to change datas of column "name" to hyperlink (using linkcolumn) with target ".../Audit/1/" where 1 comes from pk of the clicked row of course
An error occurs:
NoReverseMatch at /fr/Audit/
Reverse for 'detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Request Method: GET
Request URL: http://localhost:8000/fr/Audit/
Django Version: 1.6.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Exception Location: /opt/myenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 452
Python Executable: /opt/myenv/bin/python2.7
Python Version: 2.7.6
Audit/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from MyParam.models import MyModel, MyMptt
from mptt.models import TreeForeignKey
from organization.models import Org
class Grid(MyMptt):
name = models.CharField(max_length = 45, verbose_name=_(u"grille d'audit"))
parent = TreeForeignKey('self', limit_choices_to={'act': True}, related_name='children', null=True, blank=True, verbose_name=_(u"parent"))
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
verbose_name = _(u"grille d'audit")
verbose_name_plural = _(u"grilles des audits")
def __unicode__(self):
return unicode(self.name)
Audit/urls.py
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from Audit import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<grid_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<grid_id>\d+)/vote/$', views.vote, name='vote'),
url(r'^(?P<grid_id>\d+)/report/(?P<report_id>\d+)$', views.report, name='report'),
)
Audit/tables.py
# -*- coding: utf-8 -*-
import django_tables2 as tables
from django_tables2.utils import A
from Audit.models import Grid
class GridTable(tables.Table):
name = tables.LinkColumn('detail', args=[A('pk')])
class Meta :
model = Grid
# add class="paleblue" to <table> tag
attrs = {"class": "paleblue"}
VISU = ("id", "name", "parent")
sequence = VISU
fields = VISU
Audit/views.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django_tables2 import RequestConfig
"""
from django.views import generic
"""
from Audit.models import Grid, Item, Assessment, Report, ReportContent
from Audit.tables import GridTable
from organization.models import Org
def index(request):
"""
audit_grid_list = Grid.objects.all().order_by('name')[:5]
context = {'audit_grid_list': audit_grid_list}
return render(request, 'Audit/index.html', context)
"""
table = GridTable(Grid.objects.all())
RequestConfig(request).configure(table)
RequestConfig(request, paginate={"per_page": 25}).configure(table)
return render(request, "Audit/index.html", {"table": table})
def detail(request, grid_id):
org_list = Org.objects.all().order_by('name')[:5]
grid = get_object_or_404(Grid, pk=grid_id)
return render(request, 'Audit/detail.html', {'grid': grid,'org_list': org_list})
Audit/templates/index.html
{# Audit/templates/index.html #}
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}django_tables2/themes/paleblue/css/screen.css" />
</head>
<body>
{% render_table table %}
</body>
</html>
Audit/templates/detail.html
<h1>{{ grid.name }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'Audit:vote' grid.id %}" method="post">
{% csrf_token %}
<!-- test pour choix du service -->
<label for="org">Choix de la cible de l'audit</label>
<select name="org" id="org">
{% for firm in org_list %}
<option value="{{ firm.id }}">{{ firm.name }}</option>
{% endfor %}
</select><br>
{% for item in grid.Item_grid.all %}
<h2>{{ item.name }}</h2>
{% for assess in item.Assessment_item.all %}
<input type="checkbox" name="item{{ forloop.parentloop.counter }}[]" id="item{{ forloop.parentloop.counter }}[]" value="{{ assess.id }}" />
<label for="item{{ forloop.parentloop.counter }}">{{ assess.name }}</label><br />
{% endfor %}
{% endfor %}
<input type="submit" value="Vote" />
</form>
Your URL regex has a named group, so grid_id should be a keyworded argument. Use
name = tables.LinkColumn('detail', args={'grid_id': A('pk')})