I know this is something dumb, but I'm a new programmer and I've been smacking my head against it for 2 hours and you will likely see it in 2 seconds so...
View AllEncountersListView which has declared template_name = 'encounter_list_all.html' is using instead 'encounter_list.html'. I know the view is being called since it prints to terminal as expected. Thanks for your time.
views.py:
class AllEncountersListView(generic.ListView):
model = Encounter
paginate_by = 20
template_name = 'encounters_list_all.html'
def get_queryset(self):
print('in allEncounterListView') #to prove the correct view is being called
return Encounter.objects.filter(user=self.request.user).order_by('-encounter_date')
urls.py:
urlpatterns = [
path('',views.index, name='index'),
path('openencounter/', views.open_encounter, name='openencounter'),
path('myencounters/', views.EncountersByUserListView.as_view(), name='my-encounters'),
path('allencounters/', views.AllEncountersListView.as_view(), name='all-encounters'),
path('encounter/<int:pk>', views.EncounterDetailView.as_view(), name = 'encounter-detail'),
path('todaysencounters/', views.TodaysEncountersListView.as_view(), name='todays-encounters'),
path('logout/', views.logout_view, name='logout'),
path('export/', views.export_data_view, name = 'export'),
]
file tree:
── Aents4
│ ├── __init__.py
│ ├── __pycache__
│ ├── asgi.py
│ ├── settings.py
│ ├── templates
│ │ ├── registration
│ │ │ └── login.html
│ │ └── temp
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── encounters
│ ├── __init__.py
│ ├── __pycache__
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20210926_1548.py
│ │ ├── 0003_alter_encounter_encounter_date.py
│ │ ├── 0004_auto_20210927_1704.py
│ │ ├── 0005_animal_max_daily.py
│ │ ├── 0006_auto_20210928_1157.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ ├── models.py
│ ├── registration
│ │ └── login.html
│ ├── static
│ │ └── styles.css
│ ├── templates
│ │ ├── base_generic.html
│ │ ├── encounters
│ │ │ ├── encounter_detail.html
│ │ │ ├── encounter_form.html
│ │ │ ├── encounter_list.html
│ │ │ ├── encounters_list_all.html
│ │ │ ├── encounter_update_form.html
│ │ │ └── encounters_list_by_user.html
│ │ ├── index.html
│ │ ├── openencounter.html
│ │ └── registration
│ │ └── login.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── manage.py
class AllEncountersListView(generic.ListView):
model = Encounter
paginate_by = 20
template_name = "encounters/encounters_list_all.html"
def get_queryset(self):
return Encounter.objects.filter(user=self.request.user).order_by('-encounter_date')
Try this please if you didn't already. Usually, when we are configuring our settings.py, we make it look in the templates directory for files, but you have subdirectory encounters which contain the template files. Try to target that subdirectory with this line:
template_name = "encounters/encounters_list_all.html"
I hope this helps; please inform us about result so we can try other solutions if needed.
Maybe it didn't throw any errors because the Django class views has that functionality such that when template name is not specified it looks at the class name and tries to figure out which template to render; maybe that is why that other template is being used. Check the Django documentation for more information.
Related
I just moved tests.py file to a new directory called tests, then I added __init__.py file therein, but as I run the test python manage.py test it says ran 0 tests in 0.000s. How to solve it?
I don't know how to show my files like most do, but here is an image!
This app is also added in settings.py
Thanks
edit:
this is a sample of test_models.py
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from django.urls import reverse
from board.models import Board
from board.views import board_topics
class HomeTest(TestCase):
def home_test_case(self):
url = reverse('home')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
class BoardTest(TestCase):
def setup(self):
Board.objects.create(title='Hello world',
description='My first Django app!')
def board_topics_status_code(self):
url = reverse('board_topics', kwargs={id: 1})
response = self.client.get(url)
return self.assertEqual(response.status_code, 200)
def board_topics_status_code_not_found(self):
url = reverse('board_topics', kwargs={id: 123})
response = self.client.get(url)
return assertEqual(response.status_code, 200)
def resolve_url_to_specific_fun(self):
url = resolve('board/1/')
return assertEqual(view.func, board_topics)
def HomeTests(TestCase):
def setUp(self):
self.board = Board.objects.create(
title='Django', description='Django Desc')
url = reverse('home')
self.response = self.client.get(url)
def home_test_view_status_code(self):
self.assertEqual(self.response.status_code, 200)
def home_test_func(self):
view = resolve('/')
self.assertEqual(view.func, home)
def test_home_contains_link_to_topics_page(self):
board_topics_url = reverse(
'board_topics', kwargs={'id': self.board.pk})
self.assertContains(self.response, 'href={0}'.format(board_topics_url))
All your tests must have the test_ prefix attached. Rename all your tests adding that to the name.
For example:
def test_board_topics_status_code(self):
url = reverse('board_topics', kwargs={id: 1})
response = self.client.get(url)
return self.assertEqual(response.status_code, 200)
Also, you need to change def HomeTests(TestCase): to class HomeTests(TestCase):, that's why your last test is named correctly but it is still not being discovered.
There are 2 ways you can keep your tests in your Project. I prefer the
1st one.
1. Your development code contains all of your tests. This way it's easier to add a new test when you write development code and your tests now ships with your development code.
Project
├── __init__.py
├── api
│ ├── v1
│ │ ├── tests
│ │ │ ├── __init__.py
│ │ │ ├── test_serializers.py
│ │ │ └── test_views.py
│ │ ├── __init__.py
│ │ ├── serializers.py
│ │ ├── urls.py
│ │ └── views.py
│ ├── v2
│ │ ├── tests
│ │ │ ├── __init__.py
│ │ │ ├── test_serializers.py
│ │ │ └── test_views.py
│ │ ├── __init__.py
│ │ ├── serializers.py
│ │ ├── urls.py
│ │ └── views.py
│ ├── __init__.py
│ ├── serializers.py
│ └── urls.py
├── models
│ ├── tests
│ │ ├── __init__.py
│ │ ├── test_data_structures.py
│ │ ├── test_miscellaneous_models.py
│ │ ├── test_models.py
│ ├── __init__.py
│ ├── models.py
│ ├── data_structures.py
│ └── miscellaneous_models.py
├── resume_handler
│ ├── tests
│ │ ├── __init__.py
│ │ ├── test_handlers.py
│ │ ├── test_managers.py
│ │ ├── test_parsers.py
│ │ ├── test_uploaders.py
│ │ └── test_validators.py
│ ├── __init__.py
│ ├── handlers.py
│ ├── managers.py
│ ├── parsers.py
│ ├── uploaders.py
│ └── validators.py
├── tasks
│ ├── tests
│ │ ├── __init__.py
│ │ └── test_tasks.py
│ ├── __init__.py
│ ├── general.py
│ └── model_tasks.py
├── tests
│ └── test_utils.py
└── utils.py
2. Another way is to put a test folder separate from the project folder. This test folder maintains the same hierarchy as of the project folder. This keeps the test code separate from the development code.
Project
├── api
│ ├── v1
│ │ └── more code files ...
│ ├── v2
│ │ └── more code files ...
│ └── v3
│ └── more code files ...
├── choices
├── constants
├── models
│ ├── data_filters
│ ├── querysets
│ └── more code files ...
├── resume_builder
│ └── more code files ...
├── resume_handler
│ └── more code files ...
├── tasks
│ └── more code files ...
└── more code files ...
Now in the same directory in which the Project folder is present create a test folder which maintains the same hierarchy but only contain the corresponding tests files.
test
├── api
│ ├── v1
│ │ └── test files ...
│ ├── v2
│ │ └── test files ...
│ └── v3
│ └── test files ...
├── choices
├── constants
├── models
│ ├── data_filters
│ ├── querysets
│ └── test files ...
├── resume_builder
│ └── test files ...
├── resume_handler
│ └── test files ...
├── tasks
│ └── test files ...
└── test files ...
I have a try except block in one of my Django view functions that will delete a User object that was created in the try block if anything should fail. When I attempt to delete the User I get this error message.
OperationalError: no such table: reversion_revision
The same issue happens in the Django admin as well. I am having issues finding similar cases of this OperationalError happening to other people, and am not sure why it is happening. All the other objects that I am deleting in the except block delete without any issues.
#csrf_exempt
def signup(request):
# """Register a new account with a new org."""
if request.is_ajax():
if request.method == "POST":
form = SignUp(requestPost(request))
if form.is_valid():
cleaned_data = form.cleaned_data
email = cleaned_data['email']
password = cleaned_data['password']
org_name = cleaned_data['org_name']
org_username = cleaned_data['org_username']
if cleaned_data['token']:
invite_token = cleaned_data['token']
else:
invite_token = cleaned_data['invite']
try:
account = Account.objects.create(email=email, password=password)
x = email[:30]
userExists = User.objects.filter(username=email[:30])
if not userExists:
if len(email) < 30:
user = User.objects.create_user(email, email, password)
else:
email = email[:30]
user = User.objects.create_user(email, email, password)
if invite_token:
if ThreadInvite.objects.filter(token=invite_token):
invitation = ThreadInvite.objects.get(token=invite_token)
thread = Thread.objects.get(id=invitation.thread.id)
ThreadMember.objects.create(thread=thread, account=account)
else:
invitation = OrgInvite.objects.get(token=invite_token)
if invitation.used:
raise Exception("invitation code is invalid")
org = Org.objects.get(id=invitation.org.id)
OrgMember.objects.create(org=org, account=account)
invitation.used = False
invitation.save()
add_to_welcome(org_id=org.id, account_id=account.id)
if org_username and org_name:
org = Org.objects.create(name=org_name, username=org_username,
actor=account)
OrgMember.objects.create(account=account, org=org)
Thread.objects.create(name='welcome', account=account, owner=account, org=org,
purpose='To welcome new members to the team.')
add_to_welcome(org_id=org.id, account_id=account.id)
login(request)
md = mandrill.Mandrill(settings.MANDRILL_API_KEY)
t = invite_token.replace(' ', '+')
url = "https://localhost:8000/verify/{}".format(t)
message = {
'global_merge_vars': [
{
'name': 'VERIFICATION_URL',
'content': url
},
],
'to': [
{
'email': 'tim#millcreeksoftware.biz',
},
],
'subject': 'Welcome to Human Link',
}
message['from_name'] = message.get('from_name', 'Humanlink')
message['from_email'] = message.get('from_email',
'support#humanlink.co')
try:
md.messages.send_template(
template_name='humanlink-welcome', message=message,
template_content=[], async=True)
except mandrill.Error as e:
logging.exception(e)
raise Exception(e)
context = {
'message': 'ok'
}
return composeJsonResponse(200, "", context)
except Exception, e:
logging.error(e)
Account.objects.filter(email=email, password=password).delete()
User.objects.filter(username=email[:30]).delete()
Org.objects.filter(name=org_name, username=org_username).delete()
Structure
├── account
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── apps.py
│ ├── forms.py
│ ├── forms.pyc
│ ├── migrations
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── tests.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── api_helpers.py
├── api_helpers.pyc
├── app
│ └── components
├── bower.json
├── bower_components
│ ├── angular
│ ├── angular-animate
│ ├── angular-bootstrap
│ ├── angular-cookies
│ ├── angular-messages
│ ├── angular-sanitize
│ ├── angular-scroll-glue
│ ├── angular-touch
│ ├── angular-ui-router
│ ├── bootstrap
│ ├── checklist-model
│ ├── font-awesome
│ ├── jquery
│ ├── moment
│ ├── pusher-websocket-iso
│ └── underscore
├── cron_tasks.py
├── gulpfile.js
├── logs
│ └── readme.txt
├── manage.py
├── message
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── forms.py
│ ├── forms.pyc
│ ├── migrations
│ ├── models.py
│ ├── models.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
|
├── org
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── forms.py
│ ├── forms.pyc
│ ├── migrations
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── tests.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── package.json
├── readme.txt
├── settings
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── base.py
│ ├── base.pyc
│ ├── cron.py
│ ├── development.py
│ ├── development.pyc
│ └── production.py
├── sqlite3
│ └── local.db
├── stylesheets
│ └── less
├── templates
│ ├── accounts
│ ├── admin
│ ├── dashboard
│ ├── footer.html
│ ├── home
│ ├── layouts
│ ├── nav.html
│ ├── pages
│ ├── settings
│ ├── shared
│ ├── site-alert.html
│ └── site.html
├── third_party
│ ├── classytags
│ ├── dateutil
│ ├── django_pusher
│ ├── itsdangerous.py
│ ├── itsdangerous.pyc
│ ├── mandrill.py
│ ├── mandrill.pyc
│ ├── mptt
│ ├── pusher
│ ├── requests
│ ├── reversion
│ ├── six.py
│ ├── six.pyc
│ ├── suit
│ └── werkzeug
├── utility.pyc
├── webapp
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── static
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ ├── views.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
└── webapp_admin
├── __init__.py
├── __init__.pyc
└── static
Problem here is not in your code but in your database state. Looks like you added django reversion app. Which adds new Models in your project. Run
python manage.py syncdb
or if you in 1.8+
python manage.py migrate
Update
If this doesn't help than there are no migrations for your 3rd-party app you need to first create them with
python manage.py makemigrations name_3rd_party_app
Be careful with creating migrations on 3rd-party apps. When you run makemigrations it creates migrations in 3rd-party app package. So it won't be in your code. And after you deploy it, or other user uses it there are will not be this migrations. So you need to supply custom path for created migrations with https://docs.djangoproject.com/en/1.9/ref/settings/#migration-modules
And then run migrate
Try running
./manage.py makemigrations revisions
then
./manage.py migrate
or just delete the db file and start over with
./manage.py migrate
I am getting a 'template not found' error, although I've set up a correct template hierarchy (or so I thought)
.
├── manage.py
├── twinja
│ ├── admin.py
│ ├── admin.pyc
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── migrations
│ │ ├── __init__.py
│ │ └── __init__.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ └── views.py
└── twinjasite
├── __init__.py
├── __init__.pyc
├── settings.py
├── settings.py~
├── settings.pyc
├── static
│ └── twinja
│ ├── fonts
│ │ └── bootstrap
│ │ ├── glyphicons-halflings-regular.eot
│ │ ├── glyphicons-halflings-regular.svg
│ │ ├── glyphicons-halflings-regular.ttf
│ │ ├── glyphicons-halflings-regular.woff
│ │ └── glyphicons-halflings-regular.woff2
│ ├── images
│ ├── javascripts
│ │ ├── bootstrap
│ │ │ ├── affix.js
│ │ │ ├── alert.js
│ │ │ ├── button.js
│ │ │ ├── carousel.js
│ │ │ ├── collapse.js
│ │ │ ├── dropdown.js
│ │ │ ├── modal.js
│ │ │ ├── popover.js
│ │ │ ├── scrollspy.js
│ │ │ ├── tab.js
│ │ │ ├── tooltip.js
│ │ │ └── transition.js
│ │ ├── bootstrap.js
│ │ ├── bootstrap.min.js
│ │ └── bootstrap-sprockets.js
│ └── stylesheets
│ ├── framework.css
│ └── styles.css
├── templates
│ └── twinja
│ ├── base.html
│ └── menu.html
├── urls.py
├── urls.py~
├── urls.pyc
├── views.py
├── views.py~
├── views.pyc
├── wsgi.py
└── wsgi.pyc
At first I set up templates/base but that did not work. So I made it as you see here: templates/twinja/base
Ideally I'm setting up the MAIN template files which are independent of apps, which I thought was meant to go in the main folder (where settings.py is) but perhaps I am mistake.
Yes, I have 'twinja' set up in installed apps as well.
What appears to be wrong here?
TemplateDoesNotExist at /
twinja/base.html
If your template is independent of apps, it shouldn't be in your app folder - namespace it accordingly.
How do you load your template? Did you setup your templates/staticfolders in your settings.py?
Updated.
For the fresh project you need to configure your settings.py file. Read here, ask away if you still have a question.
Updated.
After you get familiar with static files and how to manage those, spend some time here.
I have been working on the issue of duplicate labels in Django and from this answer I have added the following files to my "jobs" project folder:
jobs/apps.py
# jobs/apps.py
from django.apps import AppConfig
class JobsConfig(AppConfig):
name = 'jobs'
verbose_name = "jobs2"
jobs/init.py
# jobs/__init__.py
default_app_config = 'jobs.apps.JobsConfig'
This hasn't really helped much and I still get the error when trying syncdb:
"duplicates: %s" % app_config.label)
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: jobs
Also, changing from "name = 'jobs'" to "name = 'jobs2'" just gives me the error:
ImportError: No module named jobs2
File Structure
/opt/Webapp
├── userfiles
├── templates
│ └── admin
│ └── base.html
├── static
│ ├── admin_tools
│ │ ├── images
│ │ │ └── apto.gif
│ │ └── css
│ │ └── theming.css
│ └── admin
│ └── css
│ └── base.css
├── smartrecruitment
│ ├── wsgi.py
│ ├── urls.py
│ ├── settings.pyc
│ ├── settings.py
│ ├── __init__.pyc
│ └── __init__.py
├── requirements.txt
├── manage.py
├── jobs
│ ├── views.py
│ ├── urls.py
│ ├── tests.py
│ ├── testhelpers.py
│ ├── templates
│ │ └── jobs
│ │ ├── test.html
│ │ ├── success.html
│ │ ├── registration.html
│ │ ├── registrationcomplete.html
│ │ └── application.html
│ ├── tables.py
│ ├── static
│ │ └── jobs
│ │ ├── styles
│ │ │ ├── index.css
│ │ │ ├── hide_admin_original.css
│ │ │ └── application.css
│ │ ├── style.css
│ │ └── images
│ │ └── apto.gif
│ ├── models.py
│ ├── migrations
│ │ ├── __init__.py
│ │ ├── 0002_auto__del_field_registrant_name__add_field_registrant_first_name__add_.py
│ │ └── 0001_initial.py
│ ├── lists.py
│ ├── __init__.pyc
│ ├── __init__.py
│ ├── forms.py
│ ├── apps.pyc
│ ├── apps.py
│ └── admin.py
├── fileuploads
│ ├── tests.py
│ ├── templates
│ │ └── fileuploads
│ │ ├── index.html
│ │ ├── details.html
│ │ ├── base.html
│ │ └── add.html
│ ├── models.pyc
│ ├── models.py
│ ├── __init__.pyc
│ ├── __init__.py
│ ├── forms.pyc
│ ├── forms.py
│ ├── context_processors.py
│ └── admin.pyc
├── dashboard.pyc
└── dashboard.py
You have a mix of old-style (south: 0002_auto_del...) and new-style (django: 0001_initial) migrations in your jobs app. Easiest fix would be to delete all numbered migrations rm jobs/migrations/0???_*.py* and recreate migrations by running manage.py makemigrations
I am trying to serve my Django project, set up with django-skel 1.4, using the development server. My site runs as expected except for my images, they are not served.
Part of templates/home.html
<img width="65px;" src="assets/img/pic.png" alt="" id="symbol" />
I'm guessing I should change something in this part: src="assets/img/pic.png".
I've looked around in SO threads and tweaked according to the given answers but I could not manage to make it work.
So how do I properly set images in templates?
Other relevant information:
settings.common.py
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
MEDIA_ROOT = normpath(join(DJANGO_ROOT, 'media'))
MEDIA_URL = '/media/'
STATIC_ROOT = normpath(join(DJANGO_ROOT, 'static'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
normpath(join(DJANGO_ROOT, 'assets')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
Tree of project
.
├── apps
│ └── __init__.py
├── assets
│ ├── css
│ │ └── base.css
│ ├── img
│ │ └── pic.png
│ └── js
├── default.db
├── __init__.py
├── libs
│ ├── core
│ │ ├── admin.py
│ │ ├── __init__.py
│ │ ├── models.py
│ │ ├── views.py
│ │ └── views.pyc
│ └── __init__.py
├── settings
│ ├── common.py
│ ├── dev.py
│ ├── __init__.py
│ └── prod.py
├── templates
│ ├── 404.html
│ ├── 500.html
│ ├── home.html
│ └── install.html
└── urls.py
Btw: Please no solutions using if settings.DEBUG, preferably if possible without needing to adapt urls.py.
Edit
Tree of the top level directory after doing collectstatic
.
├── fabfile.py
├── gunicorn.py.ini
├── manage.py
├── Procfile
├── project_name
│ ├── apps
│ │ └── __init__.py
│ ├── assets
│ │ ├── css
│ │ │ └── base.css
│ │ ├── img
│ │ │ └── pic.png
│ │ └── js
│ ├── default.db
│ ├── __init__.py
│ ├── libs
│ │ ├── core
│ │ │ ├── admin.py
│ │ │ ├── __init__.py
│ │ │ ├── models.py
│ │ │ └── views.py
│ │ └── __init__.py
│ ├── settings
│ │ ├── common.py
│ │ ├── dev.py
│ │ ├── __init__.py
│ │ └── prod.py
│ ├── static
│ │ │ └── js
│ │ ├── css
│ │ │ └── base.css
│ │ └── img
│ │ └── pic.png
│ ├── templates
│ │ ├── 404.html
│ │ ├── 500.html
│ │ ├── home.html
│ │ └── install.html
│ └── urls.py
├── README.md
├── reqs
│ ├── common.txt
│ ├── dev.txt
│ └── prod.txt
├── requirements.txt
└── wsgi.py
Edit 2
My understanding how Django reads the path:
Let src="static/img/pic.png", from my settings.common.py:
>>> DJANGO_ROOT
'/home/my_username/web/my_project/my_project'
>>> j = os.path.join(DJANGO_ROOT, 'static/')
>>> print j
/home/my_username/web/my_project/my_project/static
But
>>> STATIC_URL
'/static/'
>>> j = os.path.join(DJANGO_ROOT, STATIC_URL)
>>> print j
/static/
So somewhere Django probably does os.path.join that is the only reason I can think of why
src="static/img/pic.png" works but src="{{STATIC_URL}}img/pic.png" doesn't. But why then does this apparently work for other people but not for me?
I think you have to add the following to urls.py
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
at least thats how I always do it...
You need to add
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
)
and add staticfiles to your INSTALLED_APPS
You need to modify your img tag
<img width="65px;" src="{{STATIC_URL}}assets/img/pic.png" alt="" id="symbol" />
If it is user uploaded content then replace {{STATIC_URL}} with {{MEDIA_URL}}
Also see related Django cannot find my media files (on development server)