Created a new model called Email, but using makemigrations and migrate I am getting no changes detected. Upon runserver, I get the following error:
ProgrammingError at /admin/uploader/email/
relation "uploader_email" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "uploader_email"
I have tried every suggestion on stackoverflow, I have:
Deleted migrations files
ran migrate --fake and --fake-initial
migrate uploader (calling the app specifically)
Nothing is working, the DB simply will not be modified.
Any ideas?
Model:
class Email(models.Model):
ROUNDS_LIST = (
('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10'),
)
project = models.ForeignKey(Project)
client = models.ForeignKey(Client, null=True, blank=True)
name = models.CharField(max_length=256, null=True, blank=True)
filename = models.CharField(max_length=256, null=True, blank=True)
width = models.CharField(max_length=3, null=True, blank=True)
height = models.CharField(max_length=3, null=True, blank=True)
review_round = models.CharField(max_length=3, choices=ROUNDS_LIST, default=1)
zip_file_upload = models.FileField(blank=True, null=True, upload_to=get_upload_file_name)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
filename, file_extension = os.path.splitext(self.zip_file_upload.name)
self.name = filename
self.filename = filename + ".html"
super(Email, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "HTML Emails"
def __unicode__(self):
return self.name
Stack trace:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/uploader/email/
Django Version: 1.9.1
Python Version: 2.7.11
Installed Applications:
['grappelli',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'uploader.apps.UploaderAppConfig',
'accounts',
'crispy_forms',
'imagekit',
'storages',
'boto']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware']
Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
541. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changelist_view
1468. self.list_max_show_all, self.list_editable, self)
File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/views/main.py" in __init__
79. self.get_results(request)
File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/views/main.py" in get_results
174. result_count = paginator.count
File "/usr/local/lib/python2.7/site-packages/django/core/paginator.py" in _get_count
72. self._count = self.object_list.count()
File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py" in count
371. return self.query.get_count(using=self.db)
File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in get_count
483. number = obj.get_aggregation(using, ['__count'])['__count']
File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in get_aggregation
464. result = compiler.execute_sql(SINGLE)
File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
848. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /admin/uploader/email/
Exception Value: relation "uploader_email" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "uploader_email"
^
Related
I have this model
class CauroselImage(models.Model):
title = models.CharField(max_length=200, blank=True)
description = models.CharField(max_length=400, blank=True)
image = models.ImageField(upload_to=settings.UPLOAD_DIR,)
visible = models.BooleanField(default=True)
def __str__(self):
return self.title
that i want to set the image file minimum dimensions and I've found out the forms.py file is the way to go
class CauroselImageForm(forms.ModelForm):
class Meta:
model = CauroselImage
exclude = ('',)
def clean(self):
cleaned_data = self.cleaned_data
image = cleaned_data.get('image')
if image.width < 1300 or image.height < 400:
raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400")
return cleaned_data
and admin
class CauroselImageAdmin(admin.ModelAdmin):
form = CauroselImageForm
admin.site.register(CauroselImage, CauroselImageAdmin)
it however throws this error
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/pages/cauroselimage/1/change/
Django Version: 3.1.2
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'guides',
'pages',
'sorl.thumbnail',
'ckeditor',
'django.contrib.sites',
'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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 (most recent call last):
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1656, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1573, in _changeform_view
form_validated = form.is_valid()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid
return self.is_bound and not self.errors
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors
self.full_clean()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 375, in full_clean
self._clean_form()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 402, in _clean_form
cleaned_data = self.clean()
File "/home/sam/code/kpsga/pages/forms.py", line 26, in clean
if image.width < 1300 or image.height < 400:
Exception Type: AttributeError at /admin/pages/cauroselimage/1/change/
Exception Value: 'InMemoryUploadedFile' object has no attribute 'width'
You can use from django get_image_dimensions:
from django.core.files.images import get_image_dimensions
class CauroselImageForm(forms.ModelForm):
...
def clean(self):
width, height = get_image_dimensions(self.cleaned_data.get('image'))
if width < 1300 or height < 400:
raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400")
return cleaned_data
Method get_image_dimensions is using python PIL (Python Imaging Library).
get_image_dimensions returns the (width, height) of an image, given
an open file or a path. Set 'close' to True to close the file at the
end if it is initially in an open state.
I have created a Profile and Blog model in my Django application.
Here is the models.py file below:
from django.db import models
# Create your models here.
class Profile(models.Model):
name = models.CharField(max_length=30)
description = models.TextField()
number = models.CharField(max_length=10)
dob = models.DateField()
class Blog(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
blog_document = models.FileField(upload_to='documents/', null=True, blank=True)
And in my admin panel, for profile model: I want to view two or more columns in the table, something like this:
However this line is giving me the error since I do not know how to present more than one column appear in the Profile table:
def __str__(self):
return '%s %s' % (self.name, self.number)
What would be the correct solution for implementing two or more fields in the Profile table(admin panel).
Update
class ProfileAdmin(admin.ModelAdmin):
list_display = ('name', 'description', 'number', 'dob')
admin.site.register(Profile, ProfileAdmin)
class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'content')
admin.site.register(Blog, BlogAdmin)
This is the TrackBack:
Title: ValueError at /admin/mysite/profile/
Content:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/mysite/profile/
Django Version: 2.1.3
Python Version: 3.7.1
Installed Applications:
['mysite',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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 "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/contrib/admin/options.py" in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/contrib/admin/options.py" in changelist_view
1792. 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/models/query.py" in __len__
250. self._fetch_all()
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/models/query.py" in _fetch_all
1186. self._result_cache = list(self._iterable_class(self))
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/models/query.py" in __iter__
54. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1097. return list(result)
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in cursor_iter
1466. for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in <lambda>
1466. for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
File "/Users/sndtcsi/PycharmProjects/Assignment1/venv/lib/python3.7/site-packages/django/db/utils.py" in inner
96. return func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sqlite3/dbapi2.py" in convert_date
64. return datetime.date(*map(int, val.split(b"-")))
Exception Type: ValueError at /admin/mysite/profile/
Exception Value: invalid literal for int() with base 10: b'01/12/1990'
I have a model that I'm trying to override save on, but when I pass the information it thinks the string is a tuple, and won't save the information in the model. The particular field I'm pulling in is a single line address that looks like this: 3107 Eric Motorway, Lake William, GU 71954, but my model thinks the commas are a tuple. I've tried casting it to a string and everything.
Models.py:
class AddressBook(models.Model):
address = models.CharField(max_length=250, unique=True)
name = models.CharField(max_length=250)
def __str__(self):
return self.address
class Freight(models.Model):
pu_location = models.OneToOneField(AddressBook, to_field='address', related_name='pu_location')
pu_customer = models.CharField(max_length=200)
pu_appt_time = models.DateTimeField(default=datetime.now)
po_number = models.CharField(max_length=20)
load_number = models.CharField(max_length=10, blank=True, null=True)
pallet_count = models.IntegerField(validators=[MaxValueValidator(999)])
content_type = models.CharField(max_length=20, choices=[('Frozen', 'Frozen'), ('Chilled', 'Chilled'), ('Dry', 'Dry')])
cases_count = models.IntegerField(validators=[MaxValueValidator(9999)])
weight = models.IntegerField(validators=[MaxValueValidator(99999)])
del_customer = models.CharField(max_length=200)
del_location = models.OneToOneField(AddressBook, to_field='address', related_name='del_location')
del_city = models.CharField(max_length=50, blank=True, null=True)
del_state = models.CharField(max_length=2, blank=True, null=True)
del_appt_time = models.DateTimeField(default=datetime.now)
invoice_amount = models.FloatField(default=0.00, validators=[MinValueValidator(0.00), MaxValueValidator(999999.00)])
def save(self, *args, **kwargs):
reg = re.compile(r',+?(?P<city>[^,]+),\s+(?P<state>[A-Za-z]{2})')
print(self.del_location)
extract = reg.search(self.del_location)
city = extract.group('city')
state = extract.group('state')
if not self.del_state:
self.del_city = city
if not self.del_city:
self.del_state = state
def __str__(self):
return self.po_number, self.pu_customer, self.del_location
traceback info:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/dispatch/freight/add/
Django Version: 1.11.2
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'imagekit',
'rolepermissions',
'django_messages',
'taggit',
'dispatch']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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',
'dispatch.activeuser_middleware.ActiveUserMiddleware']
Traceback:
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
224. return view(request, *args, **kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/contrib/admin/options.py" in add_view
1508. return self.changeform_view(request, None, form_url, extra_context)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/contrib/admin/options.py" in changeform_view
1408. return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/contrib/admin/options.py" in _changeform_view
1452. self.log_addition(request, new_object, change_message)
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/contrib/admin/options.py" in log_addition
724. object_repr=force_text(object),
File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/django/utils/encoding.py" in force_text
76. s = six.text_type(s)
Exception Type: TypeError at /admin/dispatch/freight/add/
Exception Value: __str__ returned non-string (type tuple)
Your __str__ is a tuple. Your version:
def __str__(self):
return self.po_number, self.pu_customer, self.del_location
You can try something like
def __str__(self):
return "%s %s %s" % (self.po_number, self.pu_customer, self.del_location)
and it should work just fine :)
When i try sending my form then I getting error like "Error binding parameter 0 - probably unsupported type.".
I checked my model and set blank=True for all of fields for test but doesn't help. Can you give me some advice where is a problem? or fresh look :)
My traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/panel/order/create/19/
Django Version: 1.8.8
Python Version: 3.5.1
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'client',
'registration',
'avatar',
'filer',
'mptt',
'easy_thumbnails',
'reversion',
'guardian')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\loc\PycharmProjects\CRM\core\views.py" in order_create
347. form_order = OrderCreateForm(request.POST)
File "C:\Users\loc\PycharmProjects\CRM\core\forms.py" in __init__
34. Platform.objects.filter(client_id=request_client_id).values_list('id', 'name'))
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\query.py" in __iter__
162. self._fetch_all()
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\query.py" in _fetch_all
965. self._result_cache = list(self.iterator())
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\query.py" in iterator
1220. for row in compiler.results_iter():
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
794. results = self.execute_sql(MULTI)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
840. cursor.execute(sql, params)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\backends\utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\backends\utils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\utils.py" in __exit__
98. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\utils\six.py" in reraise
685. raise value.with_traceback(tb)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\backends\utils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
318. return Database.Cursor.execute(self, query, params)
Exception Type: InterfaceError at /panel/order/create/19/
Exception Value: Error binding parameter 0 - probably unsupported type.
Forms.py:
BLANK_CHOICE = (('', '---------'),)
class OrderCreateForm(forms.ModelForm):
tag_from = forms.MultipleChoiceField(label='Tags')
tag_to = forms.MultipleChoiceField()
class Meta:
model = Order
fields = ('price', 'client', 'platform')
def __init__(self, request_client_id, *args, **kwargs):
super(OrderCreateForm, self).__init__(*args, **kwargs)
self.fields['platform'].choices = BLANK_CHOICE + tuple(
Platform.objects.filter(client_id=request_client_id).values_list('id', 'name'))
self.fields['tag_from'].choices = OrderItemList.objects.all().values_list('id', 'name')
View.py:
#user_passes_test(lambda u: u.is_staff, login_url='/account/login/')
def order_create(request, request_client_id):
dict = {}
if request.method == 'POST':
form_order = OrderCreateForm(request.POST)
if form_order.is_valid():
obj = form_order.save(commit=False)
(...)
obj.save()
return HttpResponse('..')
dict['form_order'] = form_order
return render(request, 'panel/order/form.html', dict)
else:
dict['form_order'] = OrderCreateForm(request_client_id)
return render(request, 'panel/order/form.html', dict)
Your form takes request_client_id as the first argument. Therefore you must pass request_client_id every time the form is submitted, including when you do a post request.
if request.method == 'POST':
form_order = OrderCreateForm(request_client_id, request.POST)
change your form like this:
BLANK_CHOICE = ((0, '---------'),)
class OrderCreateForm(forms.ModelForm):
tag_from = forms.MultipleChoiceField(label='Tags')
tag_to = forms.MultipleChoiceField()
class Meta:
model = Order
fields = ('price', 'client', 'platform')
def __init__(self, request_client_id, *args, **kwargs):
super(OrderCreateForm, self).__init__(*args, **kwargs)
self.fields['platform'].choices = BLANK_CHOICE + tuple((x.id, x.name) for x in Platform.objects.filter(client_id=request_client_id))
I'm using django-mptt to create catalog Category model and I'm getting an error when i'm trying to create first instance of Category model
>>> c = Category(name='cat1', slug='cat1')
>>> c.save()
Error:
ValueError at /admin/catalog/category/add/
Cannot use None as a query value
This error appears only if i don't point 'parent' field in Category instance
class TimeStampedModel(models.Model):
"""
Abstract class for adding 'create' and 'modified' info
"""
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
#python_2_unicode_compatible
class Category(MPTTModel, TimeStampedModel):
''' Category model with MPTT storing approach '''
name = models.CharField(max_length=128)
slug = models.SlugField(max_length=50, unique=True)
description = models.TextField(blank=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('category', kwargs={'slug': self.slug})
class MPTTMeta:
order_insertion_by = ['id']
I can't find where error is. Have any suggestions?
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/catalog/category/add/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mptt',
'sorl.thumbnail',
'daguerre',
'home',
'utils',
'accounts',
'catalog',
'debug_toolbar')
Installed Middleware:
(u'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
584. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
204. return view(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
1454. return self.changeform_view(request, None, form_url, extra_context)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1405. self.save_model(request, new_object, form, not add)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model
1046. obj.save()
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/mptt/models.py" in save
824. right_sibling = opts.get_ordered_insertion_target(self, parent)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/mptt/models.py" in get_ordered_insertion_target
193. queryset = node.__class__._tree_manager.filter(filters).order_by(*order_by)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
691. return self._filter_or_exclude(False, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
709. clone.query.add_q(Q(*args, **kwargs))
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1287. clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1309. current_negated)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1314. current_negated=current_negated, connector=connector)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1142. value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in prepare_lookup_value
1040. raise ValueError("Cannot use None as a query value")
Exception Type: ValueError at /admin/catalog/category/add/
Exception Value: Cannot use None as a query value
Trouble was here:
class MPTTMeta:
order_insertion_by = ['id']
I changed 'order_insertion_by' field to another (to 'created' in my example) and it began to work
I found the cause of this error by using the "node_order_by" attribute when referencing a field using auto_now in a MP_node subclass....
Class Tree(MP_Node):
name = models.CharField(max_length=45)
last_modified = models.DateTimeField(auto_now=True)
node_order_by = ['last_modified']
Commented out node_order_by or using a different field and the error went away. I think the issue is that Treebeard is trying to figure out where to insert the child record and it doesn't have a date yet for the new record.