Friday, May 30, 2014

saving backbonejs model with django backend

Hi Guys,

how do i save a backbone model in the database ??

here is how i have tried it and the errors i am getting, please assist ,
/*
*
*
* the field model
*
*
*/
    var fieldModel=Backbone.Model.extend({
        defaults:{
            name:'',
            type:'',
            placeholder:'',
        },
        urlRoot:'form',
        initialize:function(){
            this.on('invalid',function(model,error){
                alert(error);
            })
        },
        validate:function(attrs){
            if(! $.trim(attrs.name) || ! $.trim(attrs.type)){
                return 'Name can not be blank'
            }
        }

    });


/*
*
*
* the collection of fields
*
*
*/
 
    var fieldCollections=Backbone.Collection.extend({
        model:fieldModel,
        urlRoot:'form',
    });


/*
*
*
* The collection of all elements view
*
*
*/
    var allFieldsView=Backbone.View.extend({
        el:'#designArea',
        //template:,
        initialize:function(){
            this.render();
            this.listenTo(this.collection,'add',this.displayOneField)
        },
        events:{
            'click #saveDesignedForm':'saveDesignedForm',           
        },
        render:function(){
            this.collection.each(this.displayOneField,this);
            return this;

        },
        // display each field
        displayOneField:function(field){
            // create a fields view based on each model that is in the collection
            var oneFieldDisplay =new fieldView({model:field});
            // append the each models fieldview
            // using fieldview created using the model get the el method
            this.$el.find('#formDesign').append(oneFieldDisplay.render().el);
        },
       

        // save all the models in a collection
        saveDesignedForm:function(){
            this.collection.each(function(element){
                element.save()
            })
        }
       
    });

the url.py has the following path

  url(r'^form-save',saveFormDesign),

from the chrome console i get the following request payload on save
  1. {"name":"default name","type":"text","placeholder":"the placeholder goes here"}

and this is my view

@csrf_exempt
def saveFormDesign(request):
    ClientData.objects.create(name='demo',fields=request)
    return HttpResponse(request)

here is my stack trace
ProgrammingError at /dataapp/form
can't adapt type 'WSGIRequest'

Request Method: POST
Request URL: http://localhost:8000/dataapp/form
Django Version: 1.6.3
Python Executable: C:\Python27\python.exe
Python Version: 2.7.6
Python Path: ['C:\\projects', 'C:\\Python27\\lib\\site-packages\\setuptools-3.2-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\pip-1.5.4-py2.7.egg', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']
Server time: Sat, 31 May 2014 08:19:45 +0300
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'south',
 'DataApp',
 'django_hstore',
 'tastypie')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  57.         return view_func(*args, **kwargs)
