I'm having a problem trying to use class based views in django.
When I try to import the base View I get an import error.
I've simplified my view down to the exact same code as used in the documentation:
from django.http import HttpResponse
from django.views.base import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')
The error I'm getting is
ImportError at /myurl/
No module named base
urls.py are fine and Django is definitely version 1.5 - I've completely reinstalled it with pip, any ideas?
Because of #dm03514 comment I test it. I try your code in your question and I got the same error with you "No module named base". So when I change it to, like the codes below, it works and no error.
from django.views.generic.base import View
Try before judging, I will accept it if it is wrong and I will try to fix it.
Related
I just finished installing Python and Django. I followed everything in a tutorial video and I wrote the most simple code:
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
return HttpResponse("<h1>Hello world!</h1>")
I imported it to the URL and it works as expected but the problem is I get this error:Unable to import I don't know why it is saying this because it works well. what is wrong with the program?
And I have the same import problem on other files too.
I'm aware of pdb built-in Python library for debugging Python programs and scripts. However, you can't really use it for debugging Django apps (I get errors when I try to use it in views.py). Are there any tools that I can use when Django's traceback isn't helpful ?
EDIT:
from .forms import TestCaseForm, TestCaseSuiteForm
from .models import TestCase, TestSuite
from django.contrib.auth.forms import UserCreationForm
from django.views.generic import FormView, ListView
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
import pdb
class ListAllTestSuites(ListView):
template_name = 'list.html'
context_object_name = 'username'
def get_queryset(self):
pdb.set_trace() # <-- setting a trace here to diagnose the code below
queryset = {'test_suites': TestSuite.objects.filter(user=self.request.user),
'username': self.request.user}
return queryset
you forgot the exact error message and full traceback, and, more importantly, you forgot to explain how you executed this code to get this result...
But anyway: from the error message, you're obviously trying to execute your view file as a plain python script (cf the reference to __main__). This cannot work. A view is a module, not a script, and, moreover, any module dependending on Django needs some setup done to be imported (which is why we use the django shell - ./manage.py shell - instead of the regular Python one).
For most case, you can just launch the django shell, import your module and use pdb.runcall() to execute some function / method under the debugger (no need to put a breakpoint then, but that's still possible).
Now views require a HTTPRequest as first argument which make them a bit more cumbersome to debug that way (well, there is django.tests.RequestFactory but still...), so your best bet here is to set your breakpoint, launch your devserver (or restart it - if it didn't already did, as it should), point your browser to the view's url, and then you should see the debugger's prompt in your devserver's terminal.
I'm new to Django testing so trying basic testing codes. But it is showing one error in second test class
Tests.py
from django.test import TestCase,Client
from .views import PostList
from django.urls import resolve
class SmokeTest2(TestCase):
def test_math(self):
self.assertEqual(1+1,2)
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
print({'found':found})
self.assertEqual(found.func(), PostList)
views.py
class PostList(ListView):
model = Post
template_name = 'home.html'
urls.py
urlpatterns = [
path('',views.PostList.as_view(),name ='list'),
]
When i am printing found its showing the o/p
{'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])}
But still I am getting this error
(blog_env) PS D:\django\blog_env\mysite> python manage.py test
D:\django\blog_env\mysite
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])}
E.
======================================================================
ERROR: test_root_url_resolves_to_home_page_view (blog.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\django\blog_env\mysite\blog\tests.py", line 19, in test_root_url_resolves_to_home_page_view
self.assertEqual(found.func(), PostList)
TypeError: view() missing 1 required positional argument: 'request'
----------------------------------------------------------------------
Ran 2 tests in 0.069s
FAILED (errors=1)
Destroying test database for alias 'default'...
I was stung by this issue just now, ended up finding the solution in the documentation
class-based views need to be compared by name, as the functions generated by as_view() won't be equal due to different object ids, so the assertion should look like the below:
from django.test import TestCase
from django.urls import resolve
from .views import HomePageView
class HomePageViewViewTest(TestCase):
def test_resolve_to_home_page_view(self):
resolver = resolve('/')
self.assertEqual(resolver.func.__name__, HomePageView.as_view().__name__)
from django.urls import resolve, reverse
class HomePageViewViewTest(TestCase):
def test_resolve_to_home_page_view(self):
resolver = resolve('/')
self.assertEqual(resolver.func.view_class, HomePageView)
You can try this, it worked for me!
Since you are testing a Class based View, from the Traceback it can be seen that it's missing the request object. You can use the RequestFactory provided by the django.test package. Better read the following RequestFactory Documentation to get a good view of it. It will solve your problem.
from django.urls import resolve, reverse
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
response = self.client.get(resolve('/'))
response = self.client.get(reverse('your_app_name:list'))
self.assertEqual(response.status_code, 200)
I'm using Python 2.7, webapp2 and GAE for developing a web app.
I'm facing a problem which i don't understand, since I know what it means but everything I did seems correct.
I get the error
AttributeError: type object 'DeleteAccount' has no attribute 'DAccount'
when i try to access the URL myappdomain/DeleteAccount/
I imported in the main file the python file DeleteAccount.py
import DeleteAccount
I linked the URL with the relative class DAccount of DeleteAccount
webapp2.Route(r'/DeleteAccount/',DeleteAccount.DAccount)
That's my DeleteAccount.py file
import logging
import webapp2
from webapp2_extras import sessions
import datastore
import FBLogin
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
return self.session_store.get_session()
class DAccount(BaseHandler):
def get(self):
w = self.response.write
logging.info("deleting account")
w('I've deleted the account')
What's wrong? I did what I've done with every other module and everything has worked well with them
I'm running Django (1.4.3) with dajaxice (0.5.4). I have a file ajax.py with my functions in the main project folder called prj, which looks like:
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
from django.utils import simplejson
from dajaxice.core import dajaxice_functions
from django.core.urlresolvers import reverse, resolve
def getContent(request, *args, **kwargs):
url = kwargs['url']
try:
v = resolve(url)
except:
data = []
data.append(('some','data'))
return simplejson.dumps(data)
dajaxice_functions.register(getContent)
I ran python manage.py collectstatic, and I get the following output:
Copying '/tmp/tmpm8OlOw'
However, the dajaxice.core.js generated does not have my function getContent at all. Where am I going wrong? I have dajaxice installed properly and everything, I hope.
Seems you forgot to call dajaxice_autodiscover() from urls.py (this is the place recommended by dajaxice author)
this call will load ajax.py module and make it's method discoverable by JS code generator
You need to register you function with dajaxice either using #dajaxice_register decorator or other methods mention in the documentation.
http://django-dajaxice.readthedocs.org/en/latest/quickstart.html#create-your-first-ajax-function