I'm using Django 3.0.8 I'm getting an error in path('post/new/',PostCreateView.as_view(),name='post-create') in blog/urls.py(blog is an app under my django_project). I've a class named PostCreateView in blog/views.py but it throws NameError:name 'PostCreateView' is not defined.
My blog/views.py is here:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView
from .models import Post
# Create your views here.
def home(request):
context={
'posts':Post.objects.all()
}
return render(request,'blog\home.html',context)
class PostListView(ListView):
model = Post
template_name='blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name='posts'
ordering=['-date_posted']
class PostDetailView(DetailView):
model = Post
class PostCreatelView(CreateView):
model = Post
fields=['title','content']
def about(request):
return render(request,'blog\about.html',{'title':'About'})
and blog/urls.py is here:
from django.urls import path
from .views import PostListView, PostDetailView, PostCreatelView
from . import views
urlpatterns = [
path('',PostListView.as_view(),name='blog-home'),
path('post/<int:pk>',PostDetailView.as_view(),name='post-detail'),
path('post/new/',PostCreateView.as_view(),name='post-create'),
path('about/',views.about,name='blog-about'),
]
What is wrong with this code?
Thanks in advance.
You have declared PostCreatelView (with an "l") not PostCreateView.
Related
I am following a yt tutorial on django(https://www.youtube.com/watch?v=sm1mokevMWk)
where the tutor searches http://127.0.0.1:8000/admin and gets the required interface
(It starts around 49:00)
everytime i search http://127.0.0.1:8000/admin
i get a
DoesNotExist at /admin
but when i search http://127.0.0.1:8000/admin/login/?next=/admin/nw/
i get the required interface
A question exactly same as mine has been asked before but the thing is i did not make the same error as that person did
this is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import ToDoList,Items
def index(response,name):
ls=ToDoList.objects.get(name=name)
item=ls.items_set.get(id=1)
return HttpResponse("<h1>%s</h1><br></br><p>%s</p>"%(ls.name,str(item.text)))
# Create your views here.
this is my urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("main.url")),
]
this is my models.py
from django.db import models
class ToDoList(models.Model):
name=models.CharField(max_length=200)
def __str__(self):
return self.name
class Items(models.Model):
todolist=models.ForeignKey(ToDoList,on_delete=models.CASCADE)
text=models.CharField(max_length=300)
complete=models.BooleanField()
def __str__(self):
return self.text
I shouldnt have added the '/ ' in /admin which is inside the urls.py file
This is the url i am trying:
http://localhost:8000/blog/categoria/1/
The foreign key is categoria_id that comes from relationship many to many of Post and Categoria.
I am using Sqlite3.
This file is the models.py
from django.db import models
from django.contrib.auth.models import User
class Categoria(models.Model):
nombre=models.CharField(max_length=50)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name='categoria'
verbose_name_plural='categorias'
def __str__(self):
return self.nombre
class Post(models.Model):
titulo=models.CharField(max_length=50)
contenido=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='blog', null=True, blank=True)
autor=models.ForeignKey(User, on_delete=models.CASCADE)
categorias=models.ManyToManyField(Categoria)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name='post'
verbose_name_plural='posts'
def __str__(self):
return self.titulo
This file is the views.py:
from django.shortcuts import render
from blog.models import Post, Categoria
def blog(request):
posts=Post.objects.all()
return render(request, "blog/blog.html",{"posts":posts})
def categoria(request, categoria_id):
categoria=Categoria.objects.get(id=categoria_id)
posts=Post.objects.filter(categorias=categoria)
return render(request, "blog/categoria.html",{'categoria': categoria, "posts":posts })
This file is the urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.blog, name='Blog'),
path('categoria/<int:categoria_id>/', views.categoria, name="categoria")
]
I change the database to postgresql and I added a / before categoria in the file urls.py. For now it works. It’s strange, because I’ve made these changes before and it didn't work.
Despite this I would appreciate any suggestion. Thank you.
This file is the urls.py after the change:
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.blog, name='Blog'),
path('/categoria/<int:categoria_id>/', views.categoria, name='categoria'),
]
So I get AttributeError at /api/test
type object 'Product' has no attribute 'objects' error when I try to load up the page via get request, I'm trying to make an API using django rest framework and it says Product has no objects attribute.
views.py
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import ProductSerializer
from .models import Product
from rest_framework.views import APIView
from rest_framework.response import Response
class Product(APIView):
def get(self, request, format=None):
products = Product.objects.all()
serializer = ProductSerializer(products)
return Response(serializer)
urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views
# router = routers.DefaultRouter()
# router.register('products', views.ProductViewSet)
# router.register('test', views.Product)
# urlpatterns = router.urls
urlpatterns = [
path('test', views.Product.as_view())
]
serializers.py
class ProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Product
fields = ['name','price','description']
change the name of view, ProductView because its overriding Product model thats why you are getting this error
Well, this question has been asked by many users, and I have tried some of the resolution provided in the query, but that doesn't seem to resolve my issue, maybe I am doing some other mistake.
I am trying to create a simple user registration/login/logout forms
SchoolnSkill ---Project name, and below is the SchoolnSkill/url details:-
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user_info/', include('user_info.urls')),
]
user_info--App name, and the user_info/url details are below:-
from django.conf.urls import url
from . import views
urlpatterns = [
# url(r'^$', views.index, name='index'),
url(r'^registration/', views.UserFormView, name='registration')
]
My views.py output is as below:-
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth import authenticate, login
from django.views import generic
from .models import Registration
from django.views import View
from .forms import UserForm
class UserFormView(View):
#from_class = UserForm
template_name = 'user_info/registration_form.html'
#dispaly blank form, new user coming to the website
def get(self, request):
form = self.UserForm(None)
return render(request, self.template_name, {'form':form})
def post(self, request):
form = self.UserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
form.py content as below:
from django.contrib.auth.models import User
from django import forms
from django.forms import ModelForm
class UserForm(forms.ModelForm):
password = forms.CharField(widget =forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
I am using below versions:
Python 3.6
Django 1.11.3
Spyder IDE
I am pretty sure that am doing something silly.
Please help.
below is the error message:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/user_info/
Using the URLconf defined in SchoolnSkill.urls, Django tried these URL patterns, in this order:
^admin/
^user_info/ ^registration/ [name='registration']
The current path, user_info/, didn't match any of these.
as you are using class based view you need to add as_view in the url
so
change this in user_info url to
urlpatterns = [
url(r'^registration/', views.UserFormView.as_view(), name='registration')
]
I use django rest framework and have this error:
base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .model or .queryset attribute.
This is my code
urls.py
from django.conf.urls import patterns, include, url
from rest_framework import viewsets, routers
import views
router = routers.SimpleRouter()
router.register(r'book', views.BookViewSet.as_view())
views.py
from django.shortcuts import render_to_response
from mobileapp.models import Book
from rest_framework import generics
from mobileapp.serializers import BookSerializer
class BookViewSet(generics.ListAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
serializers.py
from mobileapp.models import Book
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'url', 'date', 'comment')
Have you google'd error statement?
https://github.com/tomchristie/django-rest-framework/issues/933
http://django-rest-framework.org/api-guide/routers.html#usage
I'v solved my problem. There is code.
urls.py
from django.conf.urls import patterns, include, url
from views import BookList, BookDetail
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^book/$', BookList.as_view(), name='book-list'),
url(r'^book/(?P<pk>\d+)/$', BookDetail.as_view(), name='book-detail'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
views.py
class BookList(generics.ListCreateAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
model = Book
serializer_class = BookSerializer