Custom validation Django admin unknown field - django

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.

Related

Django admin form process file upload: 'InMemoryUploadedFile' object has no attribute 'width'

I have this model
class CauroselImage(models.Model):
title = models.CharField(max_length=200, blank=True)
description = models.CharField(max_length=400, blank=True)
image = models.ImageField(upload_to=settings.UPLOAD_DIR,)
visible = models.BooleanField(default=True)
def __str__(self):
return self.title
that i want to set the image file minimum dimensions and I've found out the forms.py file is the way to go
class CauroselImageForm(forms.ModelForm):
class Meta:
model = CauroselImage
exclude = ('',)
def clean(self):
cleaned_data = self.cleaned_data
image = cleaned_data.get('image')
if image.width < 1300 or image.height < 400:
raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400")
return cleaned_data
and admin
class CauroselImageAdmin(admin.ModelAdmin):
form = CauroselImageForm
admin.site.register(CauroselImage, CauroselImageAdmin)
it however throws this error
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/pages/cauroselimage/1/change/
Django Version: 3.1.2
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'guides',
'pages',
'sorl.thumbnail',
'ckeditor',
'django.contrib.sites',
'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1656, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1573, in _changeform_view
form_validated = form.is_valid()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid
return self.is_bound and not self.errors
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors
self.full_clean()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 375, in full_clean
self._clean_form()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 402, in _clean_form
cleaned_data = self.clean()
File "/home/sam/code/kpsga/pages/forms.py", line 26, in clean
if image.width < 1300 or image.height < 400:
Exception Type: AttributeError at /admin/pages/cauroselimage/1/change/
Exception Value: 'InMemoryUploadedFile' object has no attribute 'width'
You can use from django get_image_dimensions:
from django.core.files.images import get_image_dimensions
class CauroselImageForm(forms.ModelForm):
...
def clean(self):
width, height = get_image_dimensions(self.cleaned_data.get('image'))
if width < 1300 or height < 400:
raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400")
return cleaned_data
Method get_image_dimensions is using python PIL (Python Imaging Library).
get_image_dimensions returns the (width, height) of an image, given
an open file or a path. Set 'close' to True to close the file at the
end if it is initially in an open state.

ValueError: not enough values to unpack (expected 2, got 1) in Django

I'm having a problem in saving data to two tables of my database which is PurchaseOrder and PurchaseOrderLineItems using the generic view of Django the CreateView.
I'm getting this error: ValueError: not enough values to unpack (expected 2, got 1) and I don't know where in the code is the error.
I'm getting the data from a html table ( it has checkbox per row ) that is generated by another table called Masterlist that will save in PurchaseOrderLineItems.
Here's what I tried by searching of how can I save the data. I created a post function inside the CreateView class.
class PurchaseOrderCreateView(LoginRequiredMixin, CreateView):
model = PurchaseOrder
fields = ['project_site', 'supplier']
def form_valid(self, form):
form.instance.prepare_by = self.request.user
return super().form_valid(form)
def get_context_data(self, **kwargs):
kwargs['object_list'] = Masterlist.objects.all()
return super(PurchaseOrderCreateView, self).get_context_data(**kwargs)
def post(self, request, *args, **kwargs):
po = PurchaseOrder.objects.all()
if request.method == 'POST':
get_list = request.POST.getlist('checks[]')
for item in get_list:
get_id = Masterlist.objects.filter(item[0])
save_to_pol = PurchaseOrderLineItems(item_no=get_id.item_no, description=get_id.description, dimension=get_id.dimension, unit=get_id.unit, quantity=get_id.quantity, cost=get_id.cost, total=get_id.cost * get_id.quantity, po_fk=pk)
save_to_pol.save()
return super().post(request)
Error Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/lastmile/purchaseorder/new/
Django Version: 2.1.4
Python Version: 3.7.1
Installed Applications:
['users.apps.UsersConfig',
'lastmile.apps.LastmileConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/contrib/auth/mixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/Application/ERP/lastmile/views.py" in post
57. get_id = Masterlist.objects.filter(item[0])
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/db/models/query.py" in filter
844. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/db/models/query.py" in _filter_or_exclude
862. clone.query.add_q(Q(*args, **kwargs))
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/db/models/sql/query.py" in add_q
1263. clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/db/models/sql/query.py" in _add_q
1287. split_subq=split_subq,
File "/Users/workstationthreesoftwaredeveloper/JXMTSI/Projects/Office/Application/Web-Application/Django/environ/lib/python3.7/site-packages/django/db/models/sql/query.py" in build_filter
1161. arg, value = filter_expr
Exception Type: ValueError at /lastmile/purchaseorder/new/
Exception Value: not enough values to unpack (expected 2, got 1)
What I want is when the user fills up the fields for the PurchaseOrder and then checked the items in the html table (generated by Masterlist) and hit the button, it will save the the checked items in the PurchaseOrderLineItems

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 admin validation not working propely after making custom model validation work

I have a Django model that uploads photos to a user's account. The upload model uses a Django auth user as a foreign key. I needed to ensure that each user could only upload 20 photos total and I wanted to do this at the model level so even the admin could not upload more. I got that working in a way but it broke my admin form validation. If I choose a related user, everything goes perfectly. It stops me from uploading more than 20 photos. But if I don't choose a user it gives me RelatedObjectDoesNotExist error. I am including my code and traceback here. Help would be appreciated.
My models.py
def photo_count(self):
theModel = self.__class__
refModel = theModel.objects.filter(user=self.user)
picCount = refModel.count()
if picCount ==20:
print(picCount)
raise ValidationError ("You have already uploaded 20 photos. Delete some to upload more.")
class StarPhotos(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
PHOTO_CATEGORY = (
('HS', "Head Shot"),
('WP', "Western Party Wear"),
('IP', "Indian Party Wear"),
('SW', "Swim Wear"),
('CW', "Casual Wear"),
)
category = models.CharField(max_length=2, choices=PHOTO_CATEGORY, default='CW')
# This FileField should preferaby be changed to ImageField with pillow installed.
photos = models.FileField(max_length=200, upload_to='images/',)
def __str__(self):
return "Images for {0}".format(self.user)
def clean(self):
photo_count(self)
class Meta:
verbose_name_plural = "Star Photos"
Traceback
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/castar/starphotos/add/
Django Version: 1.11.1
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',
'castar.apps.CastarConfig']
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 "D:\websites\powah\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "D:\websites\powah\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\websites\powah\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\sites.py" in inner
224. return view(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in add_view
1508. return self.changeform_view(request, None, form_url, extra_context)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in changeform_view
1408. return self._changeform_view(request, object_id, form_url, extra_context)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in _changeform_view
1440. if form.is_valid():
File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in full_clean
386. self._post_clean()
File "D:\websites\powah\lib\site-packages\django\forms\models.py" in _post_clean
396. self.instance.full_clean(exclude=exclude, validate_unique=False)
File "D:\websites\powah\lib\site-packages\django\db\models\base.py" in full_clean
1233. self.clean()
File "D:\websites\powah\src\castar\models.py" in clean
75. photo_count(self)
File "D:\websites\powah\src\castar\models.py" in photo_count
49. refModel = theModel.objects.filter(user=self.user)
File "D:\websites\powah\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
194. "%s has no %s." % (self.field.model.__name__, self.field.name)
Exception Type: RelatedObjectDoesNotExist at /admin/castar/starphotos/add/
Exception Value: StarPhotos has no user.

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.