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
Related
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
I get an HTTP 410 error when invoking the following Django View:
>>> views.py:
class ReopenMilestoneView(
dj_auth_mixins.LoginRequiredMixin, dj_views.RedirectView
):
pattern_name = 'bibliotheka_dashboard'
def dispatch(self, request, *args, **kwargs):
print('DISPATCH BEGIN')
instance = project_models.Milestone.objects.get(pk=kwargs['pk'])
instance.state = project_models.STATE_OPEN
instance.save()
print('DISPATCH END')
return super(ReopenMilestoneView, self).dispatch(
request, *args, **kwargs
)
def http_method_not_allowed(self, *args, **kwargs):
print('HTTP NOT ALLOWED BEGIN')
try:
return super(ReopenMilestoneView, self).http_method_not_allowed(
*args, **kwargs
)
except:
print('EXCEPTION')
print('HTTP NOT ALLOWED END')
def get_redirect_url(self, *args, **kwargs):
print('REDIRECT BEGIN')
result = super(ReopenMilestoneView, self).get_redirect_url(
*args, **kwargs
)
print('REDIRECT END, result = ' + str(result))
url = urlresolvers.reverse('bibliotheka_dashboard')
url2 = urlresolvers.reverse(self.pattern_name)
print('REDIRECT END, URL_resolved = ' + str(url))
print('REDIRECT END, pattern_name = ' + str(self.pattern_name))
print('REDIRECT END, URL_2_resolved = ' + str(url2))
return result
>>> urls.py:
...
url(
r'^milestone/dashboard/$',
project_views.MilestoneDashboard.as_view(),
name='milestone_dashboard'
),
url(
r'^milestone/(?P<pk>[\w-]+)/dashboard/$',
project_views.MilestoneDashboard.as_view(),
name='milestone_specific_dashboard'
),
...
I added prints through the three methods form "RedirectView" that are mentioned in the Django documentation as part of the regular workflow (django).
Dispatch is properly executed but, when resolving automatically the "pattern_name", "RedirectView" fails... manually resolving it, solves the problem.
DISPATCH BEGIN
DISPATCH END
REDIRECT BEGIN
REDIRECT END, result = None
REDIRECT END, URL_resolved = /
REDIRECT END, pattern_name = bibliotheka_dashboard
REDIRECT END, URL_2_resolved = /
Gone: /prj/milestone/2/reopen/
[12/Jul/2017 13:28:34] "GET /prj/milestone/2/reopen/ HTTP/1.1" 410 0
I have used "RedirectView" before but I have never got this error, any ideas? Django is not returning a lot of info back...
My URLs are defined as follows:
from django.conf.urls import url, include
from django.conf.urls import static as dj_static
from django.contrib import admin
from bibliotheka import settings as bibliotheka_settings
from documentation.views import project as project_views
urlpatterns = [
url(
r'^$',
project_views.MilestoneDashboard.as_view(),
name='bibliotheka_dashboard'
),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^accounts/', include('allauth.urls')),
url(r'^prj/', include('documentation.urls.project')),
url(r'^dox/', include('documentation.urls.documents')),
url(r'^dox/', include('documentation.urls.discrepancies')),
]
if bibliotheka_settings.DEBUG:
urlpatterns += dj_static.static(
bibliotheka_settings.MEDIA_URL,
document_root=bibliotheka_settings.MEDIA_ROOT
)
I am trying to redirect to "/" with the problematic views.
Django is failing to reverse milestone_dashboard. In Django <= 1.11, it silences the NoReverseMatch, and returns a 410 response.
This behaviour has been changed in Django 2.0 (see ticket 26911), so Django will no longer silence the exception.
When you use pattern_name, Django tries to reverse with the same args and kwargs. You do not want this, as you are redirecting from a url containing the pk to a url that does not have any arguments.
You can set url with reverse_lazy:
from django.urls import reverse_lazy
class ReopenMilestoneView(RedirectView):
url = reverse_lazy('bibliotheka_dashboard')
I am getting error : 'str' object has no attribute 'method' . See my code below :
#csrf_exempt
def completepayment(request):
varerr =''
plist = []
if request.method == 'POST':
try:
nid = request.POST['txnref']
except MultiValueDictKeyError:
varerr ="Woops! Operation failed due to server error. Please try again later."
return render(request, 'uportal/main.html', {'varerr':varerr})
# Fetching member details
trym = Transactions.objects.get(TransRef=nid)
amount = trym.Amount
famt = int(amount * 100)
product_id = 48
salt = '4E6047F9E7FDA5638D29FD'
hash_object = hashlib.sha512(str(product_id)+str(nid)+str(famt))
hashed = hash_object.hexdigest()
url = 'https://bestng.com/api/v1/gettransaction.json?productid=pdid&transactionreference=nid&amount=famt'
raw = urllib.urlopen(url)
js = raw.readlines()
#js_object = simplejson.loads(js)
res = simplejson.dumps(js)
for item in res:
rcode = item[0]
#rdesc = item[1]
#preff = item[2]
thisresp = completepayment(rcode)
plist.append(thisresp)
else:
varerr ="Woops! Operation failed due to server error. Please try again later."
return render(request, 'uportal/main.html', {'plist':plist, 'varerr':varerr, 'completepayment':'completepayment'})
In summary I am trying to accept and use HTTP POST value from an external API. Value is showing when I inspect element but DJANGO not retrieving. Please help.
Here is my urls.py
from django.conf.urls import patterns, url
from views import *
from django.views.generic import RedirectView
urlpatterns = patterns('myproject.prelude.views',
# Home:
url(r'^$', 'home', name='home'),
#login
url(r'^login/$', 'login', name='login'),
url(r'^welcome/$', 'welcome', name='welcome'),
# Registration Portal
# Registration Portal
url(r'^uportal/$', 'uportal', name='uportal'),
url(r'^uportal/ugreg/find/$', 'findmember', name='findmember'),
url(r'^uportal/ugreg/search/$', 'searchmember', name='searchmember'),
url(r'^uportal/ugreg/$', 'ugreg', name='ugreg'),
url(r'^uportal/ugreg/initiate-payment/$', 'initiatepayment', name='initiatepayment'),
url(r'^uportal/ugreg/verifypayment/$', 'verifypayment', name='verifypayment'),
url(r'^uportal/ugreg/proceedpayment/$', RedirectView.as_view(url='https://bestng.com/pay'), name='remote_admin'),
url(r'^uportal/ugreg/completepayment/$', completepayment, name='completepayment'),
Thank you
It appears that your problem is that request is an str object rather than a request object.
Please produce urls.py and views.py.
For readability, let’s rewrite the part below:
url = 'https://bestng.com/api/v1/gettransaction.json'
params = '?productid={product_id}&transactionreference={nid}&amount={famt}'
raw = urllib.urlopen(url + params.format(**locals()))
Or even, like so:
url = 'https://bestng.com/api/v1/gettransaction.json'
params = '?productid={product_id}&transactionreference={nid}&amount={famt}'
request = url + params.format(**locals())
raw = urllib.urlopen(request)
Also, the try block is not what I would use. Instead, I would use the get method of the POST dict and return a flag value:
nid = request.POST.get('tnxref', False)
I am unable to reproduce the error you are getting. With a slightly different project-level urls.py (very simplified), the ‘completepayment’ view works fine for me. Here is urls.py.
from django.conf.urls import patterns, url
from app.views import completepayment
# The app is simply called app in my example.
urlpatterns = patterns('',
# I remove the prefix
url(r'^uportal/ugreg/completepayment/$', completepayment, name='completepayment'),
)
# This last parenthesis might be missing in your code.
I have lots of simple Django views that look like this:
#team_leader_required
def view_all_teams(request):
teams = Team.objects.all()
template_vars = {'toolbar': 'teams',
'teams': teams}
return render(request, "all_teams.html", template_vars)
I end up writing lots of unit tests of the form:
def test_view_all_teams_renders(self):
user = self.create_team_leader()
self.log_in(user)
response = self.client.get(reverse('all_teams'))
self.assertHttp200(response)
Despite my convenience methods for creating users (e.g. .create_team_leader) and various convenience assertions (e.g. .assertHttp200), I still end up with a lot of duplication in my tests.
(My tests are simple since I can't see anything else useful to assert about these views -- TestCase.assertTemplateUsed breaks if you rename templates, even if the view is correct.)
It's easy to miss a test, which gives me little confidence when I rename templates. Is there any way I can automatically generate test cases? Something like (psuedo-code):
for every view in urls:
if view doesn't take extra arguments:
test that view returns 200 when a logged in superuser does a GET
EDIT
Here's a representative snippet from my urls.py:
urlpatterns = patterns('',
url(r'^teams/$', 'teams.views.view_all_teams', name='all_teams'),
url(r'^teams/major/$', 'teams.views.view_major_teams', name='major_teams'),
url(r'^teams/minor/$', 'teams.views.view_minor_teams', name='minor_teams'),
url(r'^teams/(?P<team_id>\d+)/$', 'teams.views.view_team', name='view_team'),
url(r'^teams/(?P<team_id>\d+)/edit$', 'teams.views.edit_team', name='edit_team'),
url(r'^teams/(?P<team_id>\d+)/delete$', 'teams.views.delete_team', name='delete_team'),
I'd like to automatically test the first three views in this list.
from django.core import urlresolvers
from django.test import TestCase
class SimpleTest(TestCase):
def test_simple_views(self):
url_names = [
'all_teams',
'major_teams',
'minor_teams',
'view_team',
'edit_team',
]
user = self.create_team_leader()
self.log_in(user)
for url_name in url_names:
try:
url = urlresolvers.reverse(url_name, args=(), kwargs={})
except urlresolvers.NoReverseMatch:
#print('Pass {}'.format(url_name))
continue
#print('Try {}'.format(url_name))
response = self.client.get(url)
self.assertHttp200(response)
If all url patterns have their name, You can use follow code to define url_names:
url_names = [p.name for p in teams.urls.urlpatterns]
Known Issues
If view function fail, you will not know which view failed.
Views next to failed view will not be tested.
Another version that handle above issues.
import unittest
from django.core import urlresolvers
from django.test import TestCase
from teams.urls import urlpatterns
class SimpleTest(TestCase):
...
def setUp(self):
user = self.create_team_leader()
self.log_in(user)
url_names = [p.name for p in urlpatterns]
vs = vars()
def make_test_function(idx, url_name, url):
def t(self):
response = self.client.get(url)
self.assertHttp200(response)
t.__name__ = 'test_' + idx
t.__doc__ = 'simple get test for ' + url_name
return t
for i, url_name in enumerate(url_names):
i = str(i)
try:
url = urlresolvers.reverse(url_name, args=(), kwargs={})
vs['test_' + i] = make_test_function(i, url_name, url)
except urlresolvers.NoReverseMatch as e:
vs['test_' + i] = unittest.skip(url_name + ' requires parameter(s) or view not found')(lambda: 0)
del url_names, vs, make_test_function,
I am trying to write correct redirection to other view, but now I have no idea
This is my last try:
txt2png/urls.py
urlpatterns = patterns('txt2png.views',
# ...
url(r'^list/(?P<what>\w)/', 'list', name='list-notes'),
url(r'^search/', 'search', name='search-notes'),
)
txt2png/views.py
def list(request, what):
# ...
def search(request):
#...
return redirect(list, 'search')
have you tried the .../list/anything/ ?
It is 404, because of your url config. The (?P<what>\w) means only ONE character, so .../list/a/ will work.
Replace that row in your url config:
url(r'^list/(?P<what>\w+)/', list, name='list-notes'),
(a + sign added to the regex)