django object has no attribute status_code - python

I am learning to develop and trying to develop a screen in django 1.1 and I am getting this error below. I already took a look at some stacks I already looked at httpresponse, however, I was not successful
could someone help me and explain what could be wrong?
I'm getting this error on the console:
Internal Server Error: /gerencia-margem/list
Traceback (most recent call last):
File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response
response = middleware_method(request, response)
File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/middleware/locale.py", line 38, in process_response
if (response.status_code == 404 and not language_from_path and
AttributeError: 'HistoricoComissao' object has no attribute 'status_code'
[18/Nov/2020 13:30:06] "GET /gerencia-margem/list HTTP/1.1" 500 77145
This is models,
# -*- coding: utf-8 -*-
from django.db import models
class HistoricoComissao(models.Model):
class Meta:
verbose_name = u'Historico Comissão'
verbose_name_plural = u'Historico Comissões'
pednum = models.CharField(max_length=40, blank=True)
margem = models.DecimalField(decimal_places=4, max_digits=15, null=True, blank=True)
data = models.DateTimeField()
historico = models.TextField((u'Historico HTML'), blank=True)
status = models.PositiveSmallIntegerField(choices=[(1, 'Em Aberto'),
(3, 'Pendente'),
(4, 'Finalizado'),])
def __unicode__(self):
return str(self.pednum)
this is the views
from django.views import View
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from ..models import HistoricoComissao
def listview(request):
template_name = 'comissao/margenslist.html'
comissoes = HistoricoComissao.objects.all
context = {
'comissoes': comissoes
}
return render(request,template_name,context)
this is urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list$', views.HistoricoComissao, name='historico_comissao'),
]

In your urls.py you use as view HistoricoComissao, but that is a re-export of a Django model, not of a view. You should use the listview:
from django.conf.urls import url
from . import views
urlpatterns = [
# link to a view function ↓
url(r'^list$', views.listview, name='historico_comissao'),
]
I am learning to develop and trying to develop a screen in django 1.1.
Please upgrade. Django-1.1 was end of life before 2013. Furthermore a lot of things have changed in the meantime (and often improved).

Related

DetailView in Django, keyword 'slug'

I recently started learning Django. I want to display one news item, but when I open on the link I get an error message:
Cannot resolve keyword 'slug' into field. Choices are: NewsTitles, NewsContent, NewsSlug
Request Method: GET
Request URL: http://127.0.0.1:8000/news/nam-gravida-purus-non/
Django Version: 4.0
Exception Type: FieldError
views.py
from django.views.generic import DetailView
from .models import News
class GetNews(DetailView):
model = News
slug_url_kwarg = 'NewsSlug'
template_name = 'news/single_news.html'
context_object_name = 'single_news'
allow_empty = False
urls.py
from django.urls import path
from .views import GetNews
urlpatterns = [
path('news/<str:NewsSlug>/', GetNews.as_view(), name='news'),
]
models.py
from django.db import models
from django.urls import reverse_lazy
class News(models.Model):
NewsTitles = models.CharField(max_length=120)
NewsContent = models.TextField(max_length=255)
NewsSlug = models.SlugField(max_length=255)
def __str__(self):
return self.NewsTitles
def get_absolute_url(self):
return reverse_lazy('news', kwargs={'NewsSlug': self.NewsSlug})
What am I doing wrong?
First of all do not call your slug "NewSlug" with uppercase but all lower case "newslug" or even better "new_slug", the name itself should be more descriptive as well.
Finally you need to tell your view which field to use, you can define that with the following attribute :
slug_field = "NewSlug"
Note : Attribute of a class should not be camel case but snake case

I have a python django app that was working fine until Pylance was automatically installed. Now I get an error: Exception has occurred:

My code is:
from django.shortcuts import render # Create your views here.
from django.views.generic import ListView # <- new
from .models import Post
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
And the error I receive is
from .models import Post
Exception has occurred: ImportError
attempted relative import with no known parent package
Post is defined in:
from django.db import models # Create your model fields here.
from django.utils import timezone # for the DateTimeZone field below
from django.contrib.auth.models import User # the author field below needs this
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField() # TextField has no length limitation
date_posted = models.DateTimeField(default=timezone.now) # Use the django timezone
author = models.ForeignKey(User, on_delete=models.CASCADE) # if the User is deleted, so will this model
def __str__(self):
return self.title
Any help would be appreciated.

SyntaxError: invalid syntax when trying migrate

