Django: ValueError no ForeignKey to model in Admin - django

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

Related

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'])

Custom validation Django admin unknown field

I am trying to make a custom validation for the imageField in the admin panel, but I get the following error. There is nog field with the namen banner_image in the Event model class, but when I change field = ('banner_image',) to something else I get instead of "specified for Event" specified for EventBanner. most solutions I find for making a custom validation are for older versions of Django.
django.core.exceptions.FieldError: Unknown field(s) (banner_image) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin.
app admin.py:
class BannerImageForm(forms.ModelForm):
class Meta:
model = EventBanner
fields = ['banner_image',]
def clean_banner_image(self):
banner_image = self.cleaned_data['banner_image']
if not banner_image:
raise forms.ValidationError("No image!")
else:
w, h = get_image_dimensions(banner_image)
if w != 1200:
raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 1200px" % w)
if h != 200:
raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
return banner_image
class EventAdmin(admin.ModelAdmin):
form = BannerImageForm
list_display = ('event_name', 'event_start_date')
formfield_overrides={
models.TextField:{'widget':Textarea(attrs={'rows':15, 'cols':80})}
}
admin.site.register(Event, EventAdmin)
app models.py:
class EventBanner(models.Model):
event = models.OneToOneField(Event, unique=True)
banner_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
def clean(self):
validate_only_one_instance(self)
TraceBack:
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/events/event/1/change/
Django Version: 1.10.4
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'organizations.apps.OrganizationsConfig',
'news.apps.NewsConfig',
'events.apps.EventsConfig',
'bootstrap3',
'django_forms_bootstrap',
'registration']
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',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware']
Traceback:
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_form
642. return modelform_factory(self.model, **defaults)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/forms/models.py" in modelform_factory
548. return type(form)(class_name, (form,), form_class_attrs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/forms/models.py" in __new__
257. raise FieldError(message)
During handling of the above exception (Unknown field(s) (banner_image) specified for Event), another exception occurred:
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
544. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
211. return view(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in change_view
1512. return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.5/contextlib.py" in inner
30. return func(*args, **kwds)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in changeform_view
1438. ModelForm = self.get_form(request, obj)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_form
608. fields = flatten_fieldsets(self.get_fieldsets(request, obj))
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_fieldsets
298. return [(None, {'fields': self.get_fields(request, obj)})]
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_fields
597. form = self.get_form(request, obj, fields=None)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_form
646. % (e, self.__class__.__name__)
Exception Type: FieldError at /admin/events/event/1/change/
Exception Value: Unknown field(s) (banner_image) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin.
The form for EventAdmin must use the Event model. You get the error because BannerImageForm form uses the EventBanner model.
Create an EventBannerAdmin, and get your code working with that. Then, you could change it to an inline, and include the inline in the EventAdmin.

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