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

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.

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'

Django Multiple Record Insert CreateView ( not enough values to unpack (expected 2, got 1))

i am getting the following message while saving the record. not enough values to unpack (expected 2, got 1)
I am getting a Acquisition ID and attaching qoutations(single or multiple ) and once saving the record the system pops out the error.
there is no error if i select the ACQID from createview itself but when i am getting foriegn key from listview then error is coming.
i am getting a foriegn key from listview and inserting qoutations for it in the create view
if template is required please let me know even if i save a single record the system is giving error as mentioned above.
views.py
class QoutationAttach(SuccessMessageMixin, CreateView):
template_name = "ePROC/Acquisition/qoutation_add.html"
model = QoutationSelection
form_class=QoutationAdd
success_message = "Record was created successfully"
success_url = reverse_lazy('ePROC:qoutattach-list')
def form_valid(self, form):
form.instance.AcqID=CreateACQModel.objects.get(self.kwargs['pk'])
return super(QoutationAttach, self).form_valid(form)
class QoutationAttachListView(ListView):
template_name = "ePROC/Acquisition/qoutationattach_list.html"
model = QoutationSelection
queryset = QoutationSelection.objects.all()
context_object_name = 'query_results'
paginate_by = 10
def get_context_data(self, **kwargs):
context = super(QoutationAttachListView, self).get_context_data(**kwargs)
context['range'] = range(context["paginator"].num_pages)
return context
forms.py
class QoutationAdd(forms.ModelForm):
class Meta:
model = QoutationSelection
labels = {
"Status":"Status",
"AcqID":"Acquisition ID",
"QoutID":"Qoutation ID",
}
fields=['QoutID','Status']
QoutID=forms.ModelMultipleChoiceField(queryset=QoutationModel.objects.all())
models.py
class CreateACQModel(models.Model):
RequestItem=models.ForeignKey(CreateReqModel,on_delete=None,related_name='CreateReqID')
ACQProcDate=models.DateTimeField(auto_now_add=True)
ACQStatus=models.CharField(default='Procure',max_length=40)
def __str__(self):
return '%s' %(self.RequestItem)
def get_absolute_url(self):
return reverse('request-list', kwargs={'pk':self.id})
class QoutationModel(models.Model):
REF=models.CharField(max_length=40,default='BKB-Q-')
RequestItem=models.ForeignKey(CreateACQModel,on_delete=None,related_name='CreateRID')
RequestQuantity=models.PositiveIntegerField(validators=[MinValueValidator(1)])
VendorID=models.ForeignKey(VendorModel,on_delete=None,related_name='VendorID')
ccy=models.CharField(choices=ccych,max_length=40)
amount=models.PositiveIntegerField(validators=[MinValueValidator(1)])
date=models.DateTimeField(auto_now_add=True)
status=models.CharField(max_length=40,choices=QouteCH,default='Received')
descr=models.TextField(null=True, max_length=200)
qoute=models.FileField(upload_to='documents/',validators=[FileExtensionValidator(['pdf','zip','rar', 'txt', 'jpg', 'gif', 'doc', 'docx', 'xls', 'xlsx'])],blank=True, null=True)
def __str__(self):
return '%s %s' %(self.RequestItem,self.REF)
class Admin:
pass
def get_absolute_url(self):
return reverse('qoutation-list', kwargs={'pk':self.id})
class QoutationSelection(models.Model):
AcqID=models.ForeignKey(CreateACQModel,on_delete=None)
QoutID=models.ManyToManyField(QoutationModel)
Status=models.CharField(max_length=40,default='NotSeleted')
def __unicode__(self):
return self.REF
def __str__(self):
return '%s %s' %(self.REF)
error stack
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/ePROC/Qoutation/Attach/4/
Django Version: 2.0
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'django_filters',
'django_tables2',
'rest_framework',
'crispy_forms',
'taggit',
'jquery',
'chartit',
'ePROC']
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 "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\edit.py" in post
172. return super().post(request, *args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\edit.py" in post
142. return self.form_valid(form)
File "C:\Users\NajVM\BANKERP\ePROC\views.py" in form_valid
228. form.instance.AcqID=CreateACQModel.objects.get(self.kwargs['pk'])
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py" in get
394. clone = self.filter(*args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py" in filter
836. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
854. clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\query.py" in add_q
1252. clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\query.py" in _add_q
1276. split_subq=split_subq,
File "C:\Users\NajVM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\query.py" in build_filter
1149. arg, value = filter_expr
Exception Type: ValueError at /ePROC/Qoutation/Attach/4/
Exception Value: not enough values to unpack (expected 2, got 1)
You need to use the primary key as a kwarg when fetching the object:
form.instance.AcqID=CreateACQModel.objects.get(pk=self.kwargs['pk'])
At the moment, you'll get a DoesNotExist exception which will lead to a 500 server error if there is not object with that primary key in the database. You could use the get_object_or_404 shortcut to return a 404 page instead.
from django.shortcuts import get_object_or_404
form.instance.AcqID=get_object_or_404(CreateACQModel, pk=self.kwargs['pk'])

Model thinks my string is tuple and won't save

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

Django Model validate_unique method don't raise ValidationError

My model is :
class Inventory(models.Model):
canteen_id = models.IntegerField()
item = models.OneToOneField('Info',db_column='item_id')
I want item should be unique for each canteen_id. I used unique_togetherbut its not working as item is in OneToOneField.
I am using validate_unique method for my model and my code is now:
class Inventory(models.Model):
canteen_id = models.IntegerField()
item = models.OneToOneField('Info',db_column='item_id')
unit_price = models.CharField(max_length=50)
quantity = models.PositiveIntegerField(default=1)
sales_vat = models.DecimalField(decimal_places=2,max_digits=5,default=0.0)
date_time = models.DateField(auto_now=False,auto_now_add=True)
def vat_count(self):
self.item_price = Decimal(self.unit_price)
self.vat = (self.item_price * 15)/100
return self.vat
def validate_unique(self, exclude=None):
qs = Inventory.objects.filter(canteen_id=self.canteen_id)
if self.pk is None:
if qs.filter(item=self.item).exists():
raise ValidationError("item already exists")
def save(self, *args,**kwargs):
self.canteen_id = CANTEEN_ID
self.sales_vat = self.vat_count()
self.unit_price = Decimal(self.unit_price)
self.validate_unique()
super(Inventory,self).save(*args, **kwargs)
Now when I am trying to add same item and canteen_id, it don't raise any error message in form page. It shows error. Error:
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/item/inventory/add/
Django Version: 1.9.2
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',
'item',
'bill',
'system']
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']
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
541. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
1437. return self.changeform_view(request, None, form_url, extra_context)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in inner
184. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view
1378. self.save_model(request, new_object, form, not add)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_model
991. obj.save()
File "/home/harun/Desktop/nutboltu/canteenLatest/CanteenKiosk/diucanteen/item/models.py" in save
34. self.validate_unique()
File "/home/harun/Desktop/nutboltu/canteenLatest/CanteenKiosk/diucanteen/item/models.py" in validate_unique
27. raise ValidationError("item already exists")
Exception Type: ValidationError at /admin/item/inventory/add/
Exception Value: [u'item already exists']
What is the solution???
If you override validate_unique method in your model you should call super as you do in save/delete etc.
def validate_unique(self, exclude=None):
# custom logic
super(Inventory, self).validate_unique(exclude=exclude)
Thanks all to help me find out my problem. My code was correct but I made a mistake in query. I am getting canteen_id value by assigning a variable CANTEEN_ID in settings.py and save it by save() method.
So, My query should be:
from projectdir.settings import CANTEEN_ID
def validate_unique(self,exclude=None):
qs = Inventory.objects.filter(canteen_id=CANTEEN_ID)
Firstly, I think unique_together should work with a one to one field. If you can create a simple test case that shows that it doesn't, then it would be worth creating a bug report.
If you do want to check the unique constraint manually, don't do it in the save() method. The Django admin doesn't expect a validation error to be raised in the save method, so you get the error. Instead, override the model's clean method, and do the check in. Model forms, including the ones in the Django admin, will call the clean method when processing the form data.
class Inventory(models.Model):
...
def clean(self):
qs = Inventory.objects.filter(canteen_id=self.canteen_id)
if self.pk is None:
if qs.filter(item=self.item).exists():
raise ValidationError("item already exists")
See the docs on validating objects for more info.
The way CANTEEN_ID is provided for save method may hide solution.

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'.