ViewDoesNotExist django - django

I've been working my way through the tutorials and thought that I'd understood the MVC framework. I have three models, two of which (Guests, Bookings) are populated. I can call data from Guests no problem. I tried to call data from Bookings and get ViewDoesNotExist at /bookings Tried booked_dates in module views. Error was: 'module' object has no attribute 'booked_dates'.
My urls are:
from django.conf.urls.defaults import *
#from views import current_datetime, people, detail, booked_dates
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('views',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.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'^time/$','current_datetime'),
url(r'^mariners/$','people'),
url(r'^mariners/(?P<guest_id>\d+)/$','detail'),
url(r'^bookings/$','booked_dates'),
)
The views are:
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from guests.models import Guest, Booking, Price
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return render_to_response('current_datetime.html', {'current_date': now})
def people(request):
guests_all = Guest.objects.all().order_by('last_name')
return render_to_response('guests_all.html', {'guests_all': guests_all})
def detail(request, guest_id):
g = get_object_or_404(Guest, pk=guest_id)
return render_to_response('guest_detail.html', {'detail' : g})
def booked_dates(request):
dates_all = Booking.objects.all().order_by('start_date')
return render_to_response('bookings.html', {'dates_all' : dates_all})
I haven't included the Models, but Booking is the correct class name, and start_date and end_date are correct.
I can't see an exact replica of this problem, and have tried numerous things to correct it, including a simple 'hello world' view, but I get the same error message.
I must be doing something wrong, but can't see what it might be. I've tried calling the views in a shell, which works.
Thanks for your help.

try including the app name with the view not just the view function
url(r'^bookings/$','guests.views.booked_dates'),

Related

Where to store my index.html and index view for a non-static Django homepage

