class 'psycopg2.InterfaceError': connection already closed - django

I am pulling my hair over this and am about ready to do something dirty.
I am running nginx + django + postgresql. Half the time I am trying to test my site and open a page, I get the following:
<class 'psycopg2.InterfaceError'> Python 2.7.2: /home/webapp/newavenue/bin/python
Fri Feb 24 08:28:58 2012
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/home/webapp/newavenue/lib/python2.7/site-packages/flup/server/fcgi_base.py in run(self=<flup.server.fcgi_base.Request object>)
572
573 try:
=> 574 protocolStatus, appStatus = self.server.handler(self)
575 except:
576 traceback.print_exc(file=self.stderr)
protocolStatus undefined, appStatus undefined, self = <flup.server.fcgi_base.Request object>, self.server = <flup.server.fcgi_fork.WSGIServer object>, self.server.handler = <bound method WSGIServer.handler of <flup.server.fcgi_fork.WSGIServer object>>
/home/webapp/newavenue/lib/python2.7/site-packages/flup/server/fcgi_base.py in handler(self=<flup.server.fcgi_fork.WSGIServer object>, req=<flup.server.fcgi_base.Request object>)
1157 try:
1158 try:
=> 1159 result = self.application(environ, start_response)
1160 try:
1161 for data in result:
result = None, self = <flup.server.fcgi_fork.WSGIServer object>, self.application = <django.core.handlers.wsgi.WSGIHandler object>, environ = {'CONTENT_LENGTH': '', 'CONTENT_TYPE': '', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_COOKIE': 'csrftoken=8a0176b368b17af00a8563b5f95b134b; sess...e5bdd0d0a4e3092e7a9abd0029c02; django_language=en', 'HTTP_HOST': 'newavedev.zapto.org', ...}, start_response = <function start_response>
/home/webapp/newavenue/lib/python2.7/site-packages/django/core/handlers/wsgi.py in __call__(self=<django.core.handlers.wsgi.WSGIHandler object>, environ={'CONTENT_LENGTH': '', 'CONTENT_TYPE': '', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_COOKIE': 'csrftoken=8a0176b368b17af00a8563b5f95b134b; sess...e5bdd0d0a4e3092e7a9abd0029c02; django_language=en', 'HTTP_HOST': 'newavedev.zapto.org', ...}, start_response=<function start_response>)
272 response = self.get_response(request)
273 finally:
=> 274 signals.request_finished.send(sender=self.__class__)
275
276 try:
global signals = <module 'django.core.signals' from '/home/webapp...python2.7/site-packages/django/core/signals.pyc'>, signals.request_finished = <django.dispatch.dispatcher.Signal object>, signals.request_finished.send = <bound method Signal.send of <django.dispatch.dispatcher.Signal object>>, sender undefined, self = <django.core.handlers.wsgi.WSGIHandler object>, self.__class__ = <class 'django.core.handlers.wsgi.WSGIHandler'>
/home/webapp/newavenue/lib/python2.7/site-packages/django/dispatch/dispatcher.py in send(self=<django.dispatch.dispatcher.Signal object>, sender=<class 'django.core.handlers.wsgi.WSGIHandler'>, **named={})
170
171 for receiver in self._live_receivers(_make_id(sender)):
=> 172 response = receiver(signal=self, sender=sender, **named)
173 responses.append((receiver, response))
174 return responses
response undefined, receiver = <function close_connection>, signal undefined, self = <django.dispatch.dispatcher.Signal object>, sender = <class 'django.core.handlers.wsgi.WSGIHandler'>, named = {}
/home/webapp/newavenue/lib/python2.7/site-packages/django/db/__init__.py in close_connection(**kwargs={'sender': <class 'django.core.handlers.wsgi.WSGIHandler'>, 'signal': <django.dispatch.dispatcher.Signal object>})
83 def close_connection(**kwargs):
84 for conn in connections.all():
=> 85 conn.close()
86 signals.request_finished.connect(close_connection)
87
conn = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object>, conn.close = <bound method DatabaseWrapper.close of <django.d...postgresql_psycopg2.base.DatabaseWrapper object>>
/home/webapp/newavenue/lib/python2.7/site-packages/django/db/backends/__init__.py in close(self=<django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object>)
242 def close(self):
243 if self.connection is not None:
=> 244 self.connection.close()
245 self.connection = None
246
self = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object>, self.connection = <connection object at 0x1d37130; dsn: 'dbname=ne...er=postgres host=localhost port=5432', closed: 2>, self.connection.close = <built-in method close of psycopg2._psycopg.connection object>
<class 'psycopg2.InterfaceError'>: connection already closed
args = ('connection already closed',)
cursor = None
message = 'connection already closed'
pgcode = None
pgerror = None
The server is run with the following to generate the preceding flup traceback report:
python manage.py runfcgi host=127.0.0.1 port=8000 debug=False
Could I just get around this by patching in something like: "try: self.connection.close(), except: pass" around that offending line? It would probably work but I think it sounds dirty (messing with core) and I would like to try to find an alternative solution.
Edit: Considering this guy's approach too: commenting it out: http://osdir.com/ml/DjangoUsers/2009-04/msg01647.html

I think I got around the problem. This is not really a solution to the flup-psycopg2 setup but a sidestepping alternative. I switched from using fcgi to gunicorn and also wrapped the self.connection.close() line with "try: self.connection.close(), except: pass". This also solved a 502 Bad Gateway problem I was having with nginx.
Also, it seems my site runs a little faster, which is always a sweet side effect.

Related

ValidationException in Sagemaker pipeline creation

I am new to Sagmaker. I am creating a pipeline in sagemaker where I initialize the number of epochs as a pipeline parameter. But when I upsert, it shows this error.
Check the following code for reference, please.
epoch_count = ParameterInteger(name="EpochCount", default_value=1)
pipeline = Pipeline(
name=f"a_name",
parameters=[
training_instance_type,
training_instance_count,
epoch_count,
hugging_face_model_name,
endpoint_instance_type,
endpoint_instance_type_alternate,
],
steps=[step_train, step_register, step_deploy_lambda],
sagemaker_session=sagemaker_session,
)
Error - ---
---------------------------------------------------------------------------
ClientError Traceback (most recent call last)
<ipython-input-54-138a517611f0> in <module>
----> 1 pipeline.upsert(role_arn=role)
/opt/conda/lib/python3.7/site-packages/sagemaker/workflow/pipeline.py in upsert(self, role_arn, description, tags, parallelism_config)
217 """
218 try:
--> 219 response = self.create(role_arn, description, tags, parallelism_config)
220 except ClientError as e:
221 error = e.response["Error"]
/opt/conda/lib/python3.7/site-packages/sagemaker/workflow/pipeline.py in create(self, role_arn, description, tags, parallelism_config)
119 Tags=tags,
120 )
--> 121 return self.sagemaker_session.sagemaker_client.create_pipeline(**kwargs)
122
123 def _create_args(
/opt/conda/lib/python3.7/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
389 "%s() only accepts keyword arguments." % py_operation_name)
390 # The "self" in this scope is referring to the BaseClient.
--> 391 return self._make_api_call(operation_name, kwargs)
392
393 _api_call.__name__ = str(py_operation_name)
/opt/conda/lib/python3.7/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
717 error_code = parsed_response.get("Error", {}).get("Code")
718 error_class = self.exceptions.from_code(error_code)
--> 719 raise error_class(parsed_response, operation_name)
720 else:
721 return parsed_response
ClientError: An error occurred (ValidationException) when calling the CreatePipeline operation: Cannot assign property reference [Parameters.EpochCount] to argument of type [String]
I replace
epoch_count = ParameterInteger(name="EpochCount", default_value=1)
with
epoch_count = ParameterString(name="EpochCount", default_value="1")
And it works. Maybe we can only use an integer in pipeline parameters from the sagemaker notebook. But epoch_count is being used in the docker container, which is not directly something of Sagemaker, and that's my understanding.

Django queryset count() method raise "TypeError: unorderable types: NoneType() > int()"

My environment is Python3.5, Django1.8.3 and cx_Oracle5.3(They are checked by pip3 freeze).
Django query set raises a Type Error exception when count() method is called.
When it comes to Python2 + cx_oracle or Python3 + sqlite3 works fine without any exception but Python3 + cx_oracle.
Thue, I tried to update cx_Oracle version to 6.1(latest version) because I thought I could be some compatibility problem between cx_Oracle and Python3. However, It generates a different error.
I detail with the below code block, please refer it.
P.S: I Need to keep Django version to 1.8.3 for compatibility with my Apps.
models.py
from django.db import models
class Device(models.Model):
deviceClass = models.CharField(max_length=10)
class Meta:
db_table = 'TST_G2S_DEVICE'
cx_Oracle5.3
$ python3 manage.py shell
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
Type "copyright", "credits" or "license" for more information.
IPython 2.4.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: from polls.models import Device;
In [2]: dev = Device.objects.all()
In [3]: dev
Out[3]: []
In [4]: type(dev)
Out[4]: django.db.models.query.QuerySet
In [5]: dev.count()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-72a7bdf9f7f7> in <module>()
----> 1 dev.count()
/usr/local/lib/python3.5/dist-packages/django/db/models/query.py in count(self)
316 return len(self._result_cache)
317
--> 318 return self.query.get_count(using=self.db)
319
320 def get(self, *args, **kwargs):
/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py in get_count(self, using)
462 obj = self.clone()
463 obj.add_annotation(Count('*'), alias='__count', is_summary=True)
--> 464 number = obj.get_aggregation(using, ['__count'])['__count']
465 if number is None:
466 number = 0
/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py in get_aggregation(self, using, added_aggregate_names)
443 outer_query.select_related = False
444 compiler = outer_query.get_compiler(using)
--> 445 result = compiler.execute_sql(SINGLE)
446 if result is None:
447 result = [None for q in outer_query.annotation_select.items()]
/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py in execute_sql(self, result_type)
838 if result_type == SINGLE:
839 try:
--> 840 val = cursor.fetchone()
841 if val:
842 return val[0:self.col_count]
/usr/local/lib/python3.5/dist-packages/django/db/utils.py in inner(*args, **kwargs)
102 def inner(*args, **kwargs):
103 with self:
--> 104 return func(*args, **kwargs)
105 return inner
106
/usr/local/lib/python3.5/dist-packages/django/db/backends/oracle/base.py in fetchone(self)
507 if row is None:
508 return row
--> 509 return _rowfactory(row, self.cursor)
510
511 def fetchmany(self, size=None):
/usr/local/lib/python3.5/dist-packages/django/db/backends/oracle/base.py in _rowfactory(row, cursor)
575 # This comes from FloatField columns.
576 value = float(value)
--> 577 elif precision > 0:
578 # NUMBER(p,s) column: decimal-precision fixed point.
579 # This comes from IntField and DecimalField columns.
TypeError: unorderable types: NoneType() > int()
cx_Oracle6.1
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
Type "copyright", "credits" or "license" for more information.
IPython 2.4.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: from polls.models import Device;
In [2]: dev = Device.objects.all()
In [3]: dev
Out[3]: <repr(<django.db.models.query.QuerySet at 0x7f0ab12e8fd0>) failed: AttributeError: 'cx_Oracle.Cursor' object has no attribute 'numbersAsStrings'>
In [4]: type(dev)
Out[4]: django.db.models.query.QuerySet
In [5]: dev.count()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-72a7bdf9f7f7> in <module>()
----> 1 dev.count()
/usr/local/lib/python3.5/dist-packages/django/db/models/query.py in count(self)
316 return len(self._result_cache)
317
--> 318 return self.query.get_count(using=self.db)
319
320 def get(self, *args, **kwargs):
/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py in get_count(self, using)
462 obj = self.clone()
463 obj.add_annotation(Count('*'), alias='__count', is_summary=True)
--> 464 number = obj.get_aggregation(using, ['__count'])['__count']
465 if number is None:
466 number = 0
/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py in get_aggregation(self, using, added_aggregate_names)
443 outer_query.select_related = False
444 compiler = outer_query.get_compiler(using)
--> 445 result = compiler.execute_sql(SINGLE)
446 if result is None:
447 result = [None for q in outer_query.annotation_select.items()]
/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py in execute_sql(self, result_type)
825 return
826
--> 827 cursor = self.connection.cursor()
828 try:
829 cursor.execute(sql, params)
/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py in cursor(self)
160 self.validate_thread_sharing()
161 if self.queries_logged:
--> 162 cursor = self.make_debug_cursor(self._cursor())
163 else:
164 cursor = self.make_cursor(self._cursor())
/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py in _cursor(self)
135 self.ensure_connection()
136 with self.wrap_database_errors:
--> 137 return self.create_cursor()
138
139 def _commit(self):
/usr/local/lib/python3.5/dist-packages/django/db/backends/oracle/base.py in create_cursor(self)
260
261 def create_cursor(self):
--> 262 return FormatStylePlaceholderCursor(self.connection)
263
264 def _commit(self):
/usr/local/lib/python3.5/dist-packages/django/db/backends/oracle/base.py in __init__(self, connection)
417 self.cursor = connection.cursor()
418 # Necessary to retrieve decimal values without rounding error.
--> 419 self.cursor.numbersAsStrings = True
420 # Default arraysize of 1 is highly sub-optimal.
421 self.cursor.arraysize = 100
AttributeError: 'cx_Oracle.Cursor' object has no attribute 'numbersAsStrings'
Unfortunately for you, your restriction of staying on django 1.8 will not fix this issue.
This github issue describes the same situation you've encountered, with a very similar stack trace. A fix has been implemented in Django, but it apparently affects only 1.11 and forward releases, with no backport to 1.8 for the reason
This patch isn't completely compatible with cx_Oracle < 5.2, hence it
won't be backport to Django < 1.11

python 2 code VS python 3 ,zoho crm api [duplicate]

I am trying to convert working Python 2.7 code into Python 3 code and I am receiving a type error from the urllib request module.
I used the inbuilt 2to3 Python tool to convert the below working urllib and urllib2 Python 2.7 code:
import urllib2
import urllib
url = "https://www.customdomain.com"
d = dict(parameter1="value1", parameter2="value2")
req = urllib2.Request(url, data=urllib.urlencode(d))
f = urllib2.urlopen(req)
resp = f.read()
The output from the 2to3 module was the below Python 3 code:
import urllib.request, urllib.error, urllib.parse
url = "https://www.customdomain.com"
d = dict(parameter1="value1", parameter2="value2")
req = urllib.request.Request(url, data=urllib.parse.urlencode(d))
f = urllib.request.urlopen(req)
resp = f.read()
When the Python 3 code is run the following error is produced:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-56-206954140899> in <module>()
5
6 req = urllib.request.Request(url, data=urllib.parse.urlencode(d))
----> 7 f = urllib.request.urlopen(req)
8 resp = f.read()
C:\Users\Admin\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
159 else:
160 opener = _opener
--> 161 return opener.open(url, data, timeout)
162
163 def install_opener(opener):
C:\Users\Admin\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
459 for processor in self.process_request.get(protocol, []):
460 meth = getattr(processor, meth_name)
--> 461 req = meth(req)
462
463 response = self._open(req, data)
C:\Users\Admin\Anaconda3\lib\urllib\request.py in do_request_(self, request)
1110 msg = "POST data should be bytes or an iterable of bytes. " \
1111 "It cannot be of type str."
-> 1112 raise TypeError(msg)
1113 if not request.has_header('Content-type'):
1114 request.add_unredirected_header(
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
I have also read two other tickets (ticket1 and ticket2) which mentioned encoding the date.
When I changed the line f = urllib.request.urlopen(req) to f = urllib.request.urlopen(req.encode('utf-8')) I received the following error: AttributeError: 'Request' object has no attribute 'encode'
I am stuck as to how to make the Python 3 code work. Could you please help me?
From the docs Note that params output from urlencode is encoded to bytes before it is sent to urlopen as data:
data = urllib.parse.urlencode(d).encode("utf-8")
req = urllib.request.Request(url)
with urllib.request.urlopen(req,data=data) as f:
resp = f.read()
print(resp)
Try this:
url = 'https://www.customdomain.com'
d = dict(parameter1="value1", parameter2="value2")
f = urllib.parse.urlencode(d)
f = f.encode('utf-8')
req = urllib.request.Request(url, f)
Your problem lies in the way you were handling the dictionary.
I used python requests module with ZOHO CRM API V2. It worked without any issues.
Here is a sample working code with GET request:
import json
import requests
# API methods - https://www.zoho.com/crm/developer/docs/api/api-methods.html
# getrecords API Call
module_name = 'Deals'
authtoken = '*****'
api_url = "https://crm.zoho.com/crm/private/json/"+module_name+"/getRecords?authtoken="+authtoken+"&scope=crmapi&fromIndex=1&toIndex=2"
# GET Request
request_response = requests.get(
url=api_url
)
print(json.dumps(json.loads(request_response.text), sort_keys=True, indent=4, separators=(",", ": ")))
json_response = json.loads(request_response.text)

Python Kombu consumer get queue message but the callback can't trigger

If I run followed code, I found I can get message from the queue, but the callback can't triggered
from kombu.mixins import ConsumerMixin
from kombu import Exchange, Queue
task_exchange = Exchange('nginx', type='direct')
task_queues = [Queue(exchange=task_exchange, routing_key='nginx')]
class Worker(ConsumerMixin):
def __init__(self, connection):
self.connection = connection
def get_consumers(self, Consumer, channel):
return [Consumer(queues=task_queues,
callbacks=[self.task]
)]
def task(self, body, message):
print body
message.ack()
if __name__ == '__main__':
from kombu import Connection
with Connection('amqp://test:test#localhost:5672/test') as conn:
worker = Worker(conn)
worker.run()
I try to run python -m pdb test.py
170 -> def run(self, _tokens=1):
171 restart_limit = self.restart_limit
172 errors = (self.connection.connection_errors +
173 self.connection.channel_errors)
174 while not self.should_stop:
175 try:
(Pdb) l
176 if restart_limit.can_consume(_tokens):
177 for _ in self.consume(limit=None): # pragma: no cover
178 pass
179 else:
180 sleep(restart_limit.expected_time(_tokens))
181 except errors:
182 warn(W_CONN_LOST, exc_info=1)
It loop at
for _ in self.consume(limit=None): # pragma: no cover
pass
Runpython -m pdb test.py, Get in the connection.drain_events(), found the content.body encoding is binary,
if (content and
309 channel.auto_decode and
310 hasattr(content, 'content_encoding')):
311 -> try:
312 content.body = content.body.decode(content.content_encoding) #here get a error
313 except Exception:
314 pass
fix it
def get_consumers(self, Consumer, channel):
return [Consumer(queues=task_queues,
accept=['json', 'pickle'],
callbacks=[self.task]
)]

Django REST Framework tutorial, OperationalError: table snippets_snippet has no column named owner_id

Before I get the obvious response, about checking the database, itself, I'll start by saying that I've already checked out this post, which has a nearly identical setup to mine, and the solutions of deleting the database and migrations, and adding a default value in the table did not work, as expected. I do, however, expect the solution to be quite simple.
So, that said, I'm doing the tutorial for django-rest-framework and my problem started on part 4. The tutorial says as follows:
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/'
endpoint, and notice that the representation includes a list of the
snippet pks that are associated with each user, in each user's
'snippets' field.
So, I tried to create the "snippets" objects with the manage.py shell, as in the first part of the tutorial, with the following code:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
snippet = Snippet(code='foo = "bar"\n')
snippet.save()
And that's where it ends. .save() triggers the error, which I've printed the traceback for, below.
Using the advice from the previously answered question, I've very slightly changed my setup, but I'm still getting the error. Here's the setup:
models.py:
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model):
owner = models.ForeignKey('auth.User', related_name='snippets')
highlighted = models.TextField(default='')
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly',max_length=100 )
class Meta:
ordering = ('created',)
def save(self, *args, **kwargs):
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
serializers.py:
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES,STYLE_CHOICES
from django.contrib.auth.models import User
class SnippetSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
class Meta:
model = User
fields = ('id', 'username', 'snippets')
views.py:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework import permissions
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
/snippets/urls.py
from django.conf.urls import url, include
from snippets.views import SnippetList, SnippetDetail, UserList, UserDetail
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^snippets/$', SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', SnippetDetail.as_view()),
url(r'^users/$', UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', UserDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
urls.py:
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('snippets.urls')),
]
and, lastly, the ugly traceback:
In [6]: snippet.save()
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\utils.py in execute(self, sql, params)
63 else:
---> 64 return self.cursor.execute(sql, params)
65
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\sqlite3\base.py in execute(self, query, params)
322 query = self.convert_query(query)
--> 323 return Database.Cursor.execute(self, query, params)
324
OperationalError: table snippets_snippet has no column named owner_id
The above exception was the direct cause of the following exception:
OperationalError Traceback (most recent call last)
<ipython-input-6-fe28bd3dc796> in <module>()
----> 1 snippet.save()
D:\GitHub Repositories\Django\tutorial\snippets\models.py in save(self, *args, **kwargs)
34 full=True, **options)
35 self.highlighted = highlight(self.code, lexer, formatter)
---> 36 super(Snippet, self).save(*args, **kwargs)
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base.py in save(self, force_insert, force_update, using, update_fields)
698
699 self.save_base(using=using, force_insert=force_insert,
--> 700 force_update=force_update, update_fields=update_fields)
701 save.alters_data = True
702
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base.py in save_base(self, raw, force_insert, force_update, using, update_fields)
726 if not raw:
727 self._save_parents(cls, using, update_fields)
--> 728 updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
729 # Store the database on which the object was saved
730 self._state.db = using
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base.py in _save_table(self, raw, cls, force_insert, force_update, using, update_fields)
810
811 update_pk = bool(meta.has_auto_field and not pk_set)
--> 812 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
813 if update_pk:
814 setattr(self, meta.pk.attname, result)
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base.py in _do_insert(self, manager, using, fields, update_pk, raw)
849 """
850 return manager._insert([self], fields=fields, return_id=update_pk,
--> 851 using=using, raw=raw)
852
853 def delete(self, using=None, keep_parents=False):
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\manager.py in manager_method(self, *args, **kwargs)
120 def create_method(name, method):
121 def manager_method(self, *args, **kwargs):
--> 122 return getattr(self.get_queryset(), name)(*args, **kwargs)
123 manager_method.__name__ = method.__name__
124 manager_method.__doc__ = method.__doc__
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\query.py in _insert(self, objs, fields, return_id, raw, using)
1037 query = sql.InsertQuery(self.model)
1038 query.insert_values(fields, objs, raw=raw)
-> 1039 return query.get_compiler(using=using).execute_sql(return_id)
1040 _insert.alters_data = True
1041 _insert.queryset_only = False
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\sql\compiler.py in execute_sql(self, return_id)
1058 with self.connection.cursor() as cursor:
1059 for sql, params in self.as_sql():
-> 1060 cursor.execute(sql, params)
1061 if not (return_id and cursor):
1062 return
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\utils.py in execute(self, sql, params)
77 start = time()
78 try:
---> 79 return super(CursorDebugWrapper, self).execute(sql, params)
80 finally:
81 stop = time()
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\utils.py in execute(self, sql, params)
62 return self.cursor.execute(sql)
63 else:
---> 64 return self.cursor.execute(sql, params)
65
66 def executemany(self, sql, param_list):
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\utils.py in __exit__(self, exc_type, exc_value, traceback)
93 if dj_exc_type not in (DataError, IntegrityError):
94 self.wrapper.errors_occurred = True
---> 95 six.reraise(dj_exc_type, dj_exc_value, traceback)
96
97 def __call__(self, func):
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\six.py in reraise(tp, value, tb)
683 value = tp()
684 if value.__traceback__ is not tb:
--> 685 raise value.with_traceback(tb)
686 raise value
687
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\utils.py in execute(self, sql, params)
62 return self.cursor.execute(sql)
63 else:
---> 64 return self.cursor.execute(sql, params)
65
66 def executemany(self, sql, param_list):
C:\Users\Jordon\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\sqlite3\base.py in execute(self, query, params)
321 return Database.Cursor.execute(self, query)
322 query = self.convert_query(query)
--> 323 return Database.Cursor.execute(self, query, params)
324
325 def executemany(self, query, param_list):
OperationalError: table snippets_snippet has no column named owner_id
First of all, you have not provided a value for 'owner' while saving a Snippet object. You need to do something like this:
from django.contrib.auth.models import User
new_user = User.objects.create(...)
snippet = Snippet(owner=new_user, code='foo = "bar"\n')
snippet.save()
Nevertheless, it doesn't explain why the owner_id column was not created. Can you change the model to something like this and see if it detects the owner column?
from django.contrib.auth.models import User
class Snippet(models.Model):
owner = models.ForeignKey(User, related_name='snippets')
...
Then run these steps to attempt to create the column.
python manage.py makemigrations snippets
python manage.py migrate
It looks like you didn't delete the original database.
The tutorial removes it after the model is changed:
rm -f tmp.db db.sqlite3
rm -r snippets/migrations
python manage.py makemigrations snippets
python manage.py migrate
If you did remove none of the tmp.db or db.sqlite3 then Django might think it has already done the migration and will not redo it.
Make sure you find one of the two aforementioned files and remove them and then run the above script (plus the createsuperuser for you to login in).