Exception Value: blog() takes exactly 2 arguments (1 given) - django

I've been struggling with setting up views / urls in Django for a couple of days. Struggling to get my head around it everyone seems to do it slightly differently.
What i want to achieve is:
I want to have a blog where i can post news posts on the site that will be located at example - mysite.com/blog/ then you can click through to view the posts individually it pulls the slug through from each post. (which pretty much works).
However I want to pull the posts from the blog app so the homepage. So you can view a snippet of the latest posts. I now understand that I need to create a view and a URL outside of the app folder and in the main directory. However i'm struggling to get them to link together. I am currently getting the error message displayed above. 'No Blog matches the given query.' Here is my code for the URL's, Models and the 2 different view folders.
//URLS for app and main directory
import authority
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import url, include, patterns
from django.contrib import admin
admin.autodiscover()
authority.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^authority/', include('authority.urls')),
(r'^i18n/', include('django.conf.urls.i18n')),
(r'^admin/', include(admin.site.urls)),
url(r'^$', 'views.blog', name='index'),
url(r'^blog/(?P<slug>[-\w]+)/$', 'blog.views.blog', name="blog"),
url(r'^blog/$', 'blog.views.blog_index', name="blog_index"),
)
if settings.DEBUG:
urlpatterns += patterns('',
# Trick for Django to support static files (security hole: only for Dev environement! remove this on Prod!!!)
url(r'^admin/pages/page(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.PAGES_MEDIA_ROOT}),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^admin_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.ADMIN_MEDIA_ROOT}),
)
urlpatterns += patterns('',
(r'^', include('pages.urls')),
)
//MAIN VIEW FOR HOMEPAGE
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from blog.models import Blog, NewsPost
def blog_index(request):
blogs = Blog.objects.filter(active=True)
return render_to_response('index.html', {
'blogs':blogs,
}, context_instance=RequestContext(request))
//VIEWS FOR BLOG APP
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from blog.models import Blog, NewsPost
def blog_index(request):
blogs = Blog.objects.filter(active=True)
return render_to_response('blog/index.html', {
'blogs':blogs,
}, context_instance=RequestContext(request))
def blog(request, slug):
blog = get_object_or_404(Blog, active=True, slug=slug)
return render_to_response('blog/blog_post.html', {
'blog': blog
}, context_instance=RequestContext(request))
//MODELS FROM THE BLOG APP
from django.contrib.auth.models import User
class TimeStampedActivate(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=False, help_text="Controls
whether or now this news post is live")
class Meta:
abstract = True
class Blog(TimeStampedActivate):
title = models.CharField(max_length=255, help_text="Can be
anything up to 255 character")
slug = models.SlugField()
description = models.TextField(blank=True, help_text="Give a short
description of the news post")
content = models.TextField(blank=True, help_text="This is the main
content for the news post")
user = models.ForeignKey(User, related_name="blog")
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self):
return ('blog', (), {
'slug': self.slug
})
class NewsPost(TimeStampedActivate):
title = models.CharField(max_length=255, help_text="title of the post")
slug = models.SlugField()
description = models.TextField(blank=True, help_text="Give a short
description of the news post")
content = models.TextField(blank=True, help_text="This is the main
content for the news post")
publish_at = models.DateTimeField(default=datetime.datetime.now(),
help_text="Choose when the post is visible")
blog = models.ForeignKey(Blog, related_name="posts")
def __unicode__(self):
return self.title
class Meta:
ordering = ['-publish_at', '-modified', '-created']
If you need anymore information feel free to ask! I'm new to all this so go easy! :) Thanks in advance!

Change
url(r'$', blog),
To
url(r'$', 'views.blog_index', name='index'),
Or write a separate view.
The reason you're getting your error, is because you're attempting to execute the blog function which expects a slug from your title page. What you're wanting to do is show the index from your title page which does not take a slug.
Also, the following is going to cause you pain:
from blog.views import blog_index, blog
from views import blog_index
Which blog_index do you want to be using? You're better off using 'views.blog_index' notation in your URLs. Delete those imports above, and only use string based view names in your URLs like you've done for blog/ and blog_index/.
Edit: this is what your entire URLs should show (to get this working..)
import authority
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import url, include, patterns
from django.contrib import admin
admin.autodiscover()
authority.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^authority/', include('authority.urls')),
(r'^i18n/', include('django.conf.urls.i18n')),
(r'^admin/', include(admin.site.urls)),
url(r'^$', 'views.blog', name='index'),
url(r'^blog/(?P<slug>[-\w]+)/$', 'blog.views.blog', name="blog"),
url(r'^blog/$', 'blog.views.blog_index', name="blog_index"),
)
if settings.DEBUG:
urlpatterns += patterns('',
# Trick for Django to support static files (security hole: only for Dev environement! remove this on Prod!!!)
url(r'^admin/pages/page(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.PAGES_MEDIA_ROOT}),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^admin_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.ADMIN_MEDIA_ROOT}),
)
urlpatterns += patterns('',
(r'^', include('pages.urls')),
)

Related

Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order:

I've been going through the Tango With Django 1.7 guide and I've come up with the following issue that I'm having troubles fixing:
Using the URLconf defined in tango_with_django_project.urls, Django
tried these URL patterns, in this order:
1. ^$ [name='index']
2. ^about/$ [name='about']
3. ^category/(?P<category_name_slug>[\w\-]+)/$ [name='category']
4. ^admin/
5. ^rango/$
6. ^about/
7. ^category/
8. ^media/(?P<path>.*)
The current URL, rango/category/python, didn't match any of these.
This is my rango/urls.py file
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns(' ',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$',
views.category, name='category')
)
In tango_with_django_project/urls.py I have
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rango import views
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/$', include('rango.urls')),
url(r'^about/', include('rango.urls')),
)
if settings.DEBUG:
urlpatterns+= patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
)
In rango/views.py I have:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
def index(request):
category_list = Category.objects.order_by('-likes')[:5]
context_dict = {'categories': category_list}
return render(request, 'rango/index.html', context_dict)
def about(request):
return HttpResponse("Rango says: Hello world! <br/> <a
href='/rango/about'>About</a>")
def category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
return render(request, 'rango/category.html', context_dict)
I've been following the guide so I'm not quite sure what the problem is; I had a similar problem earlier on in the guide when I was getting the same error but with /about (never got this fixed).
Any idea what might be causing this problem? Any help is appreciated!
As already commented, the problem here is the definition of the URLconf, more precisely the inclusion of another URLconf that shall define every url that starts with rango/.... The crucial line is this one:
url(r'^rango/$', include('rango.urls')),
which should read instead
url(r'^rango/', include('rango.urls')),
The regex '^rango/$' captures: <start-of-string>rango/<end-of-string>
The regex '^rango/' captures: <start-of-string>rango/<whatever follows>, and that's where your included urls kick in.

Maximum recursion depth exceeded - Django, Python3

I am writing a blog application but I got stuck.
I'm facing the following error:
':'.join(parents + (url.namespace,)) for url in url_patterns RecursionError: maximum recursion depth exceeded
I got two urls.py files.
mysite/urls.py:
from django.conf.urls import url
from quickblog import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
]
mysite/myapp/urls.py:
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('quickblog.urls')),
]
mysite/myapp/models.py:
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
/mysite/myapp/admin.py:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
I guess I'm doing something wrong here. Any hint would be nice.
It seems you have swapped urls.py data
mysite/urls.py should be:
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('quickblog.urls')),
]
mysite/myapp/urls.py should be:
from django.conf.urls import url
from quickblog import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
]