I'm creating a Django project and currently have 3 apps (products, questions and choices) - I've got them all functioning separately/together as I'd like and am using namespaces and include as part of my urls (my urls.py given below...)
### urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^products/', include('products.urls', namespace='products')),
url(r'^questions/', include('questions.urls', namespace='questions')),
url(r'^choices/', include('choices.urls', namespace='choices')),
url(r'^admin/', include(admin.site.urls)),
)
Now I'm looking to add an index page (accessible at localhost:8000/) that will allow me to access all models created. I'm happy with my views.py...
## views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from products.models import Product
from questions.models import Question
from choices.models import Choice
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'latest_product_list'
def get_queryset(self):
return Product.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['questions'] = Question.objects.all()
context['choices'] = Choice.objects.all()
return context
What I'd like to know is, what is the most sensible combination of urls.py entry, positioning of views.py and location of index.html to allow me to show a combination of my models on the landing page?
Thanks,
Matt
Create another app (I tend to name it home). That way, your home app can import models from products, questions and choices.
App layout
home/urls.py
home/views.py
home/templates/index.html
Include your home urls just like your other apps (but don't use a prefix)
url(r'^', include('home.urls', namespace='home')),

Django NoReverseMatch Error

I'm trying to develop a blog script with Django. But when I want to show post links, I get NoReverseMatch error.
My views.py
# -*- coding: utf-8 -*-
# Create your views here.
from .models import Yazi, Yorum, Kategori
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.contrib.sites.models import Site
def Home(request):
try:
posts = Yazi.objects.filter(yayinlanmis=True).order_by('-yayinlanma_tarihi')
except Yazi.DoesNotExist:
raise Http404
site = Site.objects.get_current()
c = RequestContext(request,{
'posts':posts,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_list.html', c)
def Detail(request, slug):
post = Yazi.objects.get(slug=slug)
site = Site.objects.get_current()
c= RequestContext(request,{
'posts':post,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_detail.html',c)
Urls.py in application folder.
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.Home,name='index'),
url(r'^/makale/(?P<slug>[0-9A-Za-z._%+-]+)$', views.Detail,name='detail'),
)
Urls.py in project folder
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('',
url(r'^$', include('Penguencik_Yazilar.urls',namespace='blog')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And template code. What am I doing wrong?
{% load url from future %}
...
Read
Try to change this:
Read
to:
Read
Cause your view expect slug keyword here (?P<slug>[0-9A-Za-z._%+-]+).

Django Form Saving, but NOT Redirecting

Basis: I am trying to display a forms information with a new unique url as well as view upon submission. The form is currently saving to the database, but not redirection to the new url or view. Below I've posted both the views.py as well as the urls.py. If you need to see anything else please let me know.
Note: This is based off of a ModelForm and I am somewhat of a beginner to Django.
Thanks in advance!
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('',
url(r'^letter/testing/$', 'letter.views.letter'),
url(r'^letter/testing/(?P<pk>\d+)/$','letter.views.submission'),
# 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)),
)
views.py
# Create your views here.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from letter.forms import LetterForm
from letter.models import Letter
def submission(request, pk):
submission = get_object_or_404(Letter, pk=int(pk))
return render_to_response('post.html', {'submission':submission})
def letter(request):
if request.method == "POST":
letter = LetterForm(request.POST)
if letter.is_valid():
try:
new_letter = letter.save()
return HttpResponseRedirect('/letter/testing/%d/' % new_letter.pk)
except:
pass
else:
letter = LetterForm()
return render_to_response('letter.html',
{'letter':letter},
context_instance=RequestContext(request))
ANSWER:
Needed to remove the try/except parameters under if letter.is_valid()
Thank you #mattg!
Needed to remove the try and except parameters under if letter.is_valid()

Django - Why doesn't reverse work?

I'm trying to make a view redirect to another view so user's can't access it without a condition being met. In this case, a successful password change. I also want to achieve this using HttpResponseRedirect.
Now, I've never used reverse before, but I figured that this is the way to do that. Problem is that I can't get reverse to work. I get the following error:
ViewDoesNotExist at /account/password/
Could not import findadownload.main.views.foo. View does not exist in module findadownload.main.views.
# URLS
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
#SANDY
from findadownload.sandy.views import *
#TRIVIARIA
from findadownload.trivia.views import *
from findadownload.accounts.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'findadownload.main.views.presidium_home', name='presidium_home'),
(r'^web/$', 'findadownload.main.views.web'),
(r'^web/developers/$', sandy_developers),
#SANDY (for findadownload!)
(r'^get/sandy/$', get_sandy),
(r'^get/sandy/download/$', get_sandy_download),
(r'^sandy/register/$', sandy_registration),
(r'^sandy/complete/$', sandy_complete),
(r'^web/shared/$', sandy_shared_files),
(r'^web/remove/all/$', sandy_remove_all),
(r'^web/remove/(?P<file_id>\w+)/$', sandy_remove_file),
(r'^about/$', 'findadownload.main.views.about'),
(r'^pytech/$', 'findadownload.main.views.pytech'),
(r'^pytech/aboutus$', 'findadownload.main.views.pytech_about'),
(r'^pytech/services$', 'findadownload.main.views.pytech_services'),
(r'^pytech/support$', 'findadownload.main.views.pytech_support'),
(r'^pytech/contactus$', 'findadownload.main.views.pytech_contact'),
(r'^pytech/sitemap$', 'findadownload.main.views.pytech_sitemap'),
(r'^pytech/search/$', 'findadownload.main.views.pytech_search'),
(r'^presidium', 'findadownload.main.views.presidium_home'),
#TRIVIARIA
(r'^register/$', register),
(r'^login/$', login_view, {'template': 'trivia/registration/login.html'}),
(r'^logout/$', logout_view),
(r'^trivia/$', submit_question, {'template': 'trivia/trivia_questions.html'}),
(r'^challenges/$', submit_question, {'template': 'trivia/trivia_challenges.html'}),
(r'^question/thanks/$', question_thanks),
(r'^question/answer/$', submit_answer),
(r'^question/answer/result/(\d+)/(.*)/$', answer_result),
(r'^question/answer/challenge/$', challenge_answer),
(r'^account/$', upload_avatar),
(r'^account/password/$', password_change),
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success'),
(r'^(?P<username>\w+)/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/trivia/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/challenges/$', view_user_profile, {'template': 'trivia/trivia_view_user_challenges.html'}),
#FILE SHARING
(r'^web/share/(?P<file_id>\w+)/$', sandy_download),
(r'^web/report/(?P<file_id>\w+)/$', sandy_file_report),
(r'^web/like/(?P<file_id>\w+)/$', like_download),
#OTHER
(r'^web/profile/$', 'findadownload.main.views.web_profile'),
(r'^web/edit/$', 'findadownload.main.views.web_edit'),
(r'^trivia/$', 'findadownload.main.views.trivia_home', {'template': 'trivia/registration/index.html'}),
(r'^web/get/$', 'findadownload.main.views.web_get'),
(r'^web/progress/$', 'findadownload.main.views.web_progress'),
(r'^web/foo/$', 'findadownload.main.views.foo'),
(r'^web/search/$', 'findadownload.main.views.web_search'),
(r'^web/logout/$', 'findadownload.main.views.web_logout'),
(r'^web/resend/$', 'findadownload.main.views.web_resend'),
(r'^web/home/$', 'findadownload.main.views.web_home'),
(r'^web/history/$', 'findadownload.main.views.web_history'),
(r'^web/verify/(?P<link>\w+)/$', 'findadownload.main.views.web_activate'),
(r'^web/help/(?P<username>\w+)/$', 'findadownload.main.views.web_help'),
(r'^web/welcome/(?P<username>\w+)/$', 'findadownload.main.views.welcome'),
(r'^web/terms/$', 'findadownload.main.views.web_terms'),
(r'^web/privacy/$', 'findadownload.main.views.web_privacy'),
(r'^web/signup/$', 'findadownload.main.views.web_signup'),
(r'^web/login/$', 'findadownload.main.views.web_login'),
(r'^test$', 'findadownload.main.views.test'),
# url(r'^findadownload/', include('findadownload.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)),
)
if 1:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
'show_indexes': True,
}),
)
urlpatterns += staticfiles_urlpatterns()
# VIEWS
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from findadownload.accounts.forms import *
from django.contrib.auth.models import User
from django.contrib import auth
from findadownload.accounts.models import *
from django.core.urlresolvers import reverse
from findadownload.trivia.models import *
def password_success(request):
return render_to_response('trivia/trivia_password_success.html')
def password_change(request):
if request.user.is_authenticated():
# if for is submitted
if request.method == 'POST':
form = PasswordForm(user=request.user, data=request.POST)
# for the avatar part
if form.is_valid():
cd = form.cleaned_data
request.user.set_password(cd['confirm_password'])
request.user.save()`enter code here`
# redirect to profile page after POST
return HttpResponseRedirect(reverse('findadownload.accounts.views.password_success'))
else:
form = PasswordForm(user=request.user)
# render empty form
return render_to_response('trivia/trivia_password_change.html', {'form': form},
context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
You have to specify name kwargs in you url, in this case :
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success', name = 'password_success')
Then use reverse like this :
return HttpResponseRedirect(reverse('password_success'))
What you pass in reverse is the name kwarg on urlpatterns.
EDIT:
Can i see the rest of your urls.py. I think the problem is not on reverse, because Django can't find view named foo.

The included urlconf manager.urls doesn't have any patterns in it

A solution: Found the following django snippet that seems to work fine
(http://djangosnippets.org/snippets/2445/)
from django.utils.functional import lazy
from django.core.urlresolvers import reverse
#Workaround for using reverse with success_url in class based generic views
#because direct usage of it throws an exception.
reverse_lazy = lambda name=None, *args : lazy(reverse, str)(name, args=args)
Apparently, there is now a reverse_lazy function in django trunk.
Update: This error has something to do with me making a call to reverse inside a generic view:
class AddObjView(CreateView):
form_class = ObjForm
template_name = 'manager/obj_add.html'
success_url = reverse('manager-personal_objs')
Is this not valid?
If I instead of generic write something like this, it works:
def add_obj(request, pk):
a=reverse('manager-personal-objs')
return HttpResponse(a)
I have a project with 2 apps in it. Each app has its urls and views. They both work fine, but on the manager app, as soon as I reference the reverse function in the views(any view), I get the following error:
Exception Type: ImproperlyConfigured
Exception Value: The included urlconf manager.urls doesn't have any patterns in it
The urls file:
urlpatterns = patterns('',
url(r'^$', ObjView.as_view(), name='manager-obj'),
url(r'^add/$', AddObjView.as_view(), name='manager-add_obj'),
url(r'^personal/$', PersonalObjsView.as_view(), name='manager-personal_objs'),
)
Exception Location: ...site-packages\django\core\urlresolvers.py in _get_url_patterns, line 283
I get this error in the entire site(edit: this apparently happens because an attempt to import the manager.urls will result in the error). If I remove the include manager.urls, everything goes back to work; if I remove the call to reverse, everything is fine; if I try to rewrite manager.urls to a simpler version, it continues with the error.
I've been over this many times, can't seem to find anything wrong.
edit:root urls.py
# coding=utf8
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# 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)),
# Home Page
url(r'^$', direct_to_template, {'template': 'home.html'}, name="home"),
# manager
url(r'^manager/', include('manager.urls')),
# writing
url(r'^writing/', include('writing.urls')),
)
urlpatterns += staticfiles_urlpatterns()
edit2: Should also be noted that the url template tag works fine in the manager app and the reverse call works if I do it on the other app.
Also, every url has a written working view.
The problem is that your URLConf hasn't finished loading before your class based view attempts to reverse the URL (AddObjView.success_url). You have two options if you want to continue using reverse in your class based views:
a) You can create a get_success_url() method to your class and do the reverse from there
class AddObjView(CreateView):
form_class = ObjForm
template_name = 'manager/obj_add.html'
def get_success_url():
return reverse('manager-personal_objs')
b) If you are running on the trunk/dev version of Django, then you can use reverse_lazy https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
from django.core.urlresolvers import reverse_lazy
class AddObjView(CreateView):
form_class = ObjForm
template_name = 'manager/obj_add.html'
success_url = reverse_lazy('manager-personal_objs')
Option "b" is the preferred method of doing this in future versions of Django.