Django Reverse Not Found When Unit-Testing - python

I am writing unit-tests for a Django app. The app works as expected. However, one of the new tests fails because the system is not able to find a reverse match for a view name. What am I missing?
django.urls.exceptions.NoReverseMatch: Reverse for
'video_uploader.list_videos' not found. 'video_uploader.list_videos'
is not a valid view function or pattern name.
app/tests.py
from django.test import TestCase
from .models import Video
from .views import *
from django.db import models
from django.utils import timezone
from django.urls import reverse
class VideoTest(TestCase):
def create_video(self, name="Test Video", creation_date=timezone.now, videofile="/video/"):
return Video.objects.create(name=name, videofile=videofile)
def test_video_creation(self):
video = self.create_video()
self.assertTrue(isinstance(video, Video))
self.assertEqual(video.__str__(), video.name + ": " + str(video.videofile))
def test_videos_list_view(self):
video = self.create_video()
url = reverse("video_uploader.list_videos")
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertIn(video.name, response.content)
app/urls.py
from django.urls import path
from . import views
app_name = 'video_uploader'
urlpatterns = [
path('upload', views.upload_video, name='upload_video'),
path('', views.list_videos, name='list_videos'),
]

Between the app name and the url name should be a : not a .. Try with:
url = reverse("video_uploader:list_videos")

Related

Not getting the required interface everytime i search using/admin ,

I am following a yt tutorial on django(https://www.youtube.com/watch?v=sm1mokevMWk)
where the tutor searches http://127.0.0.1:8000/admin and gets the required interface
(It starts around 49:00)
everytime i search http://127.0.0.1:8000/admin
i get a
DoesNotExist at /admin
but when i search http://127.0.0.1:8000/admin/login/?next=/admin/nw/
i get the required interface
A question exactly same as mine has been asked before but the thing is i did not make the same error as that person did
this is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import ToDoList,Items
def index(response,name):
ls=ToDoList.objects.get(name=name)
item=ls.items_set.get(id=1)
return HttpResponse("<h1>%s</h1><br></br><p>%s</p>"%(ls.name,str(item.text)))
# Create your views here.
this is my urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("main.url")),
]
this is my models.py
from django.db import models
class ToDoList(models.Model):
name=models.CharField(max_length=200)
def __str__(self):
return self.name
class Items(models.Model):
todolist=models.ForeignKey(ToDoList,on_delete=models.CASCADE)
text=models.CharField(max_length=300)
complete=models.BooleanField()
def __str__(self):
return self.text
I shouldnt have added the '/ ' in /admin which is inside the urls.py file

page not found error while passing paarmeter through url in view django

I am new to python django. I am facing an issue while passing parameter to view through URL in django.
code:
views.py
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
text = "HEllo"
return HttpResponse(text)
def viewArticle(request, articleId):
text = "HEllo : %d"%articleId
return HttpResponse(text)
urls.py
from django.conf.urls import url
from django.urls import path,include
from myapp import views
urlpatterns = [
path('hello/',views.hello,name='hello'),
path('article/(\d
+)/',views.viewArticle,name='article'),
]
image:
you need to change your url like this:
path('article/<int:articleId>/',views.viewArticle,name='article'),
Hope this work!
Here your are using path. And path uses route without regex.
You need to change url to,
path('article/<int:articleId>/',views.viewArticle,name='article'),

urlpatterns return the value of very first function

I just started to learn Python Django Webpage development. My plan was to show the current time and window service status in my page.
I have two functions in my views.py and urlpatterns refers these two functions in urls.py
Whenever i run the server, the very first url only showed in my page.
views.py:
from django.shortcuts import render
from django.http import HttpResponse
import psutil, datetime
def winservice(request):
servicename = psutil.win_service_get('BrokerAgent')
service = servicename.as_dict()
if service['status'] == 'running':
return HttpResponse("<h2>Hey Citrix is Up and Running .. </h2>")
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.current_datetime, name ='current_datetime'),
url(r'^winservice$',views.winservice,name ='winservice'),
]
Expected Result:
Page should contains
Current time.
Status of my service.

Circular import error when I open the Django server

When I open the server(Django) I get this error: "The included URLconf 'admin.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import."
I have found out that by removing .views import from urls.py I fix the issue. So I think the problem is inside views.py.
App urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('/api', include('crud.urls')),
]
views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserSerializer
class UserView(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response({"users": users})
serializer.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)
email = serializers.EmailField()
password = serializers.CharField(max_length=255)
disease = serializers.CharField(max_length=255)
logo = serializers.TextField()
crud urls.py
Here, the issue is at the second line: if I remove that line I fix the error
from django.urls import path
from .views import UserView
app_name='crud'
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('users/', UserView.as_view()),
]
Please add error trace for better understanding of the issue.
Meanwhile try changing this:
path('/api', include('crud.urls'))
to:
path('api/', include('crud.urls')),
and
from .views import UserView
to:
from crud import views
urlpatterns = [
path('users/', views.UserView.as_view()),
]

View does not exist in module reviews.views

So I am getting this error in django
Exception Value: Could not import reviews.views.get_user_review. View does not exist in module reviews.views.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in get_callable, line 118
This is my urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
# Examples:
url(r'^$', 'feed.views.home'),
url(r'', include('social_auth.urls')),
url(r'^logged-in/$', 'custom_user.views.fb_loggedin'),
#url(r'^review/get/(?P<userid>.+?)/$', 'reviews.views.get_user_reviews_json'),
url(r'^rating/add/(?P<actor>.+?)/(?P<target>.+?)/(?P<category>.+?)/(?P<rating>.+?)/$', 'rating.views.add_rating'),
url(r'^rating/get/(?P<userid>.+?)/$', 'rating.views.get_user_ratings'),
)
urlpatterns += staticfiles_urlpatterns()
To remove the error, I've commented everything related to reviews app. But the error still exists. Here's the reviews.views
'''
from django.shortcuts import render
from models import Reviews
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.utils import simplejson
from django.core import serializers
def user_review(userid):
user = User.objects.get(id = userid)
reviews = Reviews.objects.filter(subject_user=user).select_related('user')
return reviews
#HttpResponse(data, mimetype='application/javascript')
def get_user_reviews_json(userid):
reviews = user_review(userid)
data = serializers.serialize("json", reviews)
return data
'''
EDIT:
The function get_user_reviews_json was earlier defined as get_user_review and i forgot to update the urls.py from get_user_review to get_user_reviews_json and thus got the error. but then i updated it and still the error prevails. i then commented out everything as you can see, but still the same error.
Your view should take a request object to respond to web requests. So your function should look something like below:
def get_user_reviews_json(request, userid):
reviews = user_review(userid)
data = serializers.serialize("json", reviews)
return Response(data) #from rest_framework.response import Response
Again, each view function takes an HttpRequest object as its first parameter, which is typically named request.I hope it helps.

Categories

Resources