View does not exist in module reviews.views - python

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.

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'),

Django Reverse Not Found When Unit-Testing

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")

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.

Django NameError: name 'views' is not defined

I am working through this tutorial on rapid site development with Django.
I have followed it exactly (as far as I can see), but get the following error when I try to view the index page:
NameError at /name 'views' is not defined
Exception location: \tuts\urls.py in <module>, line 12
Here's urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index'),
)
Here's views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
items = Item.objects.order_by("-publish_date")
now = datetime.datetime.now()
return render(request,'portfolio/index.html', {"items": items, "year": now.year})
And here's models.py:
from django.db import models
# Create your models here.
class Item(models.Model):
publish_date = models.DateField(max_length=200)
name = models.CharField(max_length=200)
detail = models.CharField(max_length=1000)
url = models.URLField()
thumbnail = models.CharField(max_length=200)
I also have a basic index.html template in place. From looking around I think I need to import my view somewhere.
But I'm completely new to Django so I have no clue. Any ideas?
The error line is
url(r'^$', views.index, name='index'),
#----------^
Here views is not defined, hence the error. You need to import it from your app.
in urls.py add line
from <your_app> import views
# replace <your_app> with your application name.
from .views import index
here we have to import views model classes on urls model so above sentence import your view model class on urls model.
add this code in urls.py
If you are using rest_framework in django then import:
from rest_framework import views

Categories

Resources