I'm a beginner in python-django coding. Currently I am trying to complete the challenge on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication but I am facing
LoanedBooksByAllUserListView is missing the permission_required attribute. Define LoanedBooksByAllUserListView.permission_required, or override LoanedBooksByAllUserListView.get_permission_required().
In urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('books/', views.BookListView.as_view(), name='books'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
path('authors/', views.AuthorListView.as_view(), name='authors'),
path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'),
path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
path('borrowed/', views.LoanedBooksByAllUserListView.as_view(), name='all-borrowed'),
]
In views.py
from django.shortcuts import render
# Create your views here.
from .models import Book, Author, BookInstance, Genre
def index(request):
"""View function for home page of site."""
# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact='a').count()
# The 'all()' is implied by default.
num_authors = Author.objects.count()
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
'num_visits': num_visits,
}
# Render the HTML template index.html with the data in the context variable.
return render(request, 'index.html', context=context)
from django.views import generic
class BookListView(generic.ListView):
model = Book
paginate_by = 5
class BookDetailView(generic.DetailView):
model = Book
class AuthorListView(generic.ListView):
model = Author
paginate_by = 5
class AuthorDetailView(generic.DetailView):
model = Author
from django.contrib.auth.mixins import LoginRequiredMixin
class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
"""Generic class-based view listing books on loan to current user."""
model = BookInstance
template_name ='catalog/bookinstance_list_borrowed_user.html'
paginate_by = 10
def get_queryset(self):
return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
from django.contrib.auth.mixins import PermissionRequiredMixin
class LoanedBooksByAllUserListView(PermissionRequiredMixin,generic.ListView):
model = BookInstance
template_name ='catalog/allbookinstancelistborrowed.html'
paginate_by = 10
def get_queryset(self):
return BookInstance.objects.filter(status__exact='o').order_by('due_back')
Related
Models.py
from django.db import models
# Create your models here.
class reviewData(models.Model):
building_name = models.CharField(max_length=50)
review_content = models.TextField()
star_num = models.FloatField()
class buildingData(models.Model):
building_name = models.CharField(max_length=50)
building_loc = models.CharField(max_length=50)
building_call = models.CharField(max_length=20)
views.py
# Create your views here.
from django.shortcuts import render
from rest_framework.response import Response
from .models import reviewData
from .models import buildingData
from rest_framework.views import APIView
from .serializers import ReviewSerializer
class BuildingInfoAPI(APIView):
def get(request):
queryset = buildingData.objects.all()
serializer = ReviewSerializer(queryset, many=True)
return Response(serializer.data)
class ReviewListAPI(APIView):
def get(request):
queryset = reviewData.objects.all()
serializer = ReviewSerializer(queryset, many=True)
return Response(serializer.data)
urls.py
from django.contrib import admin
from django.urls import path
from crawling_data.views import ReviewListAPI
from crawling_data.views import BuildingInfoAPI
urlpatterns = [
path('admin/', admin.site.urls),
path('api/buildingdata/', BuildingInfoAPI.as_view()),
#path('api/buildingdata/(I want to put building name here)', ReviewListAPI.as_view())
]
I am making review api.
I want to use building name as url path to bring reviews for specific buildings
For example, there are a, b, c reviews
a, b reviews are for aaabuilding
c reviews are for xxxbuilding
api/buildingdata/aaabuilding (only shows aaabuilding review)
{
building_name = aaabuilding
review_content = a
star_num = 5
building_name = aaabuilding
review_content = b
star_num = 3
}
api/buildingdata/xxxbuilding (only shows xxxbuilding review)
{
building_name = xxxbuilding
review_content = c
star_num = 4
}
I've searched some dynamic url posts, but they were not that i want.
Is there any way to bring building name into url from db?
In urls.py
path('api/buildingdata/<str:building>/', BuildingInfoAPI.as_view()),
And in views.py
class BuildingInfoAPI(APIView):
def get(request, building):
queryset = buildingData.objects.filter(building_name__contains=building)
serializer = ReviewSerializer(queryset, many=True)
return Response(serializer.data)
Hope this will solve the issue
I suggets you take a look at the django documentation, this is pretty well explained there, here is a useful link
In your urls.py, you should put:
from django.contrib import admin
from django.urls import path
from crawling_data.views import ReviewListAPI
from crawling_data.views import BuildingInfoAPI
urlpatterns = [
path('admin/', admin.site.urls),
path('api/buildingdata/', BuildingInfoAPI.as_view()),
# added <str:building> to url
path('api/buildingdata/<str:building>', ReviewListAPI.as_view())
]
And in your views.py:
# Create your views here.
from django.shortcuts import render
from rest_framework.response import Response
from .models import reviewData
from .models import buildingData
from rest_framework.views import APIView
from .serializers import ReviewSerializer
class BuildingInfoAPI(APIView):
def get(request):
queryset = buildingData.objects.all()
serializer = ReviewSerializer(queryset, many=True)
return Response(serializer.data)
class ReviewListAPI(APIView):
# added another argument, retrieved from url
def get(request, building):
# changed .all() to .filter()
queryset = reviewData.objects.filter(building_name = building)
serializer = ReviewSerializer(queryset, many=True)
return Response(serializer.data)
i am building a blog in Django and where register user can write blog articles . I want to display posts that are associated with certain categories on one page. i tried to do that but it does not show the post associated to the article. here is my files
models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from datetime import datetime, date
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
def get_absolute_url(self):
# return reverse('article', args=(str(self.id)))
return reverse('home') # go to home page after article submission
class Post(models.Model):
title = models.CharField(max_length=255)
tags = models.CharField(max_length=255, default="Ryan's World")
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default="uncategorized")
def __str__(self):
return self.title+' | '+str(self.author)
def get_absolute_url(self):
# return reverse('article', args=(str(self.id)))
return reverse('home') # go to home page after article submission
views.py
created function based view
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category
from .forms import PostForm, EditForm
from django.urls import reverse_lazy
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-id']
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats ,'category_posts': category_posts })
. . .
urls.py
from django.urls import path
# from . import views
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView
urlpatterns = [
# path('', views.home , name='home'),
path('', HomeView.as_view(), name="home"),
path('article/<int:pk>', ArticleDetailView.as_view(), name="article"),
path('add_post/', AddPostView.as_view(), name='add_post'),
path('add_category/', AddCategoryView.as_view(), name='add_category'),
path('article/edit/<int:pk>', UpdatePostView.as_view(), name="updatearticle"),
path('article/<int:pk>/remove', DeletePostView.as_view(), name="deletearticle"),
path('category/<str:cats>/', CategoryView, name='category')
]
forms.py
from django import forms
from .models import Post, Category
choices = Category.objects.all().values_list('name','name')
choice_list = []
for item in choices:
choice_list.append(item)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'tags', 'author','category' ,'body')
widgets = {
'title': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'this is placeholder'}),
'tags': forms.TextInput(attrs={'class':'form-control'}),
'author': forms.Select(attrs={'class':'form-control'}),
'category': forms.Select( choices = choice_list, attrs={'class':'form-control'}),
'body': forms.Textarea(attrs={'class':'form-control'}),
}
I'm creating a blog by django, when I want to open http://127.0.0.1:8000/accounts/login I get the error:
init() takes 1 positional argument but 2 were given
Exception Location:
C:\ProgramData\Miniconda3\envs\myDjanEnv\lib\site-packages\django\core\handlers\base.py
in _get_response, line 124
And this is the 124th line of the code from base.py:
if response is None:
wrapped_callback = self.make_view_atomic(callback)
try:
<!-- line 124 --> response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
response = self.process_exception_by_middleware(e, request)
VIEWS.PY CODES:
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Post,Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse,reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView,)
# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
# form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
# form_class = PostForm
model = Post
class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True,).order_by('created_date')
###############################################
###############################################
#login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
post.publish
return redirect('post_detail',pk=pk)
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail',pk=post.pk)
else:
form = CommentForm()
return render(request,'blog/comment_form.html',{'form':form})
#login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
#login_required
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail',pk=post_pk)
FORMS.PY CODES:
from django import forms
from blog.models import Post,Comment
class PostForm(forms.ModelForm):
class Meta():
model = Post
fields = ('author','title','text')
widgets = {
'title':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent'})
}
class CommentForm(forms.ModelForm):
class Meta():
model = Comment
fields = ('author','text')
widgets = {
'author':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea'})
}
MODELS.PY CODES:
from django.db import models
from django.utils import timezone
from django.urls import reverse,reverse_lazy
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.PROTECT)
title = models.CharField(max_length=200)
text = models.TextField()
create_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 approve_comments(self):
return self.comments.filter(approve_comment=True)
def get_absolute_rul(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.PROTECT)
author = models.CharField(max_length=200)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
approve_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_rul(self):
return reverse('post_list')
def __str__(self):
return self.text
URLS.PY (in the same folder that setting.py is in):
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from django.contrib.auth import views
from django.contrib.auth.views import LoginView
urlpatterns = [
path('admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'accounts/login/$',views.LoginView,name='login'),
url(r'accounts/logout/$',views.LogoutView,name='logout',kwargs={'next_page':'/'}),
]
URLS.PY (in the same folder that VIEWS.PY is in)
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(),name='post_list'),
url(r'^about/$',views.AboutView.as_view(),name='about'),
url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
url(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$',views.PostDetailView.as_view(),name='post_remove'),
url(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),
url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
url(r'^post/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
url(r'^post/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]
What is the problem?
In your urls, you are not using as_view() at the end of class based views. You need to use it like this:
path('about/', AboutView.as_view(), name='about')
Update
Problem is in your LoginView and LogoutView which is imported from django.contrib.auth.views. They are class Based Views. So you need to add as_view at the end of them when declaring in the class.
url(r'accounts/login/$',views.LoginView.as_view(),name='login'),
url(r'accounts/logout/$',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'})
I am using django 1.11.6 and python 3.6.2
I'm new to django and there is no one to help me where i live so you guys are all my hope
in my django application in the add song section i faced an error
error message =
IntegrityError at /music/album/5/AddSong/ NOT NULL constraint failed:
music_song.album_id
here is my views file:
from django.views import generic
from django.views.generic import View
from .forms import UserForm
from django.views.generic.edit import CreateView,UpdateView,DeleteView
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login
from .models import Album, Song
from django.core.urlresolvers import reverse_lazy
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DetailView):
model = Album
template_name = 'music/detail.html'
context_object_name = 'album'
class AlbumCreate(CreateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class SongCreate(CreateView):
model = Song
fields = ['song_title', 'file_type']
class AlbumUpdate(UpdateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumDelete(DeleteView):
model = Album
success_url = reverse_lazy('music:index')
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
#display a blank form
def get(self,request):
form = self.form_class(None)
return render(request,self.template_name, {"form": form})
#procces form data
def post(self,request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
#returns User objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request,user)
return redirect('music:index')
return render(request,self.template_name, {"form": form})
and here is my models.py :
from django.db import models
from django.core.urlresolvers import reverse
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.FileField()
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.album_title + ' - ' + self.artist
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
is_favorite = models.BooleanField(default=False)
# song_file = models.FileField(null=True)
def __str__(self):
return self.song_title
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.album.id})
urls.py:
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
# /music/
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^register/$', views.UserFormView.as_view(), name='register'),
# /music/album/54
url(r'^album/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# music/album/add
url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'),
# music/album/3/AddSong
url(r'album/(?P<pk>[0-9]+)/AddSong/$', views.SongCreate.as_view(), name='song-add'),
# music/album/2/update/
url(r'album/(?P<pk>[0-9]+)/AlbumUpdate/$', views.AlbumUpdate.as_view(), name='album-update'),
# music/album/2/delete/
url(r'album/(?P<pk>[0-9]+)/AlbumDelete/$', views.AlbumDelete.as_view(), name='album-delete'),
]
For creating forms I used Django built-in forms,I had to create one for adding albums and another for adding the album's songs
Here is my album_form.html screenshot
and here is my form-template.html screenshot:
and here is my song_form.html screenshot
In the form_valid method, you should fetch the album pk from the url kwargs and set the album on the form instance.
from. django.shortcuts import get_object_or_404
class SongCreate(CreateView):
model = Song
fields = ['song_title', 'file_type']
def form_valid(self, form):
album = get_object_or_404(Album, pk=self.kwargs['pk']
form.instance.album = album
return super(SongCreate, self).form_valid(form)
I'm trying to add a search function to my website but I'm having some issues. It's currently telling me that "Search" is not defined, but I have the class in my views file. This is what I have thus far:
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^player/(?P<pk>\d+)/$', views.player, name='player'),
url(r'^season/(?P<pk>\d+)/$', views.season, name='season'),
url(r'^seasons/$', views.seasons, name='seasons'),
url(r'^search/$', Search.as_view(), name='search'),
]
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView
from .models import Player, Season, PxS, Statistics
def home(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/home.html', {'seasons': seasons})
def player(request, pk):
player = get_object_or_404(Player, pk=pk)
return render(request, 'webapp/player.html', {'player': player, 'seasons': player.season_set.order_by('sid'), 'statistics': player.statistics_set.all()})
def season(request, pk):
season = get_object_or_404(Season, pk=pk)
return render(
request,
'webapp/season.html',
{'season': season, 'players': season.players.order_by('lastname')}
)
def seasons(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/seasons.html', {'seasons': seasons})
class Search(ListView):
template_name = 'search.html'
model = Player
context_object_name = 'list'
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
context['count'] = self.get_queryset().count()
return context
def get_queryset(self):
pobj = Player.objects.all()
var_get_search = self.request.GET.get('search_box')
var_get_order_by = self.request.GET.get('pid')
if var_get_search is not None:
pobj = pobj.filter(playername__icontains=var_get_search)
if var_get_order_by is not None:
pobj = pobj.order_by(var_get_order_by)
return pobj
Any insight is greatly appreciated. I'm kind of just piecing this stuff together little by little. Thanks!
The problem is in the urls.py
Give url(r'^search/$', views.Search.as_view(), name='search'),
instead of just Search.