models.py
from django.db import models
class User(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField(max_length=256, unique=True)
views.py
from django.shortcuts import render
form appTwo.moldels import User
# Create your views here.
def index(request):
return render(request, 'appTwo/index.html')
def users(request):
user_list = User.object.order_by('first_name')
user_dict = {'users':user_list}
return render(request, 'appTwo/users.html', context=user_dict)
protwo/urls.py
appTwo/urls.py
from django.conf.urls import path
from appTwo import views
urlpatterns = [
path('', views.users, name='users'),
]
I've tried migrating but it causes a syntax error. The stack trace is included below:
File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/proTwo/urls.py", line 18, in <module>
from appTwo import views
File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/appTwo/views.py", line 2
form appTwo.moldels import User
^
SyntaxError: invalid syntax
(myDjango) hamid#hamid-PC:~/Desktop/my_django_stuff/project_two/proTwo$
You misspelled models:
form appTwo.moldels import User
to
form appTwo.models import User
Other than the typo in "moldels" pointed out by FBSO, there is also another in the same line in "form", it should be "from":
from appTwo.models import User

Django testing user model fails but it works in the browser

I am new to testing and am trying to run the following tests but I get a 404 assertion error because the method that tries to reverse the url cannot find the category that had been created in the setUp method. I can create categories in the browser using the superuser with no problem and the url responds with 200 status. Could you help me understand what I am doing wrong?
Test:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth.models import User
from cataloger.models import Category
class CatalogerCategoriesTests(TestCase):
def setUp(self):
tom = User.objects.create_user(username="tom", password="1234567")
Category.objects.create(name="cell phone",
description="current cell phone types in the market.",
created_by=tom)
def test_category_page_success_status_code(self):
url = reverse('category_items', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
Fail:
Traceback (most recent call last):
File "/home/ubuntu/workspace/cataloger/tests_categories.py", line 48, in test_category_page_success_status_code
self.assertEquals(response.status_code, 200)
AssertionError: 404 != 200
Models:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=300)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
created_by = models.ForeignKey(User, related_name="categories")
Views:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from cataloger.models import Category
def category_items(request, pk):
category = get_object_or_404(Category, pk=pk)
return render(request, 'category_items.html', {'category': category})
urls:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^cataloger/$', views.cataloger, name='cataloger'),
url(r'^cataloger/categories/(?P<pk>\d+)/$', views.category_items, name='category_items')
]
The pk of the object might not always be 1 depending upon the test structure and DB. The pk of the Category instance should be used explicitly.
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth.models import User
from cataloger.models import Category
class CatalogerCategoriesTests(TestCase):
def setUp(self):
tom = User.objects.create_user(username="tom", password="1234567")
self.category = Category.objects.create(
name="cell phone",
description="current cell phone types in the market.",
created_by=tom
)
def test_category_page_success_status_code(self):
url = reverse('category_items', kwargs={'pk': self.category.pk})
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
#Stuart Dines explains very well. You should match pk for urls.
Or if you just want to know that model instance created well, just try self.assertIsInstance(...)
def setUp(self):
tom = User.objects.create_user(username="tom", password="1234567")
category = Category.objects.create(name="cell phone",
description="current cell phone types in the market.",
created_by=tom)
def test_if_category_instance_made(self):
self.assertIsInstance(self.category, Category)
Also I recommend model mommy for easy testing django models. It automatically generate random model (also put test data possible) and make really easy to testing your model!
This is example using model_mommy for your test code
from model_mommy import mommy
class CatalogerCategoriesTests(TestCase):
def setUp(self):
self.tom = mommy.make("User")
self.category = mommy.make("Category", user=self.user)
def test_if_category_instance_made(self):
self.assertIsInstance(self.category, Category)
def test_category_page_success_status_code(self):
url = reverse('category_items', kwargs={'pk': self.category.pk})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)

cats() got an unexpected keyword argument 'pk'

I'm a amature django web developer. I have a problam with Django. this error is "cats() got an unexpected keyword argument 'pk'".
please see my codes and help me.
Request Method: GET
Request URL: http://127.0.0.1:8000/1
Django Version: 1.6.5
Exception Type: TypeError
Exception Value:
cats() got an unexpected keyword argument 'pk'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response, line 112
Python Executable: /usr/bin/python
Python Version: 2.7.6
models.py
from django.db import models
from taggit.managers import TaggableManager
class Category(models.Model):
title = models.CharField(max_length=40)
def __unicode__(self):
return self.title
class Post (models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
date = models.DateTimeField()
tags = TaggableManager ()
cats = models.ManyToManyField(Category)
def __unicode__ (self):
return self.title
urls.py
from django.conf.urls import include, url, patterns
from django.views.generic import ListView, DetailView
from blog.models import Post, Category
urlpatterns = patterns('blog.views',
url(r'^$',ListView.as_view(
queryset = Post.objects.all().order_by("-date")[:2],
template_name="index.html")),
url(r'^(?P<pk>\d+)$', 'cats', name='cats'),
)
views.py
from blog.models import Post,Category
from django.shortcuts import render_to_response
from django.template import RequestContext
def cats(request):
queryset = Post.objects.all().order_by("-date")
navitem = Category.objects.all().order_by("title")
return render_to_response('post.html',{'queryset':queryset,'navitem':navitem},context_instance=RequestContext(request))
The problem is in this line in urls.py:
url(r'^(?P<pk>\d+)$', 'cats', name='cats')
You are sending to the view an argument that it doesn't need.
You can include the pk argument in the view parameters, like this:
def cats(request, pk):
or this:
def cats(request, pk=None):
Or, even better, you can use a different pattern in your URL, without capturing it (because you are not using that pk value at all in your view, you don't need to create a variable for it), like this:
url(r'^(\d+)$', 'cats', name='cats')

Categories

Resources