I have this error in Django regarding a failed test - python

It says that 1 test has failed in the tests.py file in the HomeTests. I am doing a product application. Here is my tests.py file.
from django.urls import reverse
from django.urls import resolve
from django.test import TestCase
from .views import home, product_topics
from .models import Product
class HomeTests(TestCase):
def test_home_view_status_code(self):
url = reverse('home')
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
def test_home_url_resolves_home_view(self):
view = resolve('/')
self.assertEquals(view.func, home)
def test_home_view_contains_link_to_topics_page(self):
product_topics_url = reverse('product_topics', kwargs={'pk': self.product.pk})
self.assertContains(self.response, 'href="{0}"'.format(product_topics_url))
class ProductTopicsTests(TestCase):
def setUp(self):
Product.objects.create(name='Light Bulb', description='Conserver energy',price=25.99,qtyOnHand=25)
def test_product_topics_view_success_status_code(self):
url = reverse('product_topics', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
def test_product_topics_view_not_found_status_code(self):
url = reverse('product_topics', kwargs={'pk': 99})
response = self.client.get(url)
self.assertEquals(response.status_code, 404)
def test_product_topics_url_resolves_board_topics_view(self):
view = resolve('/products/1/')
self.assertEquals(view.func, product_topics)
The AttributeError says that HomeTests has no attribute Product.
and here is my views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Product
# Create your views here.
def home(request):
products = Product.objects.all()
return render(request, 'home.html', {'products': products})
def product_topics(request, pk):
product = get_object_or_404(Product, pk=pk)
return render(request, 'topics.html', {'product': product})
In the urls.py, I have the following.
from django.conf.urls import url
from django.contrib import admin
from inventories import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^products/(?P<pk>\d+)/$', views.product_topics, name='product_topics'),
url(r'^admin/', admin.site.urls),
]
I would like to know why I am getting this error and what this error means so I can fix it. I am following the tutorial at Urls

The problem is the whole of this test!
def test_home_view_contains_link_to_topics_page(self):
product_topics_url = reverse('product_topics', kwargs={'pk': self.product.pk})
self.assertContains(self.response, 'href="{0}"'.format(product_topics_url))
There is no product or response objects in self while you are calling self.response & self.product. Maybe you wanted to do something like this?:
from django.test import Client
class HomeTests(TestCase):
def setUp(self):
self.client = Client()
# the other tests
def test_home_view_contains_link_to_topics_page(self):
product = Product.objects.create(
name='name', description='descr', price=1.0, qtyOnHand=2
)
product_topics_url = reverse('product_topics', kwargs={'pk': product.pk})
response = self.client.get(url)
content = response.content.decode('utf-8')
self.assertContains(content, 'href="{0}"'.format(product_topics_url))

Related

Django REST framework error - name is not defined

