When I deploy my django app in azure with sql database, it is showing me The page cannot be displayed because an internal server error has occurred.
But when I deploy it without sql database it works fine. What is the problem?
error log
Most likely causes:
IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.
IIS was not able to process configuration for the Web site or application.
The authenticated user does not have permission to use this DLL.
The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.
I tried to reproduce your issue but failed. I deploy my django app to azure with sqlserver database by using django-mssql successfully.
Please refer to the steps I did:
Step 1: Add configuration in settings.py
DATABASES = {
'default': {
'NAME': '***',
'ENGINE': 'sqlserver_ado',
'HOST': '***.database.windows.net',
'USER': '***',
'PASSWORD': '***',
'OPTIONS': {
'provider': 'SQLOLEDB',
'use_legacy_date_fields': 'True'
}
}
}
Step 2: Add test code to query results:
from django.db import connection
def my_custom_sql():
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM ***")
row = cursor.fetchone()
return row
Step 3: Install django-mssql package and dependency on KUDU.
Step 4: Deploy django app to azure and access url in browser.
Hope it helps you.
Update Answer:
Firstly , the error as below when you tried to build django with django-mssql because your version of django is too high.
From the django-mssql doc , you could see : Django 1.8 is supported by the current release and your django version is 1.11.8.
Secondly, the django-pyodbc package which you mentioned in your comment just supports django 1.10. You could refer to this doc.
So, I suggest you to use django-pyodbc-azure package which supports django 1.11 by now.
You could follow the tutorial in above doc.
Configuration in settings.py
DATABASES = {
'default': {
'NAME': '***',
'ENGINE': 'sql_server.pyodbc',
'HOST': '***.database.windows.net',
'USER': '***',
'PASSWORD': '***',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
}
}
}
My django version is as same as you and it works for me.
Any concern please let me know.
Update Answer2 :
I just used Visual Studio 2017 python django template.
My view.py :
"""
Definition of views.
"""
from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime
from django.db import connection
def my_custom_sql():
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM dbo.student")
row = cursor.fetchone()
return row
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/index.html',
{
'title':'Home Page',
'year':datetime.now().year,
}
)
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
{
'title':'Contact',
'message':'Your contact page.',
'year':datetime.now().year,
}
)
def about(request):
row = my_custom_sql()
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
{
'title': row,
'message':'Your application description page.',
'year':datetime.now().year,
}
)
Please note the my_custom_sql() function.
My about.html:
{% extends "app/layout.html" %}
{% block content %}
<h2>{{ title }}.</h2>
<h3>{{ message }}</h3>
<p>Test Something!</p>
{% endblock %}
And the pyodbc settings in the settings.py just refer to my previous update answer.
Please enable Diagnostics Logging for debugging your application and determine the real cause of your application is not working. This blog post may also help you troubleshooting-logging your application.
Related
This question already has an answer here:
Django: Detect database backend
(1 answer)
Closed 3 years ago.
I'm hoping this will be similar to a few questions which have been previously answered.
I was wondering what the full processes are for testing the DB connection string (not the DB name) for the current connected DB in Django is? I see a few methods for printing the name, but across local development and staging, these names will be the same. I need to know more, such as the db engine (e.g., is it PostgreSQL, or is it db.sqlite3. etc etc), and various other DB parameters.
I'm currently trying to debug why a Celery beat task is failing to create database entries for the application DB I think I am connected to.
I'm performing a simple obj, created = Object.objects.get_or_create() DB method, and on logging created, some are True and some are False. All good so far.
However, the admin section of the Django CMS is not showing any more entries to the DB.
I believe testing the location and connection strings of the DB the Django application is using might be useful in debugging this ghost object creation...unless someone can advise on similar issues they have had with the Celery daemon not actually persisting a DB create/update etc...
Perhaps, something such as:
from django.db import connection
print(connection.settings_dict)
Would be sufficient?
So, the following was useful for determining the DB engine:
from django.db import connection
print(connection.settings_dict)
For useful guidance, the connection.settings_dict contains the following structure:
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/usr/src/app/db.sqlite3',
'ATOMIC_REQUESTS': False,
'AUTOCOMMIT': True,
'CONN_MAX_AGE': 0,
'OPTIONS': {},
'TIME_ZONE': None,
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
'TEST': {
'CHARSET': None,
'COLLATION': None,
'NAME': None,
'MIRROR': None
}
}
So, we could work with something like this in a management command:
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Displays The Currently Connected DB Settings'
def handle(self, *args, **kwargs):
print(
"The current database engine is {ENGINE}".format(**connection.settings_dict)
)
print(
"Currently connected to host {HOST} on port {PORT} ".format(**connection.settings_dict)
)
I'm having a strange problem that is difficult to reproduce (everything worked 2 days ago but some time between then and now no longer does--with no changes in the interim!)
I have a django server program which we are running via gunicorn with multiple worker subprocesses and a separate small REST webservice which shares the settings.py of the server program and acts on the same DB objects. The code for this server program is roughly as follows:
# my app's models.py
class TestConfig(models.Model):
## various attributes
class Test(models.Model):
## some attributes
def startTest(self):
return TestExecution.objects.create(test=self)
class TestExecution(models.Model):
test = models.ForeignKey(
Test,
on_delete=models.CASCADE
)
config = models.ForeignKey(
TestConfig,
on_delete=models.CASCADE,
null=True
)
# excerpt from a post() method in my app's views.py
test = Test.objects.get(test_id)
if config_form.is_valid():
config = config_form.save()
config_id = config.id
test_exe = test.startTest()
test_exe.config = config
test_exe.save()
webservice_response = requests.get(
'http://{}:{}/rest/add_to_queue/{}'.format(
webservice_ip, webservice_port, test_exe.id))
The other program (small REST webservice) sharing the same settings.py as the django server program looks as follows:
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
import django
django.setup()
# the REST endpoint referenced from the django server program
#app.route('/rest/add_to_queue/<test_exe_object_id>/')
#app.route('/rest/add_to_queue/<test_exe_object_id>')
def add_to_queue(test_exe_object_id):
from myapp.models import TestExecution
try:
exe_object = TestExecution.objects.get(pk=int(test_exe_object_id))
# for completeness the database section of my settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
As I mentioned, this was all working fine a few days ago, then when I tried again today I was getting a DoesNotExist in the second program when trying to "get()" the TestExecution object using its 'id'.
I'm new in django and trying to connect to my heroku database from my localhosted django app.
I've followed the instructions on heroku website but it's seems django won't understand that i'm trying to access an external database.
i get this error
relation "myAppName_user" does not exist
LINE 1: INSERT INTO "myAppName_user" ("title", "content") VALUES
('Beat...
However i never created or never intented to create a table named myAppName_user
I'm just trying to access the table user in my heroku postgres db but i don't know why it tries with myAppName_user
i just explicitly added myAppName in the INSTALLED_APPS config as django throws an error if it's not the case.
My DATABASE config :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASES['default'] =
dj_database_url.config(default='postgres://xxxxx')
I want to test my database from my localhost. I'm doing this easily with Node JS but i can't find the solution in django.
Any suggestions ?
EDIT
from __future__ import unicode_literals
from django.db import models
class Fruits(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.name
I am building a Django website and I am using Selenium to test my pages. My problem is that when I run the tests, the browser is launched, but no page is loaded or even attempted to be loaded. It just opens blank and the tests hang. It seems to me that the liveserver doesn't get started. I am running on Apache2 and WSGI, but my understanding is that the Selenium tests are run by the the Django's built-in web server. Any idea what could be wrong? The relevant files are below:
tests.py:
from selenium.webdriver.firefox.webdriver import WebDriver
class MyProjectLiveServerTestCase(LiveServerTestCase):
#classmethod
def initSeleniumDriver(cls):
cls.driver = WebDriver()
#classmethod
def closeSeleniumDriver(cls):
cls.driver.quit()
def testIndexShouldLoad(self):
self.driver.get('%s%s' % (self.live_server_url, '/nd5/mybook/'))
self.assertEqual(len(self.driver.find_elements(
By.CSS_SELECTOR,
'span#copyright'
)), 1)
settings.py:
# Test database runs on SQLite
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(os.path.realpath(os.path.dirname(__file__)), '..', 'myprojectdb'),
}
}
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
I am using django-nose, so I execute the tests this way:
python manage.py test --exe
Please, let me know if you need to see any other parts of the code.
UPDATE:
Here is update: I found out that the reason Firefox doesn't load the page is because my version of Firefox is newer than the latest version supported by Selenium. So I switched to Chrome and now the URL in the browser is requested. However, the page isn't found (404 error). This must mean that the liveserver is still not running. My tests don't turn on the liveserver when they get run. Any idea why? The port isn't blocked - I checked.
I think you forgot to select webdriver to use:
class SomethingTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(2)
def tearDown(self):
self.browser.quit()
def test_user_can_log_in(self):
self.browser.get(self.live_server_url + reverse('something'))
self.fail('write rest of the test')
This probably wasn't your problem, but what bit me was that LiveServerTestCase starts the server thread from setUpClass, which I'd defined without calling super(MyProjectLiveServerTestCase, self).setUpClass().
So Ive managed to screw something up between my production database settings for heroku.
Running the production settings locally I receive the error,
ImproperlyConfigured at /
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
And I get the following error when deployed to Heroku seen here: http://tulsa-staging.herokuapp.com
Exception Value:
cannot concatenate 'str' and 'NoneType' objects
It appears that it has to do with my Database settings but I'm just not sure how to resolve this.
prod.py database settings for Heroku
urlparse.uses_netloc.append('postgres')
urlparse.uses_netloc.append('mysql')
try:
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
DATABASES = {
'default':{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port
}
}
except Exception:
print 'Unexpected error:', sys.exc_info()
Any thoughts on how to resolve this?
Why aren't you using dj-database-url?
It makes this so much easier:
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
It automatically looks for and parses the value in env['DATABASE_URL'], falling back to what you pass into default.
It's what Heroku actually recommends you use.