Related
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'),
]
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
]
I'm trying to use the "register" endpoint from Djoser. It works properly, but I need more fields than just "username", "email" and "password".
I've seen this question and indeed I can see the fields I wanted (in the browsable API). But when I try to post it, I get this error
ImproperlyConfigured at /account/register/ Could not resolve URL
for hyperlinked relationship using view name "user-detail". You may
have failed to include the related model in your API, or incorrectly
configured the lookup_field attribute on this field.
And I don't have idea what's going wrong.
My models.py looks so:
from django.db import models
class User(models.Model):
created = models.DateTimeField(auto_now_add=True)
email = models.CharField(max_length=100, blank=False)
name = models.CharField(max_length=100, blank=False)
last_name = models.CharField(max_length=100, blank=False)
birthday = models.CharField(max_length=15, blank=False)
password = models.CharField(max_length=100, blank=False)
class Meta:
ordering = ('created',)
the serializers.py
from rest_framework import serializers
from users.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'id', 'email', 'name', 'last_name', 'birthday', 'password')
my views.py
from users.models import User
from users.serializers import UserSerializer
from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
and in the settings.py I added:
DJOSER = {
...
'SERIALIZERS': {
'user_registration': 'users.serializers.UserSerializer',
},
}
EDIT
App/urls.py
from django.conf.urls import url, include
from users import views
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'users', views.UserViewSet)
schema_view = get_schema_view(title='Pastebin API')
# The API URLs are now determined automatically by the router.
# Additionally, we include the login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url('^schema/$', schema_view),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
api/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework_jwt import views as jwt_views
from rest_framework import routers
router = routers.DefaultRouter()
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^account/', include('djoser.urls')),
url(r'^auth/login/', jwt_views.obtain_jwt_token, name='auth'),
]
Does someone have an idea?
You can create a Custom User in django 2.0 using djoser by inheriting with AbstractUser, which creates a new user model with respect to your app like this:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
FUNCTION = 1
VIEWER = 2
TECHNICIAN = 3
ROLE_CHOICES = (
(FUNCTION, 'Functional'),
(VIEWER, 'Viewer'),
(TECHNICIAN, 'Technician'),
)
role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)
REQUIRED_FIELDS = ["email", "role"]
and then defined user new User class in settings.py:
AUTH_USER_MODEL = 'app_name.User'
Please note that here I have defined my REQUIRED_FIELDS. So when I use the djoser API /me/, it will give me all the required fields.
The exception is clear: Django cannot resolve URL by user-detail name. It tries to do so because you've made an extended serializer from serializers.HyperlinkedModelSerializer with a url field, which should contain a link to your specific user object.
The problem I see is that your main urls.py does not include api urls, and they all duplicated and wired up kinda strange. I would rewrite it as follows (assuming you also have user app):
Root urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.schemas import get_schema_view
from rest_framework_jwt import views as jwt_views
schema_view = get_schema_view(title='Pastebin API')
urlpatterns = [
url('^schema/$', schema_view),
url(r'^admin/', admin.site.urls),
url(r'^user/', include('user.urls')),
url(r'^account/', include('djoser.urls')),
# Not sure if you need both:
url(r'^auth/login/', jwt_views.obtain_jwt_token, name='auth'),
url(
r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
]
User app urls.py:
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from .views import UserViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
And I'm not sure why you need another app called api though.
If it doesn't help, try examining this article on namespacing the router.
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')),
)
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!