Maximum recursion depth exceeded - Django, Python3 - django

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

Related

Dynamic reverse URL name supplied from model Django

I'm trying to reverse(just the way reverse_lazy works) the url_name stored in the SubMenu.link
Here is my code
My Model
class SubMenu(models.Model):
menu = models.ForeignKey(MainMenu, on_delete=models.CASCADE, related_name="submenus")
title = models.CharField(max_length=50)
link = models.CharField(max_length=50, null=True, default="null")
def __str__(self):
return self.title
My root urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('bodys.urls')),
path('blog', include('blogs.urls')),
path('contact', include('contacts.urls')),
path('services/', include('services.urls')),
]

include() got an unexpected keyword argument 'app_name'

i am making a blog application for my website with django-2.0
when i run server i see the following error
File "C:\Users\User\Desktop\djite\djite\djite\urls.py", line 7, in <module>
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
TypeError: include() got an unexpected keyword argument 'app_name'
here is my main urls.py
from django.contrib import admin
from django.conf.urls import url,include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
and here's my blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>d{2})/(?P<post>
[-/w]+)/$', views.post_detail, name='post_detail'),
]
my views.py:
from django.shortcuts import render, HttpResponse, get_object_or_404
from blog.models import Post
def post_list(request): #list
posts=Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
def post_detail(request, year, month, day, post):
post =get_object_or_404(post, slog=post,
status='published',
publush__year=year,
publish__month=month,
publish__day=day)
return render (request, 'blog/post/detail.html', {'post':post})
models.py:
# -*- coding:utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title =
models.CharField(max_length=255,verbose_name=_('title'),help_text=_('add
title'))
content = models.TextField(verbose_name=_('content'),help_text=_('write
here'))
publish = models.DateTimeField(default=timezone.now)
createtime = models.DateTimeField(_('create time'),auto_now_add=True,
auto_now=False,help_text=_('create time'))
updatetime = models.DateTimeField(_('update time'),auto_now_add=False,
auto_now=True,help_text=_('update time'))
author = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('author'),
on_delete=models.DO_NOTHING,help_text=_('choose author'))
slug = models.SlugField(unique=True, max_length=255,help_text=_('add
slug'))
status = models.CharField(max_length=10, choices=STATUS_CHOICES,
default='draft')
def __unicode__(self):
return self.title
def __str__(self):
return self.title
class Meta:
ordering = ('-publish',)
verbose_name = _('Post')
verbose_name_plural = _('Posts')
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
also my views.py has a problem that i don't think that's related to my current error, when i delete
namespace='blog', app_name='blog'
from this line in main urls.py
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
the server runs but when i go to this directory:
http://localhost:8000/blog/
i see this error
AttributeError at /blog/
type object 'Post' has no attribute 'published'
it says that this line of code has problem in views.py
posts=Post.published.all()
Using app_name with include is deprecated in Django 1.9 and does not work in Django 2.0. Set app_name in blog/urls.py instead.
app_name = 'blog'
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
...
]
Then change the include to:
url(r'^blog/', include('blog.urls')),
You don't need namespace='blog', as it will default to the application namespace anyway.
The second error is unrelated. You have forgotten to instantiate your custom manager on the model.
class Post(models.Model):
...
published = PublishedManager()
In Django 2.0 app_name, will not support :
Use of project URLs:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path(r'blog/', include('blog.urls')),//use this
]

Zinnia rewriting urls does doesn't work

I'm trying to customize the url of entries in zinnia to show slugs of entries only, ie .../blog/slug.
I've been following closely the documentation here - I've overwritten the get_absolute_url method, I've added the view and configured the urls and registered the _base model in django settings - yet the error persists:
zinnia_customized models.py:
from django.db import models
from zinnia.models_bases.entry import AbstractEntry
class EntryWithNewUrl(AbstractEntry):
"""Entry with '/blog/<id>/' URL"""
#models.permalink
def get_absolute_url(self):
return ('zinnia:entry_detail', (),
{'slug': self.slug})
class Meta(AbstractEntry.Meta):
abstract = True
zinnia_customized views.py:
from django.views.generic.detail import DetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.entry_preview import EntryPreviewMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
class EntryDetail(EntryPreviewMixin, EntryProtectionMixin, DetailView):
queryset = Entry.published.on_site()
template_name_field = 'template'
project urls.py:
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
url(r'^admin/tools/', include('admin_tools.urls')),
url(settings.ADMIN_URL, include(admin.site.urls)),
url(r'^users/', include('anpene.users.urls', namespace='users')),
url(r'^accounts/', include('allauth.urls')),
url(r'^blog/', include('zinnia_customized.urls', namespace='zinnia')),
url(r'^comments/', include('django_comments.urls')),
]
zinnia_customized urls.py:
blog_urls = [
url(r'^', include('zinnia.urls.capabilities')),
url(r'^search/', include('zinnia.urls.search')),
url(r'^sitemap/', include('zinnia.urls.sitemap')),
url(r'^trackback/', include('zinnia.urls.trackback')),
url(r'^blog/tags/', include('zinnia.urls.tags')),
url(r'^blog/feeds/', include('zinnia.urls.feeds')),
url(r'^blog/authors/', include('zinnia.urls.authors')),
url(r'^blog/categories/', include('zinnia.urls.categories')),
# url(r'^blog/', include('zinnia.urls.entries')),
url(r'^blog/', include('zinnia_customized.urls.entries')),
url(r'^blog/', include('zinnia.urls.archives')),
url(r'^blog/', include('zinnia.urls.shortlink')),
url(r'^blog/', include('zinnia.urls.quick_entry')),
]
urlpatterns += patterns('',
url(r'^', include(blog_urls), name='blog')
)
zinnia_customized app urls/entries.py:
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia_customized.views import EntryDetail
urlpatterns = [
url(r'^(?P<slug>[\w-]+)/$', EntryDetail.as_view(), name='entry_detail'),
]
zinnia_customized admin.py:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from zinnia.models.entry import Entry
from zinnia.admin.entry import EntryAdmin
class EntryUrlAdmin(EntryAdmin):
"""blank"""
admin.site.register(Entry, EntryUrlAdmin)
settings:
...
ZINNIA_ENTRY_BASE_MODEL = 'zinnia_customized.models.EntryWithNewUrl'
...
And the error:
NoReverseMatch at /blog/
Reverse for 'entry_detail' with arguments '()' and keyword arguments '{'slug': u'pies'}' not found. 1 pattern(s) tried: [u'blog/(?P<year>\\d{4})/(?P<month>\\d{2})/(?P<day>\\d{2})/(?P<slug>[-\\w]+)/$']
My problem was that I've created a folder called urls in my zinnia_customized, therefore django wasn't sure if it was supposed to use the folder or urls.py

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

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

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!