File "C:\projects\DataApp\views.py" in saveFormDesign
  253.     ClientData.objects.create(name='demo',fields=request)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in create
  157.         return self.get_queryset().create(**kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in create
  319.         obj.save(force_insert=True, using=self.db)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
  545.                        force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
  573.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in _save_table
  654.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in _do_insert
  687.                                using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in _insert
  232.         return insert_query(self.model, objs, fields, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in insert_query
  1511.     return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  903.             cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  69.             return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  53.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
  99.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  53.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /dataapp/form
Exception Value: can't adapt type 'WSGIRequest'
Request information:
GET: No GET data

POST: No POST data

FILES: No FILES data

COOKIES:
csrftoken = 'LQEqpLJNW3g5IaGcMGa3nRwEnWJP2Eui'
sessionid = '01ekwy6yrmq27q8xs784a8os6uxep8i0'

META:
TMP = 'C:\\Users\\EDDMASH\\AppData\\Local\\Temp'
COMPUTERNAME = 'EDDMASH-PC'
wsgi.multiprocess = False
RUN_MAIN = 'true'
HTTP_REFERER = 'http://localhost:8000/dataapp/form-design'
USERDOMAIN = 'EDDMASH-PC'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SOFTWARE = 'WSGIServer/0.1 Python/2.7.6'
PSMODULEPATH = 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\'
SCRIPT_NAME = u''
COMMONPROGRAMFILES = 'C:\\Program Files (x86)\\Common Files'
PROCESSOR_IDENTIFIER = 'Intel64 Family 6 Model 42 Stepping 7, GenuineIntel'
REQUEST_METHOD = 'POST'
PROGRAMFILES = 'C:\\Program Files (x86)'
PROCESSOR_REVISION = '2a07'
PROJ_LIB = 'C:\\OSGeo4W\\share\\proj'
QUERY_STRING = ''
SYSTEMROOT = 'C:\\Windows'
HTTP_ORIGIN = 'http://localhost:8000'
PROGRAMFILES(X86) = 'C:\\Program Files (x86)'
CONTENT_LENGTH = '79'
HTTP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36'
HTTP_CONNECTION = 'keep-alive'
HTTP_COOKIE = 'sessionid=01ekwy6yrmq27q8xs784a8os6uxep8i0; csrftoken=LQEqpLJNW3g5IaGcMGa3nRwEnWJP2Eui'
TEMP = 'C:\\Users\\EDDMASH\\AppData\\Local\\Temp'
REMOTE_ADDR = '127.0.0.1'
COMMONPROGRAMFILES(X86) = 'C:\\Program Files (x86)\\Common Files'
PROCESSOR_ARCHITECTURE = 'x86'
AGSDESKTOPJAVA = 'C:\\Program Files (x86)\\ArcGIS\\Desktop10.0\\'
wsgi.url_scheme = 'http'
ALLUSERSPROFILE = 'C:\\ProgramData'
SERVER_PORT = '8000'
LOCALAPPDATA = 'C:\\Users\\EDDMASH\\AppData\\Local'
HOMEPATH = '\\Users\\EDDMASH'
PROCESSOR_LEVEL = '6'
PROGRAMW6432 = 'C:\\Program Files'
USERNAME = 'EDDMASH'
GDAL_DATA = 'C:\\Program Files\\PostgreSQL\\9.3\\gdal-data'
LOGONSERVER = '\\\\EDDMASH-PC'
PROMPT = '$P$G'
COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
HTTP_X_REQUESTED_WITH = 'XMLHttpRequest'
PROGRAMDATA = 'C:\\ProgramData'
HTTP_ACCEPT = 'application/json, text/javascript, */*; q=0.01'
wsgi.multithread = True
CSRF_COOKIE = u'LQEqpLJNW3g5IaGcMGa3nRwEnWJP2Eui'
PATH = 'C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\xampp\\php;C:\\ProgramData\\Composer\\bin;C:\\Program Files (x86)\\Toshiba\\Bluetooth Toshiba Stack\\sys\\;C:\\Program Files (x86)\\Toshiba\\Bluetooth Toshiba Stack\\sys\\x64\\;C:\\Python27\\;C:\\Python27\\Lib\\site-packages\\;C:\\Python27\\Scripts\\;;C:\\Python27;C:\\OSGeo4W\\bin;C:\\Program Files\\PostgreSQL\\9.3\\bin\\;C:\\Ruby200-x64\\bin\\;C:\\Program Files\\nodejs\\;C:\\RailsInstaller\\Git\\cmd;C:\\RailsInstaller\\Ruby1.9.3\\bin;C:\\Users\\EDDMASH\\AppData\\Roaming\\npm'
wsgi.input = <socket._fileobject object at 0x03383AF0>
wsgi.errors = <open file '<stderr>', mode 'w' at 0x003760D0>
HTTP_HOST = 'localhost:8000'
SESSIONNAME = 'Console'
PATHEXT = '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC'
PATH_INFO = u'/dataapp/form'
FP_NO_HOST_CHECK = 'NO'
WINDIR = 'C:\\Windows'
wsgi.file_wrapper = ''
HTTP_ACCEPT_ENCODING = 'gzip,deflate,sdch'
wsgi.version =
HOMEDRIVE = 'C:'
APPDATA = 'C:\\Users\\EDDMASH\\AppData\\Roaming'
SERVER_NAME = 'drupal.themes'
wsgi.run_once = False
REMOTE_HOST = ''
SYSTEMDRIVE = 'C:'
GATEWAY_INTERFACE = 'CGI/1.1'
HTTP_ACCEPT_LANGUAGE = 'en-GB,en-US;q=0.8,en;q=0.6'
NUMBER_OF_PROCESSORS = '4'
VBOX_INSTALL_PATH = 'C:\\Program Files\\Oracle\\VirtualBox\\'
DJANGO_SETTINGS_MODULE = 'projects.settings'
CONTENT_TYPE = 'application/json'
PROCESSOR_ARCHITEW6432 = 'AMD64'
COMMONPROGRAMW6432 = 'C:\\Program Files\\Common Files'
OS = 'Windows_NT'
PUBLIC = 'C:\\Users\\Public'
USERPROFILE = 'C:\\Users\\EDDMASH'

Settings:
Using settings module projects.settings
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
CSRF_COOKIE_SECURE = False
LANGUAGE_CODE = 'en-us'
ROOT_URLCONF = 'projects.urls'
MANAGERS =
BASE_DIR = 'C:\\projects'
DEFAULT_CHARSET = 'utf-8'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
STATIC_ROOT = None
ALLOWED_HOSTS = []
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
EMAIL_SUBJECT_PREFIX = '[Django] '
FILE_UPLOAD_PERMISSIONS = None
STATICFILES_FINDERS =
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'sessionid'
ADMIN_FOR =
TIME_INPUT_FORMATS =
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'AUTOCOMMIT': True, 'ATOMIC_REQUESTS': False, 'NAME': 'dataapp', 'TEST_MIRROR': None, 'OPTIONS': {}, 'CONN_MAX_AGE': 0, 'TIME_ZONE': 'UTC', 'TEST_COLLATION': None, 'TEST_CHARSET': None, 'HOST': '', 'USER': 'postgres', 'TEST_NAME': None, 'PASSWORD': u'********************', 'PORT': ''}}
SERVER_EMAIL = 'root@localhost'
FILE_UPLOAD_HANDLERS =
DEFAULT_CONTENT_TYPE = 'text/html'
APPEND_SLASH = True
FIRST_DAY_OF_WEEK = 0
DATABASE_ROUTERS = []
YEAR_MONTH_FORMAT = 'F Y'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
SESSION_COOKIE_PATH = '/'
MIDDLEWARE_CLASSES =
USE_I18N = True
THOUSAND_SEPARATOR = ','
SECRET_KEY = u'********************'
LANGUAGE_COOKIE_NAME = 'django_language'
DEFAULT_INDEX_TABLESPACE = ''
TRANSACTIONS_MANAGED = False
LOGGING_CONFIG = 'django.utils.log.dictConfig'
SEND_BROKEN_LINK_EMAILS = False
TEMPLATE_LOADERS =
WSGI_APPLICATION = 'projects.wsgi.application'
TEMPLATE_DEBUG = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
CSRF_COOKIE_NAME = 'csrftoken'
FORCE_SCRIPT_NAME = None
USE_X_FORWARDED_HOST = False
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_DOMAIN = None
FILE_CHARSET = 'utf-8'
DEBUG = True
SESSION_FILE_PATH = None
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
INSTALLED_APPS =
LANGUAGES =
COMMENTS_ALLOW_PROFANITIES = False
STATICFILES_DIRS =
PREPEND_WWW = False
SECURE_PROXY_SSL_HEADER = None
SESSION_COOKIE_HTTPONLY = True
DEBUG_PROPAGATE_EXCEPTIONS = False
MONTH_DAY_FORMAT = 'F j'
LOGIN_URL = '/accounts/login/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
TIME_FORMAT = 'P'
AUTH_USER_MODEL = 'auth.User'
DATE_INPUT_FORMATS =
AUTHENTICATION_BACKENDS = 'django.contrib.auth.backends.ModelBackend'
EMAIL_HOST_PASSWORD = u'********************'
PASSWORD_RESET_TIMEOUT_DAYS = u'********************'
CACHE_MIDDLEWARE_ALIAS = 'default'
SESSION_SAVE_EVERY_REQUEST = False
NUMBER_GROUPING = 0
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
CSRF_COOKIE_PATH = '/'
LOGIN_REDIRECT_URL = '/accounts/profile/'
DECIMAL_SEPARATOR = '.'
IGNORABLE_404_URLS =
LOCALE_PATHS =
TEMPLATE_STRING_IF_INVALID = ''
LOGOUT_URL = '/accounts/logout/'
EMAIL_USE_TLS = False
FIXTURE_DIRS =
EMAIL_HOST = 'localhost'
DATE_FORMAT = 'N j, Y'
MEDIA_ROOT = ''
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
ADMINS =
FORMAT_MODULE_PATH = None
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
MEDIA_URL = ''
DATETIME_FORMAT = 'N j, Y, P'
TEMPLATE_DIRS =
DISALLOWED_USER_AGENTS =
ALLOWED_INCLUDE_ROOTS =
LOGGING = {}
SHORT_DATE_FORMAT = 'm/d/Y'
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
CACHE_MIDDLEWARE_KEY_PREFIX = u'********************'
TIME_ZONE = 'UTC'
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_TABLESPACE = ''
TEMPLATE_CONTEXT_PROCESSORS =
SESSION_COOKIE_AGE = 1209600
SETTINGS_MODULE = 'projects.settings'
USE_ETAGS = False
LANGUAGES_BIDI =
FILE_UPLOAD_TEMP_DIR = None
INTERNAL_IPS =
STATIC_URL = '/static/'
EMAIL_PORT = 25
USE_TZ = True
SHORT_DATETIME_FORMAT = 'm/d/Y P'
PASSWORD_HASHERS = u'********************'
ABSOLUTE_URL_OVERRIDES = {}
CACHE_MIDDLEWARE_SECONDS = 600
CSRF_COOKIE_HTTPONLY = False
DATETIME_INPUT_FORMATS =
EMAIL_HOST_USER = ''
PROFANITIES_LIST = u'********************'

You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard 500 page.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e24f7f23-641a-4ed2-8652-876c025e20bc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment