I try to built basic chat application in django using jquery. In my post view of views.py, I successfully get the message data but some how in c.save() i got an below error. i also try to debug passing default value but getting same error. i can't make it as a not null constraint.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Chat2(models.Model):
user = models.ForeignKey(User)
message = models.CharField(max_length=500)
def __unicode__(self):
return self.message
chat.js
$('#msg_f').on('submit',function(event) {
event.preventDefault();
$.ajax({
datatype:"json",
url : '/login/post/',
type: 'POST',
data:{msgbox : $('#msg_box').val()},
success : function(data){
$('#msg_box').val('');
$('#msg_b').append('<div class="msg_right"><p class="msg">'+data.msgbox+'</p></div>');
}
});
});
views.py
def post(request):
if request.method=="POST":
msg = request.POST.get('msgbox',None)
c = Chat2(user=request.user,message=msg)
if msg != '':
c.save()
return JsonResponse({'msg':msg,'user':c.user.username})
else:
return HttpResponse("request must be post")
Error
[24/Jun/2017 09:21:45] "GET /login/login/chat_home/ HTTP/1.1" 200 3216
Internal Server Error: /login/post/
Traceback (most recent call last):
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: chat_chat2.message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\django-tuto\login\chat\views.py", line 40, in post
c.save()
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 836, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 922, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 961, in _do_insert
using=using, raw=raw)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\query.py", line 1063, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\sql\compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: chat_chat2.message
Related
i try to add usernames to my video chatting app and this error occured. I try to fetch create_member but this error occured. I try to solve many times but failed. Kindly Check it.
Uncaught (in promise) SyntaxError: Unexpected token. This error occured in console and i can't get my video and audio tracks.
Internal Server Error: /create_member/
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
89, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such column: videoApp_roommember.name
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\hp\Desktop\ChattingApp\VideoChatting\videoApp\views.py", line 76, in createMember
member, created = RoomMember.objects.get_or_create(
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line
85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 657, in get_or_create
return self.get(**kwargs), False
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 492, in get
num = len(clone)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 302, in __len__
self._fetch_all()
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 57, in __iter__
results = compiler.execute_sql(
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py",
line 1361, in execute_sql
cursor.execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
103, in execute
return super().execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
67, in execute
return self._execute_with_wrappers(
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
84, in _execute
with self.db.wrap_database_errors:
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
89, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: videoApp_roommember.name
[11/Oct/2022 07:47:37] "POST /create_member/ HTTP/1.1" 500 141222
So, here is my views.py file:
#csrf_exempt
def createMember(request):
data = json.loads(request.body)
member, created = RoomMember.objects.get_or_create(
name=data['name'],
uid=data['UID'],
room_name=data['room_name']
)
return JsonResponse({'name':data['name']}, safe=False)
here is my script.js file
let createMember = async () => {
let response = await fetch('/create_member/', {
method:'POST',
headers: {
'Content-Type':'application/json'
},
body:JSON.stringify({'name':NAME, 'room_name':CHANNEL, 'UID':UID})
})
let member = await response.json()
return member
}
And here is models.py file
class RoomMember(models.Model):
name = models.CharField(max_length=200)
uid = models.CharField(max_length=1000)
room_name = models.CharField(max_length=200)
insession = models.BooleanField(default=True)
def __str__(self):
return self.name
In django's docs under migrations it says:
Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
So the error says
django.db.utils.OperationalError: no such column: videoApp_roommember.name
Which means the changes you made, which is adding name to the model, has not been migrated to take effect on the database table so whenever you make a query or try to create a room member the error above will be thrown because of not finding the name column in the DB.
So you need to:
Run python manage.py makemigrations to create the migrations file for the changes you made.
Run python manage.py migrate to make the updates to the database
I read in Django document that a blank database will be created for testing. I am new to Django so I barely changed anything in setting.py and currently using Sqlite database. However, when I run python manage.py test, Django keep telling the user has been existed, so I tried changing the username for the created users in TestCase, run the test again and found out that the new users are created in the existing database. The test file is as bellow:
class UserTestCase(unittest.TestCase):
def setUp(self):
admin = User.objects.create(username="admin", password="1")
user1 = User.objects.create(username="user1", password="1")
user2 = User.objects.create(username="user2", password="1")
admin.following.add(user1)
admin.followers.add(user2)
def test_users_count(self):
self.assertEqual(User.objects.count()==3)
My model is as bellow:
class User(AbstractUser):
followers = models.ManyToManyField('self', related_name="following", symmetrical=False, through='Follow', through_fields=('followee', 'follower'))
def __str__(self):
return f"{self.username}"
def serialize(self):
return {
"id": self.id,
"username": self.username,
}
class Follow(models.Model):
followee = models.ForeignKey(
'User',
on_delete=models.CASCADE,
related_name='+'
)
follower = models.ForeignKey(
'User',
on_delete=models.CASCADE,
related_name='+'
)
def clean(self, *args, **kwargs):
if self.follower__id == self.followee__id:
raise ValidationError('Can not follow self.')
return super().clean(*args, **kwargs)
class Meta:
constraints = [
models.UniqueConstraint(fields=['follower', 'followee'], name='follow_once'),
models.CheckConstraint(check=~Q(follower=F('followee')), name='not_follow_self')
]
EDIT: Bellow is the output when I run python manage.py test
(env_web) PS C:\Users\HL94NVT\Programming\web_development\project4> python manage.py test
System check identified no issues (0 silenced).
EE
======================================================================
ERROR: test_following_count (network.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: network_user.username
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\project4\network\tests.py", line 21, in setUp
admin = User.objects.create(username="admin1", password="1")
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: network_user.username
======================================================================
ERROR: test_users_count (network.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: network_user.username
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\project4\network\tests.py", line 21, in setUp
admin = User.objects.create(username="admin1", password="1")
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: network_user.username
----------------------------------------------------------------------
Ran 2 tests in 0.063s
Using django.test.TestCase instead of unittest.TestCase helps according to the document
https://docs.djangoproject.com/en/3.1/topics/testing/overview/
If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.
Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.
I am learning Django, and is following this online tutorial for creating forms.
https://www.youtube.com/watch?v=6oOHlcHkX2U&list=PLEsfXFp6DpzTD1BD1aWNxS2Ep06vIkaeW&index=23. Upon rendering in browser, I receive NOT NULL constraint failed: product_product.price.
In my models.py I have
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length = 200, null = False, blank = False)
description = models.TextField(null = True, blank = True)
price = models.DecimalField(decimal_places=0, max_digits = 10)
active = models.BooleanField(default = True)
def __str__(self):
return self.title
In my views.py under the same app I have
from django.shortcuts import render
from .forms import ProductForm
# Create your views here.
def productCreateView(request):
form = ProductForm(request.POST or None)
if form.is_valid:
print('form is valid now to saving')
print('\n\n')
form.save()
context = {'form' : form}
return render(request, '../templates/product_create.html', context=context)
I have tried to
python manage.py makemigrations
python manage.py migrate
when I tried to modify my price in my models.py e.g. by stating
price = models.DecimalField(decimal_places=0, max_digits = 10, blank = False, null = False)
Each time it says that there is nothing to migrate.
For the sake of learning, can anybody tell me what I am missing?
My complete error messages looks like below
[09/Mar/2020 23:24:41] "GET /create HTTP/1.1" 301 0
form is valid now to saving
Internal Server Error: /create/
Traceback (most recent call last):
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: product_product.price
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python\dimsumshop\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\dimsumshop\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\dimsumshop\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\dimsumshop\shop\product\views.py", line 11, in productCreateView
form.save()
File "C:\Python\dimsumshop\env\lib\site-packages\django\forms\models.py", line 459, in save
self.instance.save()
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 784, in save_base
force_update, using, update_fields,
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 926, in _do_insert
using=using, raw=raw,
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\sql\compiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: product_product.price
[09/Mar/2020 23:24:41] "GET /create/ HTTP/1.1" 500 145386
Replace form.is_valid with form.is_valid() as proposed by Willem Van Onsem is the answer! Thanks!
I'm running django 2.1.4 on python 3.6 with latest Postgresql.
Problem is, when I'm trying to create database from django code, it returning "current transaction is aborted, commands ignored until end of transaction block". Here is my code ->
#transaction.atomic
def mutate(self, info, username, password, email, name, phone, company, country):
user = get_user_model()(
first_name=name,
username=username,
email=email,
is_active=False
)
user.set_password(password)
user.save()
get_country = Country.objects.filter(id=country).first()
company = Company(name=company, phone=phone, user=user, country=get_country)
company.save()
code = secrets.token_hex(16)
activation = ActivationCode(user=user, code=code)
activation.save()
try:
with connection.cursor() as cursor:
cursor.execute("CREATE DATABASE company_" + str(company.id))
except:
GraphQLError("Something went wrong! Please contact the support center!")
finally:
cursor.close()
db = CompanyDatabase(db_name="company_" + str(company.id), company=company)
db.save()
return CreateUser(user=user, company=company)
But it creates the database from django shell ->
shell image
Here's the postgres log error ->
[12728] ERROR: CREATE DATABASE cannot run inside a transaction block
Here's the terminal errors generated ->
Traceback (most recent call last):
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\promise\promise.py", line 487, in _resolve_from_executo
r
executor(resolve, reject)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\promise\promise.py", line 754, in executor
return resolve(f(*args, **kwargs))
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\graphql\execution\middleware.py", line 75, in make_it_p
romise
return next(*args, **kwargs)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\contextlib.py", line 52, in inner
return func(*args, **kwds)
File "D:\xERP\graphqltest\users\schema.py", line 68, in mutate
db.save()
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 718, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 831, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 869, in _do_insert
using=using, raw=raw)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_metho
d
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1136, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1289, in execut
e_sql
cursor.execute(sql, params)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with
_wrappers
return executor(sql, params, many, context)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
graphql.error.located_error.GraphQLLocatedError: current transaction is aborted, commands ignored until end of transaction block
You must set the connection to autocommit mode before running CREATE DATABASE, otherwise psycopg2 will wrap it in an explicit transaction, which leads to the observed error.
I get an error when saving the model with custom primary key - id field.
My model:
class TestZ(models.Model):
id = models.CharField(primary_key=True, max_length=7)
field0 = models.CharField(max_length=10)
class Meta:
abstract = True
class TestX(TestZ):
field1 = models.CharField(max_length=10)
class TestA(TestX):
field2 = models.CharField(max_length=10)
class TestB(TestX):
pass
Error:
>>> TestB.objects.create(pk='aa', field0='0', field1='1')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 157, in create
return self.get_queryset().create(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 322, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 545, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 687, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1514, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 903, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 451, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: NOT NULL constraint failed: myapp_testb.testx_ptr_id
Without custom pk field in TestZ I can save objects.
From admin page I can add an objects, there are no errors.
Django==1.6.5
You need to reference the custom id field when creating the model object. I tested this out and it works --> TestB.objects.create(id='aa', field0='0', field1='1')