Django. Confusion about redirections

Here is my simplified code:
project's urls:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^to_app1/', include('app1.urls')),
url(r'^to_app2/', include('app2.urls')),
)
app1's urls:
from django.conf.urls import *
from app1 import views
urlpatterns = patterns('',
url(r'^$', views.app1Page, name='app1-page'),
url(r'^action/', views.app1_to_app2, name='app1-to-app2-page'),
)
app2's urls:
from django.conf.urls import *
from app2 import views
urlpatterns = patterns('',
url(r'^$', views.app2Page, name='app2-page'),
)
app1's view:
def app1Page(request):
return render(request, 'app1/app1page.html')
def app1_to_app2(request):
# some actions going on here #
return HttpResponseRedirect('/to_app2/')
app2's view:
def app2Page(request):
return render(request, 'app2/app2page.html')
So, I have a button on app1page.html which should sends data through POST function to to_app1/action/ url. In the end it should redirect me to app2page.html, but it does not. It gives me GET 127.0.0.1:8000/to_app2/ HTTP/1.0 200 OK, but I staying on the same page (app1page.html).
There is obviously something I missing, could someone point out it to me?

Django does not match urls

I've been working on a django web app (using Django 1.3), a web catalogue of products, and it was working fine until I was asked to add a custom admin site. I'm fully aware of the Django admin site, but the client is very old-fashioned, and is tech-ignorant so I have to make a "for dummies" version admin site. The root urlconf:
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
from store.models import Category
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^^$', TemplateView.as_view(
template_name='homepage.html',
get_context_data=lambda: {
'crumb': 'home',
'category_list':Category.objects.all()
}
),
name='home'),
url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/img/favicon.ico'}),
url(r'^store/', include('store.urls', app_name='store', namespace='store')),
)
And the urlconf for the store app:
from django.conf import settings
from django.conf.urls.defaults import *
from store import views
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
)
and the original views:
from django.http import Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView
from store.models import Category, Brand, Product
def get_brands(request):
q = request.GET.get('q')
if q is not None:
category = get_object_or_404(Category, slug__iexact=q)
try:
brands = category.brands.all()
except:
brands = []
template = 'infobox.html'
data = {
'category': category,
'brands': brands,
}
return render( request, template, data )
class GalleryView(ListView):
context_object_name = 'product_list'
template_name = 'store/gallery.html'
def get_queryset(self):
self.category = get_object_or_404(Category, slug__iexact=self.args[0])
try:
brand = Brand.objects.get(slug__iexact = self.args[1])
self.brand_name = brand.name
except:
#no brand is specified, show products with no brand
if self.category.category_products.filter(brand__isnull=True):
#if there are products with no brand, return those
return self.category.category_products.filter(brand__isnull=True)
else:
#if all products have a brand, return the products of the first brand
all = self.category.brands.all()
if all:
brand = all[0]
self.brand_name = brand.name
return brand.brand_products.all()
else:
raise Http404
else:
#brand is specified, show its products
return Product.objects.filter(category=self.category, brand=brand)
def get_context_data(self, **kwargs):
context = super(GalleryView, self).get_context_data(**kwargs)
category = self.category
category_brands = self.category.brands.all()
context['category_list'] = Category.objects.all()
context['category'] = category
context['crumb'] = category.name
context['category_brands'] = category_brands
try:
context['brand'] = self.brand_name
except:
context['brand'] = None
return context
Now, my custom admin app was working fine on my local dev environment, but when I added the new urls and views to prod, Django doesn't seem to match any of the new urls. The original views and urls still work, but none of the new urls get matched and I just keep getting a 404 Not Found error.
The updated urlconf:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from store import views
admin_urls = patterns ('',
url(r'^$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
)
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^login/$', views.admin_login, name='login'),
url(r'^logout/$', views.admin_logout, name='logout'),
url(r'^logout/success/$', views.admin_logout_success, name='logout_success'),
url(r'^test/', views.test, name='test'),
url(r'^admin/', include(admin_urls, namespace='admin')),
url(r'^ajax/$', views.ajax_request, name='ajax_request'),
)
Note that not even the simple '/store/test/' url does not get matched. I'm not really sure why Django isn't matching my urls, and any help is appreciated.
I'm not exactly sure what was happening since all of my templates linked to other pages using the {% url %} tag, but I think the reason my urls were getting muddled up was because I was using the r'^(\w+)/$' regex, so it was matching any word. I simply moved the urlconfs with the (\w+) rule to the bottom of urls.py, and refactored them to be a little more specific and they were gold again.
The updated urlconf:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from store import views
admin_urls = patterns ('',
)
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^login/$', views.admin_login, name='login'),
url(r'^logout/$', views.admin_logout, name='logout'),
url(r'^logout/success/$', views.admin_logout_success, name='logout_success'),
url(r'^ajax/$', views.ajax_request, name='ajax_request'),
url(r'^administration/$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^administration/add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
)
As you mentioned in the comments, removing login_required fixes the problem. Here's what the django docs have to say about the decorator:
login_required() does the following:
If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example:
/accounts/login/?next=/polls/3/.
If the user is logged in, execute the view normally
[...] Note that if you don't specify the login_url parameter, you'll
need to map the appropriate Django view to settings.LOGIN_URL.
In other words, it goes to a default url you can override in settings.LOGIN_URL.
Now here's what I think happened - I think you defined your own login here:
url(r'^login/$', views.admin_login, name='login'),
And because the login_required in the new urls pointed at the default url, which doesn't exist it returned 404. However, when you configured the login_required views after your other urls:
url(r'^login/$', views.admin_login, name='login'),
...
url(r'^administration/$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^administration/add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
it worked. Why is that? You didn't overrid LOGIN_URL here right? But you sort of did - because at this point, you redefined the namespace 'login' to point to your own view. Now this isn't mentioned anywhere in the docs, but it makes sense, and looking at the default admin templates you can see this is the namespace being used.
Does that make sense to you?

Why does my dead simple Django app keep crashing python on my mac 10.6.4?

views.py
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import get_list_or_404
from django.template.context import RequestContext
from articles.models import Article
def index(request):
articles = get_list_or_404(Article)
return render_to_response(
'articles/index.html',
{"articles": articles},
context_instance=RequestContext(request),
mimetype="application/xhtml+xml")
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
return render_to_response(
'articles/article.html',
{"article": article},
context_instance=RequestContext(request),
mimetype="application/xhtml+xml")
models
from django.db import models
from django.contrib.auth.models import User
import datetime
class Article(models.Model):
"""
Article model
"""
title = models.CharField(blank=True, max_length=200)
slug = models.SlugField()
body = models.TextField(blank=True)
created = models.DateTimeField(blank=True, default=datetime.datetime.now)
author = models.ForeignKey(User)
def __unicode__(self):
return "%s" % (self.title)
#property
def handle(self):
return self.slug
urls
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(
r'^$',
'articles.views.index',
name="articles_index"
),
url(
r'^article/(?P<article_id>\d*)$',
'articles.views.article',
name="article_view",
),
)
root urls
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
from settings import PROJECT_ROOT
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
(r'^articles/', include('articles.urls')),
)
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': PROJECT_ROOT + "/media"}),
)
Would you need to see more?
I had a theory that the word 'Article' might have conflicted with something, tho I tried renaming that to no avail.
This is supposed to be just a little 'play app' that I'm learning on. But now I'm quite stuck.
Running: python manage.py runserver_plus
http://127.0.0.1:8000/admin (views work ok)
http://127.0.0.1:8000/articles (crashes python everytime)
Quite a hair pulling exercise... help very much appreciated
edit
the error report:
http://dpaste.org/8Fzx/
Thank you!
Answer: self referencing template!