I am importing my views:
from .views import HomeView, EntryView
and the error I'm getting is:
ImportError: cannot import name 'EntryView' from 'entries.views' (.
C:\Users\Kheri\dev\cfehome\blog\entries\views.py) */
Below I'm providing my files:
views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Entry
class HomeView(ListView):
model = Entry
template_name = 'entries/index.html'
context_object_name = "blog_entries"
class EntryView(DetailView):
model = Entry
template_name = 'entries/entry_detail.html'
urls.py:
from django.urls import path
from .views import HomeView, EntryView
urlpatterns = [
path('', HomeView.as_view(), name = 'blog-home'),
path('entry/<int:pk>/', EntryView.as_view(), name = 'entry-detail')
]
Try correcting the indentation of views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Entry
class HomeView(ListView):
model = Entry
template_name = 'entries/index.html'
context_object_name = "blog_entries"
class EntryView(DetailView):
model = Entry
template_name = 'entries/entry_detail.html'
Got this error also, saw that I had a spelling error in urls.py
In my urlpatterns
I had path ('', AtricleListView.as_view(), name='article-list'),
instead of path ('', ArticleListView.as_view(), name='article-list'),
also in the import AtricleListView I had to change it to ArticleListView
from this
from .views import (
AtricleListView
)
to this
from .views import (
ArticleListView
)
My error looked like this
ImportError: cannot import name 'AtricleListView' from 'blog.views'
Here you can see that I tried to import "AtricleListView" instead of the real name that was "AtricleListView"
Related
where can I import the detail attribute from?
views.py:
from django.shortcuts import render
from django.views import generic
from . import models
class Index(generic.TemplateView):
template_name='catalog/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['num_books'] = models.Book.objects.all().count()
context['num_instances'] = models.BookInstance.objects.all().count()
context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
context['num_authors'] = models.Author.objects.count()
return context
class BookListView(generic.ListView):
model = models.Book
template_name = 'catalog/book_list.html'
class BookDetialView(generic.Detail.View):
model= models.Book
template_name = 'catalog/book_detail.html'
urls.py
from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView
app_name='catalog'
urlpatterns = [
path(r'', views.Index.as_view(), name='index'),
re_path(r'^$', views.Index.as_view(), name='index')
]
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'^books/$', views.BookListView.as_view(), name='books'),
path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]
but the result:
class BookDetialView(generic.Detail.View):
AttributeError: module 'django.views.generic' has no attribute 'Detail'
Should be generic.DetailViewinstead of generic.Detail.View
In your BookDetailView you used generic.Detail.View instead of DetailView[Djano-doc].
Change your BookDetailView as
from django.views import generic
class BookDetialView(generic.DetailView): #<--- change here
model= models.Book
template_name = 'catalog/book_detail.html'
You have a couple of issues here.
(1) In your views you spell your view name as BookDetialView and in your url definition you spell it BookDetailView.
(2) I believe the correct inheritance is generic.DetailView instead of generic.Detail.View
In my app I want a user to upload an image and the image's file name will become same as the title of the form.
For example,
user uploads image xyz.jpg, while `title = newfile. After that the image will now be newfile.jpg.
This is my code below:
#forms
class PostForm(forms.modelForm):
class Meta:
model = Post
fields = ['title', 'cover']
#urls
from django.urls import path
from .views import HomePageView, CreatePostView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('post/', CreatePostView.as_view(), name='add_post')
]
#views
from django.shortcuts import render
from django.views.generic import ListView, CreateView
from django.urls import reverse_lazy
from .forms import PostForm
from .models import Post
class HomePageView(ListView):
model = Post
template_name = 'home.html'
class CreatePostView(CreateView): # new
model = Post
form_class = PostForm
template_name = 'post.html'
success_url = reverse_lazy('home')
I am using django 2.2.2 . I am trying to include path('api/', include('music.urls')),into my root url but I get an exception thrown from resolvers.py file.
Here is my music/urls.py
urls.py
from django.urls import path
from . import views
app_name = 'music'
urlpatterns = [
path('songs/', ListSongsView.as_view(), name = 'songs-all'),
]
here is my root url file
urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('music.urls')),
]
views.py
from django.shortcuts import render
from rest_framework import generics
from .models import Songs
from serializers import SongSerializer
# Create your views here.
class ListSongsView(generics.ListApiView):
queryset = Songs.objects.all()
serializer_class = SongsSerializer
models.py
from django.db import models
# Create your models here.
class Songs(models.Model):
title = models.CharField(max_length=255, null = False)
artist = models.CharField(max_length=50, null= False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
and my stacktrace
File "/home/brianonchari/Documents/django/drf/myapi/lib/python3.5/site-
packages/django/urls/resolvers.py", line 588, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'rest.urls' does not
appear to have any patterns in it. If you see valid patterns in the file then the issue is
probably caused by a circular import.
music/urls.py
from django.urls import path
from .views import ListSongsView
app_name = 'music'
urlpatterns = [
path('songs/', ListSongsView.as_view(), name='songs-all'),
]
root urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('music.urls')),
]
music/views.py:
from django.shortcuts import render
from rest_framework import generics
from .models import Songs
from .serializers import SongSerializer
# Create your views here.
class ListSongsView(generics.ListAPIView):
queryset = Songs.objects.all()
serializer_class = SongSerializer
music/models.py:
from django.db import models
# Create your models here.
class Songs(models.Model):
title = models.CharField(max_length=255, null=False)
artist = models.CharField(max_length=50, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
music/serializers.py:
from rest_framework import serializers
from .models import Songs
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Songs
fields = ('title', 'artist')
run your migration for Songs model:
python manage.py makemigrations
python manage.py migrate
I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
I've been trying for days now to use get_absolute_url and whenever I click on the view on site button in the admin page or click submit on my add form page, I get this error:
NoReverseMatch at /admin/r/14/3/ (or NoReverseMatch at /blogs/add/)
Reverse for 'blog_detail' with arguments '()' and keyword arguments '{'pk': 3}' not found. 0 pattern(s) tried: []
If I go to mysite/blog/3 I do get the blog details page just fine as I have it set up. So I know the page works, but it seems like its not trying to find it since it says zero patterns tried.
Docs I'm looking at are:
https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-editing/
https://docs.djangoproject.com/en/1.7/ref/models/instances/#get-absolute-url
My code (what I think is relevant at least. If more info is needed let me know please)
blogs.models.py
from django.contrib.auth.models import User
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from audit_log.models.fields import CreatingUserField, CreatingSessionKeyField
class Blog(models.Model):
created_by = CreatingUserField(related_name = "created_categories")
created_with_session_key = CreatingSessionKeyField()
created_time = models.DateTimeField(auto_now_add=True)
blog_title = models.CharField('Blog Title', max_length=200)
short_description = models.TextField('Short Description', max_length=140)
blog_image = models.CharField('Image', max_length=200)
youtube_link = models.URLField('YouTube', max_length=200)
external_site_link = models.URLField('Website', max_length=200)
full_blog = models.TextField(max_length=10000)
def get_absolute_url(self):
return reverse('blog_detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.blog_name
urls.py
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^blogs/', include('blogs.urls', namespace='blogs')),
)
blogs.urls.py
from django.conf.urls import patterns, url
from blogs import views
urlpatterns = patterns('',
url(
regex=r'^$',
view=views.BlogListView.as_view(),
name='blog_list'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogDetailView.as_view(),
name='blog_detail'
),
url(
regex=r'^add/$',
view=views.BlogCreate.as_view(),
name='blog_add'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogUpdate.as_view(),
name='blog_update'
),
url(
regex=r'^(?P<pk>\d+)/delete/$',
view=views.BlogDelete.as_view(),
name='blog_delete'
),
)
blogs.views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
# Only authenticated users can access views using this.
from braces.views import LoginRequiredMixin
from .models import Blog
class BlogDetailView(DetailView):
model = Blog
class BlogListView(ListView):
model = Blog
class BlogCreate(LoginRequiredMixin, CreateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogUpdate(LoginRequiredMixin, UpdateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogDelete(LoginRequiredMixin, DeleteView):
model = Blog
success_url = reverse_lazy('blog_list')
you need to address url with namespace blogs like this:
return reverse('blogs:blog_detail', kwargs={'pk': self.pk})