I have a Class based view:
class PromocionListView(ListView):
model = Promocion
and this url path:
urlpatterns = [
path('promocion/list', PromocionListView.as_view(), name='promocion_list')]
so i made the following test:
class PromocionTests(TestCase):
#classmethod
def setUpTestData(cls):
cls.promocion = Promocion.objects.create(fecha_de_inicio = date(2022,7,6),duracion = 90)
def test_url_exists_at_correct_location(self):
response = self.client.get('promocion/list')
self.assertEqual(response.status_code, 200)
but it is showing the error: AssertionError: 404 != 200.
Does anything knows why this is happening? I googled it a lot but I couldn't find an answer
Related
I am learning Djnago and
I have this function inside admin.py that counts how many participants in an activity, it is working fine until, I want to know if the current user is a superuser and added request inside def set_count(self, request, obj) expecting to make a request for the user. Since I am getting an error, this means, this it's not how to do it and wrong. How to correct this? Thanks.
Below is what I want to do, evaluate the user.is_superuser if true, it will display in the list_display the link to the participants_changelist otherwise, display a plain text.
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(set_count=Count('activity_activity'))
return queryset
def set_count(self, request, obj):
counter = obj.set_count
if request.user.is_superuser:
url = (
reverse("admin:activity_announcements_participants_changelist")
+ "?"
+ urlencode({"activity__id": f"{obj.id}"})
)
return format_html('{} Paticipants', url, counter)
else:
counter = obj.set_count
return format_html('{} Paticipants', counter)
set_count.short_description = "No. of Paticipants"
Error:
TypeError at /admin/activity_announcements/activity/
ActivityAdmin.set_count() missing 1 required positional argument: 'obj'
Request Method: GET
Request URL: http://localhost:8000/admin/activity_announcements/activity/
Django Version: 4.1.5
Exception Type: TypeError
Exception Value:
ActivityAdmin.set_count() missing 1 required positional argument: 'obj'
Exception Location: /py/lib/python3.11/site-packages/django/contrib/admin/utils.py, line 280, in lookup_field
Raised during: reversion.admin.changelist_view
Python Executable: /py/bin/python
Python Version: 3.11.1
Python Path:
['/app',
'/usr/local/lib/python311.zip',
'/usr/local/lib/python3.11',
'/usr/local/lib/python3.11/lib-dynload',
'/py/lib/python3.11/site-packages',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf']
Server time: Sun, 22 Jan 2023 03:06:22 +0800
The problem is that when defining a custom field to list in the admin, you don't have access to the request. The function definition should be like this def your_field(self, obj): . In order to get the request in a field definition you can do the following:
class YourAdmin(admin.modeladmin):
def get_queryset(self, request):
self.request = request
return super().get_queryset(request)
def set_count(self, obj):
counter = obj.set_count
if self.request.user.is_superuser:
url = (
reverse(
"admin:activity_announcements_participants_changelist")
+ "?"
+ urlencode({"activity__id": f"{obj.id}"})
)
return format_html('{} Participants', url, counter)
else:
counter = obj.set_count
return format_html('{} Participants', counter)
set_count.short_description = "No. of Paticipants"
anyone know why this error is happening? i've been running the same line for my other tests and only this one is returning an error
both lines in test_coverageReturnSuccess + test_coverageReturnCorrectCoverage returning this error:
response.render()
AttributeError: 'HttpResponse' object has no attribute 'render'
This is my APi test case
class CoverageTest(APITestCase):
protein = None
domain = None
protein_domain = None
good_url = ''
bad_url = ''
def setUp(self):
self.protein = ProteinFactory.create(pk=1, protein_id='A0A014PQC0', length=338)
self.domain = PfamFactory.create()
self.protein_domain = ProteinDomainLinkFactory.create(protein=self.protein,
pfam_id=self.domain,
start=157,
stop=314)
# Set urls
self.good_url = reverse('coverage', kwargs={'protein_id': 'A0A014PQC0'})
def tearDown(self):
# Reset test tables
Protein.objects.all().delete()
Pfam.objects.all().delete()
ProteinDomainLink.objects.all().delete()
# Reset primary keys
ProteinFactory.reset_sequence(0)
PfamFactory.reset_sequence(0)
ProteinDomainLinkFactory.reset_sequence(0)
def test_coverageReturnSuccess(self):
"""
Ensure we get an 200 OK status code when making a valid GET request.
"""
response = self.client.get(self.good_url, format='json')
response.render()
self.assertEqual(response.status_code, 200)
def test_coverageReturnCorrectCoverage(self):
"""
Ensure we get the right coverage of the requested protein
"""
response = self.client.get(self.good_url, format='json')
response.render()
data = json.loads(response.content)
self.assertEqual(data, 0.46449704142011833)
You should not render the response, the response is already rendered, so for example:
def test_coverageReturnSuccess(self):
"""
Ensure we get an 200 OK status code when making a valid GET request.
"""
response = self.client.get(self.good_url, format='json')
# not response.render()!
self.assertEqual(response.status_code, 200)
For JSON, you use:
def test_coverageReturnCorrectCoverage(self):
"""
Ensure we get the right coverage of the requested protein
"""
response = self.client.get(self.good_url, format='json')
# not response.render()!
data = response.json()
self.assertEqual(data, 0.46449704142011833)
When I transfer to the test url, an error pops up:
Reverse for 'movie' not found. 'movie' is not a valid view function or pattern name.
Here is my self test:
class BooksApiTestCase(APITestCase):
def setUp(self):
self.movie_1 = Movie.objects.create(title="terminator", year="1990", rating="5",url="retminator")
self.movie_2 = Movie.objects.create(title="robocop", year="1991", rating="4",url="robocop")
self.movie_3 = Movie.objects.create(title="rembo", year="1992", rating="3",url='rembo')
def test_get(self):
url = reverse('movie')
print(url)
response = self.client.get(url)
serializer_data = MovieListSerializer([self.movie_1, self.movie_2, self.movie_3], many=True).data
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual(serializer_data, response.data)
Here is my self url:
urlpatterns = format_suffix_patterns([
path("movie/", views.MovieViewSet.as_view({'get': 'list'})),
Hi #Andrew and Welcome to StackOverflow.
To use reverse() you have to properly set the view's name in the urlpatterns
urlpatterns = format_suffix_patterns([
path("movie/", views.MovieViewSet.as_view({'get': 'list'}, name='movie')
]),
Refer to the official documentation
I'm trying to create a custom Django RSS feed using django syndication (actually using django wagtail feeds). I have an error which I think I've identified as stemming from a NoneType object which is returned by the get_object() function inside syndication/views.py.
`AttributeError at /feed/basic/Chups/
'NoneType' object has no attribute 'startswith'
Exception Location: /Users/technical/.virtualenvs/wagtest4-plnzODoN/lib/python3.6/site-packages/django/contrib/syndication/views.py in add_domain, line 19`
That function is called as part of class Feed() and looks like this:
def get_object(self, request, *args, **kwargs):
return None
That function is called at line 36 but fails because get_object() returns a None object.
My customisation of django wagtail feeds extends Feed in the following way:
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import (
SyndicationFeed, rfc3339_date, Rss201rev2Feed
)
from .models import RSSFeedsSettings, RSSFeed
class BasicFeed(Feed):
# FEED TYPE
feed_type = Rss201rev2Feed
def get_object(self, request, category):
return category
try:
feed_app_settings = RSSFeedsSettings.objects.get(feed_category_name="Flex")
print(feed_app_settings)
feed_app_label = feed_app_settings.feed_app_label
feed_model_name = feed_app_settings.feed_model_name
feed_category_name = feed_app_settings.feed_category_name
use_feed_image = feed_app_settings.feed_image_in_content
except: # pragma: no cover
feed_app_settings = None
try:
feed_model = apps.get_model(app_label=feed_app_label,
model_name=feed_model_name)
except: # pragma: no cover
feed_model = None
# The RSS information that gets shown at the top of the feed.
if feed_app_settings is not None:
title = feed_app_settings.feed_title
link = feed_app_settings.feed_link
description = feed_app_settings.feed_description
author_email = feed_app_settings.feed_author_email
author_link = feed_app_settings.feed_author_link
item_description_field = feed_app_settings.feed_item_description_field
item_content_field = feed_app_settings.feed_item_content_field
def items(self, obj):
url_category = obj
categories = ContentType(app_label="blog", model="blogcategory")
category_id = categories.get_object_for_this_type(name=url_category).id
return feed_model.objects.filter(categories=category_id).order_by('-date').live()
def item_pubdate(self, item):
return datetime.combine(item.date, time())
def item_link(self, item):
return item.full_url
def item_author_name(self, item):
pass
urls.py includes this and requests seem to be reaching the function fine.
url(r'^feed/basic/(?P<category>[0-9a-zA-Z]+)/$', BasicFeed(), name='basic_feed'),
Can anyone tell me why that might be? I'm missing something about the expected functioning of this. Thanks!
I ask you to help me finding the source of problems with the following code.
I used page http://jcalderone.livejournal.com/53074.html as a guide.
The only difference of my code is that resource isn't served from .rpy file.
Also there is no cache() call anywhere.
The result of opening page at
https://serveraddr:serverport/services/admin is 403 Forbidden.
It needs to show the output from UpdateManager.render_GET().
In server.tac:
...
root = resource.ForbiddenResource()
err = resource.ForbiddenResource()
root.putChild("service", err)
upd = UpdateXMLProcessor()
err.putChild("update2", upd)
portal = Portal(PublicHTMLRealm(), [FilePasswordDB('httpd.password')])
credentialFactory = DigestCredentialFactory("md5", "House of Life Updates")
admin = HTTPAuthSessionWrapper(portal, [credentialFactory])
err.putChild('admin', admin)
...
In auth.py:
class PublicHTMLRealm(object):
implements(IRealm)
def requestAvatar(self, avatarId, mind, *interfaces):
if IResource in interfaces:
resc = UpdateManager()
resc.realm = self
return (IResource, resc, lambda: None)
raise NotImplementedError()
in admin.py:
class UpdateManager(resource.Resource):
isLeaf = False
pathFromRoot = '/service/admin'
def __init__(self):
resource.Resource.__init__(self)
self.newFull = NewFullResource()
self.putChild('new_full', self.newFull)
self.newDelta = NewDeltaResource()
self.putChild('new_delta', self.newDelta)
self.switch = SwitchResource()
self.putChild('switch', self.switch)
self.putChild('', self)
def render_GET(self, request):
...
Is anything wrong here in these code parts?
I have no errors shown in the console running with
twistd -ny server.tac