I have a Django 2.2 that has two apps - status and updates:
django_api
|
status
|
api
|
updates
In django_api/urls.py:
from django.contrib import admin
from django.urls import include, path
from updates.views import (
json_example_view,
JsonCBV,
JsonCBV2,
SerializedListView,
SerializedDetailView
)
from status.api.views import
StatusListSearchAPIView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/status/', status.api.urls),
path('api/updates/', updates.api.urls),
In django_api/status/api/views.py:
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import StatusSerializer
from status.models import Status
class StatusListSearchAPIView(APIView):
permission_classes = []
authentication_classes = []
def get(self, request, format = None):
qs = Status.objects.all()
serializer = StatusSeralizer(qs, many = True)
return Response(serializer.data)
def post(self, request, format=None):
qs = Status.objects.all()
serializer = StatusSeralizer(qs, many = True)
return Response(serializer.data)
class StatusAPIView(generics.ListAPIView):
permission_classes = []
authentication_classes = []
queryset = Status.objects.all()
serializer_class = StatusSeralizer
def get_queryset(self):
qs = Status.objects.all()
query = self.request.GET.get('q')
if query is not None:
qs = qs.filter(content_icontains = query)
return qs
In django_api/status/api/serializers.py:
from rest_framework import serializers
from django import forms
from status.models import Status
class StatusSerializer(serializers.ModelSerializer):
class Meta:
model = Status
fields = [
'user',
'content',
'image']
def validate_content(self, value):
if len(value) > 10000:
raise serializers.ValidationError("This is way too long.")
return value
def validate(self, data):
content = data.get("content", None)
if content == "":
content = None
image = data.get("image", None)
if content is None and image is None:
raise serializers.ValidationError("content or image is required.")
return data
When I run python manage.py runserver, I am getting an error:
File "...\status\api\views.py", line 26, in StatusAPIView
serializer_class = StatusSeralizer
NameError: name 'StatusSeralizer' is not defined
Updated: as indicated, this was a spelling error. However, after I imported status and from status.api imported urls, I am getting this error:
...\urls.py", line 39, in <module>
path('api/status/', status.api.urls),
...File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-
packages\django\urls\conf.py", line 73, in _path
raise TypeError('view must be a callable or a list/tuple in the case of
include().')
TypeError: view must be a callable or a list/tuple in the case of
include().
This is my status/api/urls.py:
from django.contrib import admin
from django.urls import path
from .views import StatusAPIView, StatusCreateAPIView
urlpatterns = [
path('/', StatusAPIView.as_view()),
path('create/', StatusCreateAPIView.as_view()),
]
Why am I getting this error?
It's a typo:
You are calling: StatusSeralizer but it is: StatusSerializer
I dont see StatusCreateAPIView in you views file. Have you created this view?
Try just commenting or removing path('create/', StatusCreateAPIView.as_view()), and see If you still get an error.
Try it bro:
from rest_framework import status.
Tell me if you have sucess!

Non_field_errors no data provided in django webapi

I am new in Django and python. Now I am trying to do web API with Django and python. I can get the get request but when I request the post method, this error is shown
"non_field_errors": [
"No data provided"
]
View.py=>
from rest_framework.generics import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Allowance
from .serializers import AllowanceSerializer
# Create your views here.
class AllowanceAPIView(APIView):
def get(self,request,pk=None):
if pk:
allowance=get_object_or_404(Allowance.objects.all(),pk=pk)
serializer = AllowanceSerializer(allowance)
return Response({serializer.data})
allowance=Allowance.objects.all()
serializer = AllowanceSerializer(allowance,many=True)
return Response({"allowance":serializer.data})
def post(self,request):
allowance = request.data.get('allowance')
serializer = AllowanceSerializer(data=allowance)
if serializer.is_valid(raise_exception=True):
allowance_saved=serializer.save()
return Response({"success":"Allowance '{}' created successfully".format(allowance_saved.AllowID)})
def put(self,request,pk):
save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk)
data = request.data.get('allowance')
serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True)
if serializer.is_valid(raise_exception = True):
allowance_saved=serializer.save()
return Response({"sucess": "Allowance '{}' updated successfully".format(allowance_saved.AllowID)})
def delete(self,request,pk):
#Get object with this pk
allowance = get_object_or_404(Allowance.objects.all(),pk=pk)
allowance.delete()
return Response({"message":"Allowance with id '{}' has been deleted.".format(pk)},status=204)
urls.py inside app =>
from django.conf.urls import url
from .views import AllowanceAPIView
urlpatterns = [
url(r'^$', AllowanceAPIView.as_view(), name='post-listcreate'),
url(r'^(?P<pk>\d+)/$', AllowanceAPIView.as_view(), name='post-listcreate')
]
urls.py inside project =>
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^api/auth/login/$', obtain_jwt_token, name='api-login'),
url(r'^api/allowances_mas/', include('tmswebapi.urls')),
]
sample API request=>
{
"AllowID": "Allow1",
"AllowDesc": "Allow1 Description",
"AllowAmt": "11.00",
"AllowType": "MEAL",
"Created_DT": "2019-06-18T18:09:00Z",
"Created_Usr": "Admin",
"LastModified_Usr": "",
"LastModified_DT": "2019-06-18T18:09:00Z"
}
Serializer =>
from rest_framework import serializers
import datetime
from .models import Allowance
class AllowanceSerializer(serializers.ModelSerializer):
class Meta:
model=Allowance
fields = "__all__"
def create(self,validated_data):
return Allowance.objects.create(**validated_data)
def update(self,instance,calidated_data):
instance.AllowDesc = validated_data.get('AllowDesc',instance.AllowDesc)
instance.AllowAmt = validated_data.get('AllowAmt',instance.AllowAmt)
instance.AllowType = validated_data.get('AllowType',instance.AllowType)
instance.LastModified_Usr = "Admin"
instance.LastModified_DT = datetime.datetime.now()
instance.save()
return instance
Is it because of urls or because of data format?
It's returning error from on of if serializer.is_valid(raise_exception = True): lines.
It means data is None somewhere.
Debug your code to make sure data variable has data
def post(self,request):
allowance = request.data
serializer = AllowanceSerializer(data=allowance)
if serializer.is_valid(raise_exception=True):
allowance_saved=serializer.save()
return Response({"success":"Allowance '{}' created successfully".format(allowance_saved.AllowID)})
Now try this

django - Type Error __init__ positional argument

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':'/'})

HttpRequestResponse reloading to same page in django 2.0.3

1.I am trying to develop a simple blog using django 2.0.3. in the view.py when i was trying to redirect to page from edit.html or create.html it is redirecting to it self when i was giving the url manually it is still loading to same page i don't know why.
views.py
from django.shortcuts import render,get_object_or_404,redirect
from django.http import HttpResponseRedirect,HttpResponse
from posts.models import Post
from posts.forms import PostForm
from django.contrib import messages
from django.urls import reverse
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
HttpResponseRedirect(instance.get_absolute_url())
context = {"title":"Create Blog","form":form}
return render(request,"create.html",context)
def post_detail(request,id):
instance = get_object_or_404(Post,id=id)
context = {
"title": instance.title,
"instance":instance
}
return render(request,"detail.html",context)
def post_update(request,id):
instance = get_object_or_404(Post,id=id)
form = PostForm(request.POST or None,instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Saved")
HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": "Edit Blog",
"instance":instance,
"form":form
}
return render(request,"edit.html",context)
def post_delete(request):
context = {"title":"Delete"}
return HttpResponse("<h1>delete</h1>")
def post_list(request):
queryset = Post.objects.all().order_by('-timestamp')
context = {
"title":"List",
"object_list":queryset
}
return render(request,"index.html",context)
2.this my urls.py
urls.py
from django.contrib import admin
from django.urls import path,include,re_path
from . import views
app_name = 'posts'
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^$',views.post_list,name="list"),
re_path(r'^create/$',views.post_create,name="create"),
re_path(r'^(?P<id>\d+)/$',views.post_detail,name="detail"),
re_path(r'^(?P<id>\d+)/edit/$',views.post_update,name="update"),
re_path(r'^delete$',views.post_delete),
]
3.this my models.py
model.py
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
timestamp = models.DateTimeField(auto_now=False,auto_now_add=True)
updated = models.DateTimeField(auto_now=True,auto_now_add=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"id":self.id})

Search Functionality on a Django Site

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.

Categories

Resources