Django - NoReverseMatch error not a valid function or pattern - django

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' ),
]

Related

I'm getting a NoReverseMatch error in my home page

I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>

Why am I getting "NoReverseMatch at /" error?

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.

django form.save() fails to write to disk on model instance update

Ive been Playing around with django to create an asset management app and have hit a wall on the file upload to model instance behaviour.
I am attempting to use the ModelForm class in Forms.py
Basically im pretty certain that form.save() is not writing my uploaded file to disk to update my model instance.
Do I have to write a form.save definition into my AssetForm ? or have I missed something else.
Appreciate any help.
My project is built around the Polls tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial01/ and the minimal file upload tutorial at Need a minimal Django file upload example.
Here is my model .py
class Category(models.Model):
category_text = models.CharField(max_length=200)
def __str__(self): # __unicode__ on Python 2
return self.category_text
class Asset(models.Model):
asset_text = models.CharField(max_length=200)
asset_tag = models.CharField(max_length=200)
asset_category = models.ForeignKey(Category)
cert_date = models.DateTimeField('cert published')
def __str__(self): # __unicode__ on Python 2
return self.asset_text
def was_certed_recently(self):
return self.cert_date >= timezone.now() - datetime.timedelta(days=365)
was_certed_recently.admin_order_field = 'cert_date'
was_certed_recently.boolean = True
was_certed_recently.short_description = 'Certified recently?'
docfile = models.FileField(upload_to='documents')
Here is my forms.py
from django import forms
from django.forms import ModelForm
from polls.models import Asset
class AssetForm(ModelForm):
class Meta:
model = Asset
fields = '__all__'
Here is my views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
#from django.template import RequestContext, loader
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from polls.models import Asset
from polls.forms import AssetForm
def list(request, asset_id):
# Handle file upload
ID = asset_id
p = get_object_or_404(Asset, pk = asset_id)
if request.method == 'POST':
form = AssetForm(request.POST, request.FILES, instance= p )
if form.is_valid():
form.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list', args=(p.id,)))
else:
form = AssetForm() # A empty, unbound form
# Load documents for the list page
documents = p
# Render list page with the documents and the form
return render_to_response(
'polls/list.html',
{'documents': documents, 'ID': ID, 'form': form},
context_instance=RequestContext(request )
)
def index(request):
latest_asset_list = Asset.objects.order_by('-cert_date')[:]
context = {'latest_asset_list': latest_asset_list}
return render(request, 'polls/index.html', context)
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^/list/$', 'list', name='list'),
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<asset_id>[0-9]+)/$', views.list, name='list'),
# ex: /polls/5/results/
url(r'^(?P<asset_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<asset_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
Finally my list.html template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
<p>Current Doc.</p>
<li>{{ documents.docfile.name }}</li>
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<ul>
{{ ID }}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' ID %}" 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>
You're doing various things twice. For example, at the start of your function, you get an Asset into p and then you get the same one into a. Why?
More significantly, in the is_valid() block you create a new Asset object just from the uploaded file, with no other data from the form, but then you save the form itself which should update the existing Asset. This might be the cause of your problem - you should remove the lines with docfile and just save the form.

Linkcolumn does not work django-tables2

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')})

django slugfield url error

i get :
Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:
^ ^$
^ ^/(?P[a-zA-Z0-9]+) [name='view_blog_post']
The current URL, duzeltme-yazisi/, didn't match any of these.
this error.
here some outputs :
urls.py (in project folder) :
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('userside.urls')),
)
urls.py (in app's folder) :
from django.conf.urls import patterns, include, url
urlpatterns = patterns('userside.views',
url(r'^$','index'),
url(r'^/(?P<postslug>[^\.]+)','userside.views.singlePost',name='view_blog_post'),
)
views.py :
from userside.models import Post
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
post_list = Post.objects.all()
return render_to_response('userside/index.html',
{'post_list':post_list},
context_instance = RequestContext(request))
def singlePost(request,postslug):
post = Post.objects.get(slug=postslug)
context = {'post':post}
return render_to_response('userside/detail.html',context,context_instance = RequestContext(request))
models.py :
from django.db import models
#from django.utils import timezone
from django.db.models import permalink
class Post(models.Model):
title = models.CharField(max_length = 100)
# date = models.DateTimeField(auto_now_add=True)
text = models.TextField()
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.title
#permalink
def get_absolute_url(self):
return ('view_blog_post',None, {'postslug':self.slug})
and here is my index.html template file :
<html>
<head>
<title>Welcome</title>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/index.css" />
</head>
<body>
<h1>Hello Mars</h1>
<br>
{% if post_list %}
{% for x in post_list %}
<p>{{ x.title }}</p>
<p>{{ x.text }}</p>
<hr>
{% endfor %}
{% else %}
<div class="center">No records! ( but looks like code works correctly!)</div>
{% endif %}
</body>
</html>
Django version : 1.4
whats wrong here ? :/
thank you
project - urls.py
url(r'^$', include('userside.urls')),
userside - urls.py
url(r'^(?P<postslug>[-\w]+)/$',
# ../gis-grundlagen/
view = 'singlePost',
name = 'userside-single-post',
),
userside - views.py
def singlePost(request, postslug):
post = get_object_or_404(Post, slug=postslug)
context = {'post':post}
return render_to_response('userside/detail.html',context,context_instance = RequestContext(request))
There shouldn't be a $ when using include, try:
url(r'^', include('userside.urls')),
normally you would have a subfolder indicated, e.g.
url(r'^userside/', include('userside.urls')),
The initial slash (/) is probably also a mistake:
url(r'^/(?P<postslug>[^\.]+).html','userside.views.singlePost',name='view_blog_post'),
should likely be
url(r'^(?P<postslug>[^\.]+).html','userside.views.singlePost',name='view_blog_post'),