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'),
Related
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' ),
]
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.
I have overridden my admin change_list.html
{% extends "admin/change_list.html" %}
{% block object-tools-items %}
<li>
Import CSV
</li>
{{ block.super }}
{% endblock %}
When I click this Import CSV link, I would like to import CSV and save to my model.
App's name Auction. Objects of Auction:
forms.py
from django import forms
import csv
from auction.models import AuctionGroup, AuctionHouse, AuctionList
class DataInput(forms.Form):
file = forms.FileField()
def save(self):
records = csv.reader(self.cleaned_data["file"])
for line in records:
house = AuctionHouse()
house.house_name = line[0]
house.auction_type = line[1]
house.auction_day = line[2]
house.volume = line[3]
house.aleado_id = line[4]
house.aleado_photo_number = line[5]
house.house_region = line[6]
house.save()
views.py
def csv_import(request):
if request.method == "POST":
form = DataInput(request.POST, request.FILES)
if form.is_valid():
form.save()
success = True
context = {"form": form, "success": success}
return render_to_response("auction/importcsv.html", context,
context_instance=RequestContext(request))
else:
form = DataInput()
context = {"form": form}
return render_to_response("auction/importcsv.html", context,
context_instance=RequestContext(request))
urls.py
urlpatterns = patterns('',
url(r'/importcsv/$', views.csv_import, name='importcsv'),
)
project/urls.py
urlpatterns = patterns('',
url(r'^auction/', include('auction.urls')),
url(r'^admin/', include(admin.site.urls)),
)
importcsv.html
<!DOCTYPE html>
<html>
<form enctype="multipart/form-data" method="post" action=".">
{{ form }}
</form>
</html>
But it does not work. Please, help. Regards
Use the {% url %} tag in the link code:
Import CSV
If you want to use single template for multiple models then change_list.html has the cl.opts context variable which is a Model._meta of the current model.
So you can pass the app_label and model_name to your importcsv() view:
<a href="{% url 'importcsv' cl.opts.app_label cl.opts.model_name %}"
class="grp-state-focus addlink">Import CSV</a>
Change your urls.py:
urlpatterns = patterns('',
url(r'/importcsv/(\w+)/(\w+)/$', views.csv_import, name='importcsv'),
)
And the signature of the view function:
def csv_import(request, app_label, model_name):
...
models.py
from django.db import models
class Blog(models.Model):
time = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length = 100)
slug = models.SlugField()
perex = models.TextField()
content = models.TextField()
#models.permalink
def get_absolute_url(self):
return ('blog', [self.slug])
def __unicode__(self):
return self.title
class Meta:
ordering = ['-time']
views.py
from django.shortcuts import render_to_response, get_object_or_404
from blog.models import Blog
def blog_entries(request):
blogs = Blog.objects.all()[0:3]
title = "Blogs"
return render_to_response('blog/blog.djhtml', {'blogs': blogs, 'title': title,})
def blog_single_entry(request, slug):
blog = get_object_or_404(Blog, slug=slug)
title = blog.title
return render_to_response('blog/single.djhtml', {'blog': blog, 'title': title,})
url.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'kablog.views.home', name='home'),
# url(r'^kablog/', include('kablog.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', 'blog.views.blog_entries', name='blog'),
url(r'^blog/(?P<slug>[-\w]+)/', 'blog.views.blog_single_entry', name='single_blog'),
)
template
{% extends 'base.djhtml' %}
{% block title %}| {{title}}{% endblock %}
{% block content %}
<div class="hero-unit">
<h1>Welcome to my Blog</h1>
<p>Where knowledge is always free</p>
<p>
<a class="btn btn-primary btn-large">
Read More
</a>
</p>
</div>
<div class="row">
{% for blog in blogs %}
<div class="span4">
<h2>{{blog}}<small>{{blog.time|date:"M D d Y"}}</small></h2>
<p>{{blog.perex|safe}}</p>
<a class="btn" href="{{ blog.get_absolute_url }}">
Read More
</a>
</div>
{% endfor %}
</div>
{% endblock %}
blog.get_absolute_url does not return a slug and also even though i have have try to browse "blog/my-first-blog" the browser just displays the home blog not the single_blog and it doesn't return a 404 error if you browse "blog/dgdsghdsfhdsfhds"
I also tried that but I can't make it work, so I try other approach
class Blog(models.Model):
[......]
#property
def get_blog_url(self):
return reverse('blog', args=[self.slug])
<a class="btn" href="{{ blog.get_blog_url }}">
Read More
</a>
You need to make #models.permalink instead #permalink.
I'd like to add Imageform to my form to allow all users to add a photo.
I've read this https://docs.djangoproject.com/en/dev/ref/forms/fields/#imagefield
and this https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files
but still I'm confused about how to achieve that. How can I change my codes to allow users to add a photo from their own folders?Here's my codes and I also attached the ideal form I'd like to create.
[My ideal form]
models.py
from django.db import models
from django.forms import ModelForm
class Sell(models.Model):
subject = models.CharField(max_length=100)
price = models.CharField(max_length=100)
condition = models.CharField(max_length=100)
photo = models.ImageField(upload_to="media")
email = models.EmailField()
body = models.CharField(max_length=200)
forms.py
from django.forms import ModelForm
from uasite1.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
views.py
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
from uasite1.forms import SellForm
from uasite1.models import Sell
from django.template import RequestContext
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
new_sell = form.save()
return HttpResponseRedirect('/sechand/%d/' % new_sell.pk)
else:
form = SellForm()
context['form'] = form
return render_to_response('sell.html',context,context_instance = RequestContext(request))
sell.html
{% extends 'base.html' %}
{% block extrahead %}
{% endblock %}
{% block content %}
<form enctype="multipart/form-data" action = "/sechand/" method = "post">
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
{% endblock%}
sell_display.html (this is the template where the submitted information would show up.)
{% extends 'base.html' %}
{% block content %}
<div id = 'sell'>
<h3> Product Name : [ {{ sell.subject }}]</h3>
<p>Photo{{ sell.photo }}</p>
<p>Price: [ {{ sell.price }} ]</p>
<p>Condition: [ {{ sell.condition }} ]</p>
<p>Comments: [ {{sell.body}} ]</p>
<p>Contact Email:[ {{ sell.email }} ]</p>
</div>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','uasite1.views.sell_create'),
url(r'^sechand/(?P<pk>\d+)/$', 'uasite1.views.sell_detail'),
url(r'^products/electronics/$', 'uasite1.views.Electronics'),
url(r'^products/$', 'uasite1.views.ProductsAll'),
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I did not go through your entire code but I can notice 1 important mistake, view should have the following:
form = SellForm(request.POST, request.FILES)
Also, this line:
<p>Photo{{ sell.photo }}</p>
I don't think that's the way to show a photo, I would put a link to the photo doing:
<p>Photo{{ sell.photo.url }}</p>
And finally, for development environments you may want to serve media files so just add this line to your main urls.py file:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# your url patterns in here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
editing:
Serving media files. That link should give you a good overview, it's confusing I know, so I am going to give you an example, just like I do in my projects. First the way I do it in settings.py:
#settings.py
from os.path import dirname, join, realpath
# have in mind that I have settings.py under project_root/project/settings.py
# so you probably want to check your path to your project root folder first
ROOT_DIR = realpath(join(dirname(__file__), '..'))
MEDIA_ROOT = realpath(join(ROOT_DIR, 'media'))
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
join(ROOT_DIR, "static"),
)
That's the way I do it, you could find many ways that also work. To give you a better clue my folders look like this:
project_root/
media/
static/
project/
settings.py