Model thinks my string is tuple and won't save - django

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 :)

Related

Django error: invalid literal for int() with base 10: b'01/12/1990'

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'

ProgrammingError relation "uploader_email" does not exist

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"
^

Django: ValueError no ForeignKey to model in Admin

I am trying do a simple thing, I thought. I wanted to be able to create tasks in the admin and then have a separate page with the log and the staff as inlines to make editing easier. I have done this before but now I am running into:
Exception Type: ValueError at /admin/delegation/studytask/add/
Exception Value: 'account.UserProfile' has no ForeignKey to 'delegation.StudyTask'.
Not sure why this is happening. Thoughts? Thanks!
Models:
from django.db import models
from account.models import UserProfile
from studies.models import Study
# Create your models here.
class StudyTask(models.Model):
title = models.CharField(max_length=150)
description = models.TextField()
class DelegationLog(models.Model):
study = models.ForeignKey(Study)
del_log = models.FileField(upload_to='uploads/delegation_logs/%Y/%m/%d', null=True, blank=True)
staff = models.ManyToManyField(UserProfile, through='DelegatedStaff')
class DelegatedStaff(models.Model):
staff = models.ForeignKey(UserProfile)
del_log = models.ForeignKey(DelegationLog)
start_date = models.DateField('Start Date')
end_date = models.DateField('End Date')
approved_date = models.DateField('Date Approved by PI')
tasks = models.ManyToManyField(StudyTask)
def __str__(self):
return self.staff
Admin:
from django.contrib import admin
from .models import DelegationLog, DelegatedStaff, StudyTask
# Register your models here.
class DelegatedStaffAdminInline(admin.TabularInline):
model = DelegatedStaff
class DelegationLogAdmin(admin.ModelAdmin):
list_display = ['study']
inlines = [DelegatedStaffAdminInline]
admin.site.register(StudyTask)
admin.site.register(DelegationLog, DelegationLogAdmin)
The user admin:
class ProfileInline(admin.TabularInline):
model = UserProfile
UserAdmin.inlines += [ProfileInline]
Update: Here is the traceback
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/delegation/studytask/add/
Django Version: 1.8.7
Python Version: 3.5.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studies',
'account',
'delegation')
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 "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
618. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
233. return view(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in add_view
1518. return self.changeform_view(request, None, form_url, extra_context)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py" in inner
30. return func(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in changeform_view
1482. formsets, inline_instances = self._create_formsets(request, self.model(), change=False)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in _create_formsets
1798. for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_formsets_with_inlines
796. yield inline.get_formset(request, obj), inline
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_formset
1879. fields = flatten_fieldsets(self.get_fieldsets(request, obj))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_fieldsets
354. return [(None, {'fields': self.get_fields(request, obj)})]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_fields
1955. form = self.get_formset(request, obj, fields=None).form
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_formset
1950. return inlineformset_factory(self.parent_model, self.model, **defaults)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/forms/models.py" in inlineformset_factory
1016. fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/forms/models.py" in _get_foreign_key
988. parent_model._meta.object_name,
Exception Type: ValueError at /admin/delegation/studytask/add/
Exception Value: 'account.UserProfile' has no ForeignKey to 'delegation.StudyTask'.

django-mptt ValueError: Cannot use None as a query value

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.

django-admin list_filter by datetime range not only by date range

in django-admin, for a model, I have to filter by datetime range.
I've found this:
https://github.com/DXist/django-daterange-filter/blob/master/daterange_filter/filter.py
that works great but is just for Date range and not DateTime range.
So I'm trying to modify for the purpose that, that's my own version:
class DateRangeForm(forms.Form):
def __init__(self, *args, **kwargs):
field_name = kwargs.pop('field_name')
super(DateRangeForm, self).__init__(*args, **kwargs)
self.fields['%s__gte' % field_name] = forms.DateTimeField(
label='', widget=AdminSplitDateTime(
attrs={'placeholder': _('From date')}), localize=True,
required=False)
self.fields['%s__lte' % field_name] = forms.DateTimeField(
label='', widget=AdminSplitDateTime(
attrs={'placeholder': _('To date')}), localize=True,
required=False)
class DateRangeFilter(admin.filters.FieldListFilter):
template = 'admin/daterange_filter/filter.html'
def __init__(self, field, request, params, model, model_admin, field_path):
self.lookup_kwarg_since = '%s__gte' % field_path
self.lookup_kwarg_upto = '%s__lte' % field_path
super(DateRangeFilter, self).__init__(
field, request, params, model, model_admin, field_path)
self.form = self.get_form(request)
def choices(self, cl):
return []
def expected_parameters(self):
return [self.lookup_kwarg_since, self.lookup_kwarg_upto]
def get_form(self, request):
return DateRangeForm(data=self.used_parameters,
field_name=self.field_path)
def queryset(self, request, queryset):
if self.form.is_valid():
# get no null params
filter_params = dict(filter(lambda x: bool(x[1]),
self.form.cleaned_data.items()))
for k, v in filter_params.items():
if k.endswith('__lte'):
filter_params[k] = v + timedelta(days=1)
return queryset.filter(**filter_params)
else:
return queryset
admin.filters.FieldListFilter.register(lambda f: isinstance(f, models.DateTimeField), DateRangeFilter)
"front-end" side it's working.. it shows the AdminSplitDateTime widget but when I submit the filter form I get:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/erp/ordine/?data_creazione__gte_0=29%2F05%2F2013&data_creazione__gte_1=12%3A42%3A10&data_creazione__lte_0=&data_creazione__lte_1=
Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'account',
'south',
'mptt',
'erp',
'tinymce')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
372. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
202. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
1180. self)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in __init__
73. self.query_set = self.get_query_set(request)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_query_set
303. use_distinct) = self.get_filters(request)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_filters
100. if not self.model_admin.lookup_allowed(key, value):
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in lookup_allowed
263. model = field.rel.to
Exception Type: AttributeError at /admin/erp/ordine/
Exception Value: 'NoneType' object has no attribute 'to'
I've prepared a semi-empty django project (1 light model, admin setted up, dev.db sqlite3) just for testing that issue:
you can find it here: https://dl.dropboxusercontent.com/u/53953129/test_project.zip
You haven't posted your client code for this filter. What value gets 'field' variable in options.py?
The situation is unchanged though... I've added a tiny test project to play on