I am using PostgreSQL with Django and am trying to use ArrayField(models.EmailField(max_length=200)). But I am ending up with an 500 error code(TypeError) when giving invalid email address.
How can I validate each email in the ArrayField. I have tried writing validate method in both serializer and models. But nothing helped. What is the right way to validate ArrayFields? I am using Django 2.1 and Python 3.6
The traceback of the error is given below...please have a look
models.py
billing_emails = ArrayField(models.EmailField(max_length=200))
company = models.OneToOneField(Company, on_delete=models.CASCADE)
Traceback
Traceback (most recent call last):
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response
response = response.render()
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/render.py", line 8, in render
return super(CamelCaseJSONRenderer, self).render(camelize(data), *args,
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/util.py", line 17, in camelize
new_dict[new_key] = camelize(value)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/util.py", line 16, in camelize
new_key = re.sub(r"[a-z]_[a-z]", underscoreToCamel, key)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
Thanks in advance.
If you are using Forms, use Form or Serializer, you can use the clean_<attribute_name> method to validate the data. For example:
from django.core.validators import email_re
from django.core.exceptions import ValidationError
class YourForm(forms.ModelForm): # serializers.ModelSerializer
def clean_billing_emails(self):
data = self.cleaned_data['billing_emails']
for email in data:
if not email_re.match(email):
raise ValidationError('Invalid email {}'.format(email) # or raise serializers.ValidationError
return data
Also you can use model's clean method.
class YourModel(models.Model):
...
def clean(self):
try:
for email in self.billing_emails:
if not email_re.match(email):
raise ValidationError('Invalid email {}'.format(email)
except (TypeError, Exception) as e:
# log error
# handle error
def save(self, *args, **kwargs):
self.full_clean()
return super(YourModel, self).save(*args, **kwargs)
Related
Not sure why but my code is getting the following error:
ValueError: too many values to unpack (expected 2)
Here is my models.py:
class UserList(models.Model):
list_name = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.list_name
Here is my views.py
def otherUserList(request):
userName = request.GET.get('userName', None)
print(userName)
qs = UserList.objects.filter(user__username=userName)
return qs
Here is the traceback:
Internal Server Error: /electra/otheruserlist/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
[02/Sep/2021 05:38:43] "GET /electra/otheruserlist/?userName=alice HTTP/1.1" 500 94227
I'd be very grateful for any assistance.
Your view is returning a QuerySet, but that does not make much sense: a view should return a HttpResponse. You can for example render a template, convert it to JSON, etc.
We can for example render a template with:
from django.shortcuts import render
def otherUserList(request):
userName = request.GET.get('userName', None)
qs = UserList.objects.filter(user__username=userName)
return render(request, 'some-template.html', {'lists': qs})
Or we can for example return a JsonResponse wit the list_name`s of user the user with the given username with:
from django.http import JsonField
def otherUserList(request):
userName = request.GET.get('userName', None)
qs = UserList.objects.filter(user__username=userName)
return JsonResponse({'listnames': [list.name for list in qs]})
The exception comes from a Django internal middleware, since it's trying to process your returned qs as a response.
You'll need to return a response, not just a queryset, e.g. this simple example to return a list of user IDs.
from django.http import JsonResponse
def otherUserList(request):
userName = request.GET.get('userName', None)
print(userName)
qs = UserList.objects.filter(user__username=userName)
return JsonResponse({"ids": [user.id for user in qs]})
So I have a model like this
from django.db import models
from sorl.thumbnail import get_thumbnail
class Upload(BaseModel):
#staticmethod
def upload_path_handler(instance, filename):
return f'boxes/{instance.box.id}/uploads/{filename}'
#staticmethod
def thumbnail_path_handler(instance, filename):
return f'boxes/{instance.box.id}/thumbnails/{filename}'
def save(self, *args, **kwargs):
if self._state.adding:
# we cache the file size and store
# it into the database to improve performance
# we cannot edit the object's file so we don't
# bother to modify the file size on updates
self.size = self.file.size
super(Upload, self).save(*args, **kwargs)
thumbnail = get_thumbnail(self.file, '1280x720', crop='center')
# sorl is not saving the thumbnails for non-image files
return self.thumbnail.save(thumbnail.name, ContentFile(thumbnail.read()), True)
super(Upload, self).save(*args, **kwargs)
objects = api_managers.UploadManager()
size = models.PositiveBigIntegerField()
name = models.CharField(max_length=100, default='untitled', validators=[MinLengthValidator(2)])
channel = models.ForeignKey('api_backend.Channel', on_delete=models.CASCADE, editable=False)
box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE, editable=False)
owner = models.ForeignKey('api_backend.User', on_delete=models.CASCADE, editable=False)
thumbnail = models.ImageField(max_length=512, upload_to=thumbnail_path_handler.__func__, null=True, blank=True)
file = models.FileField(max_length=512, upload_to=upload_path_handler.__func__)
REQUIRED_FIELDS = [file, owner]
the file field can be literally any file, and I want sorl-thumbnail to make a thumbnail for the same and save it into the thumbnail field. I am on windows and am using ImageMagick. [python version- 32 bits]
this is the binary distribution I installed.
https://imagemagick.org/script/download.php
ImageMagick-7.0.10-61-Q16-x86-dll.exe Win32 dynamic at 16 bits-per-pixel component
settings.py
THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.convert_engine.Engine'
However, whenever an upload-model is saved, I get the following error.
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\iyapp\\PycharmProjects\\rebox\\media\\cache\\db\\5a\\db5a88e1d6a08cdfa1afbc92e9b8cb47.jpg'
Full traceback:
Exception ignored in: <function TemporaryFile.__del__ at 0x04184610>
Traceback (most recent call last):
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\core\files\temp.py", line 61, in __del__
self.close()
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\core\files\temp.py", line 49, in close
if not self.close_called:
AttributeError: 'TemporaryFile' object has no attribute 'close_called'
__init__() got an unexpected keyword argument 'delete'
Traceback (most recent call last):
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\sorl\thumbnail\base.py", line 104, in get_thumbnail
source_image = default.engine.get_image(source)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\sorl\thumbnail\engines\convert_engine.py", line 76, in get_image
with NamedTemporaryFile(mode='wb', delete=False) as fp:
TypeError: __init__() got an unexpected keyword argument 'delete'
Remote file [boxes/2/uploads/a243bfbd00fdcb54982faf63cfc290b1dfcd47f1c0484facbd67c8b8ff606aff.jpg] at [1280x720] does not exist
exc: [Errno 2] No such file or directory: 'C:\\Users\\iyapp\\PycharmProjects\\rebox\\media\\cache\\db\\5a\\db5a88e1d6a08cdfa1afbc92e9b8cb47.jpg'
Internal Server Error: /api/channels/1/uploads/
Traceback (most recent call last):
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\asgiref\sync.py", line 339, in thread_handler
raise exc_info[1]
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\core\handlers\exception.py", line 38, in inner
response = await get_response(request)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async
response = await wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\asgiref\sync.py", line 304, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "c:\python38\lib\asyncio\tasks.py", line 455, in wait_for
return await fut
File "c:\python38\lib\concurrent\futures\thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\asgiref\sync.py", line 343, in thread_handler
return func(*args, **kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\generics.py", line 242, in post
return self.create(request, *args, **kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
serializer.save()
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\serializers.py", line 205, in save
self.instance = self.create(validated_data)
File "C:\Users\iyapp\PycharmProjects\rebox\api_backend\serializers\partial.py", line 35, in create
return super(PartialUploadSerializer, self).create(validated_data)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\rest_framework\serializers.py", line 939, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\iyapp\PycharmProjects\rebox\api_backend\models\uploads.py", line 43, in save
return self.thumbnail.save(thumbnail.name, ContentFile(thumbnail.read()), True)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\sorl\thumbnail\images.py", line 162, in read
f = self.storage.open(self.name)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\core\files\storage.py", line 36, in open
return self._open(name, mode)
File "C:\Users\iyapp\Envs\rebox_django\lib\site-packages\django\core\files\storage.py", line 231, in _open
return File(open(self.path(name), mode))
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\iyapp\\PycharmProjects\\rebox\\media\\cache\\db\\5a\\db5a88e1d6a08cdfa1afbc92e9b8cb47.jpg'
Can someone please help me fix this?
thanks a lot!
as far as I know this is why the first exception arises.
from django.core.files.temp import NamedTemporaryFile
https://github.com/jazzband/sorl-thumbnail/blob/master/sorl/thumbnail/engines/convert_engine.py#L8
this import returns a TemporaryFile
(see source code)
"""
The temp module provides a NamedTemporaryFile that can be reopened in the same
process on any platform. Most platforms use the standard Python
tempfile.NamedTemporaryFile class, but Windows users are given a custom class.
This is needed because the Python implementation of NamedTemporaryFile uses the
O_TEMPORARY flag under Windows, which prevents the file from being reopened
if the same flag is not provided [1][2]. Note that this does not address the
more general issue of opening a file for writing and reading in multiple
processes in a manner that works across platforms.
The custom version of NamedTemporaryFile doesn't support the same keyword
arguments available in tempfile.NamedTemporaryFile.
1: https://mail.python.org/pipermail/python-list/2005-December/336957.html
2: https://bugs.python.org/issue14243
"""
import os
import tempfile
from django.core.files.utils import FileProxyMixin
__all__ = ('NamedTemporaryFile', 'gettempdir',)
if os.name == 'nt':
class TemporaryFile(FileProxyMixin):
"""
Temporary file object constructor that supports reopening of the
temporary file in Windows.
Unlike tempfile.NamedTemporaryFile from the standard library,
__init__() doesn't support the 'delete', 'buffering', 'encoding', or
'newline' keyword arguments.
"""
def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='', dir=None):
fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
self.name = name
self.file = os.fdopen(fd, mode, bufsize)
self.close_called = False
# Because close can be called during shutdown
# we need to cache os.unlink and access it
# as self.unlink only
unlink = os.unlink
def close(self):
if not self.close_called:
self.close_called = True
try:
self.file.close()
except OSError:
pass
try:
self.unlink(self.name)
except OSError:
pass
def __del__(self):
self.close()
def __enter__(self):
self.file.__enter__()
return self
def __exit__(self, exc, value, tb):
self.file.__exit__(exc, value, tb)
NamedTemporaryFile = TemporaryFile
else:
NamedTemporaryFile = tempfile.NamedTemporaryFile
gettempdir = tempfile.gettempdir
and the TemporayFile class' init method doesn't take any parameter named delete. instead, only tempfile.NamedTemporaryFile does. Therefore, this chunk of code fails.
def get_image(self, source):
"""
Returns the backend image objects from a ImageFile instance
"""
with NamedTemporaryFile(mode='wb', delete=False) as fp:
fp.write(source.read())
return {'source': fp.name, 'options': OrderedDict(), 'size': None}
https://github.com/jazzband/sorl-thumbnail/blob/master/sorl/thumbnail/engines/convert_engine.py#L72
I think that because of this the file isn't being saved at all.
And at last, inside the save method of the model,
We see the backend raise that the file doesn't exist.
So I´ve tried to make an ajax for my models but it is giving me a matching query does not exist, here is the full error:
Internal Server Error: /messages/notification/
Traceback (most recent call last):
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\detail.py", line 106, in get
self.object = self.get_object()
File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\views.py", line 26, in get_object
obj, created = Thread.objects.get_or_new(self.request.user, other_username)
File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\models.py", line 29, in get_or_new
user2 = Klass.objects.get(username=other_username)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 415, in get
raise self.model.DoesNotExist(
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
HTTP GET /messages/notification/ 500 [0.16, 127.0.0.1:56012]
Also here is my code:
models.py
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),
#to=settings.AUTH_USER_MODEL,
to = User,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
notifications = models.FloatField(default='0')
views.py
def notifications(request, user_id, *args, **kwargs):
user = User.objects.get(pk=user_id)
user.profile.notifications = user.profile.notifications + 1
user.save()
return JsonResponse(data=user.profile.notifications, safe=False)
urls.py
path('messages/notification/', notifications)
my html for the ajax call
// Add the notification val
$.get('notification/')
someone tell me that is that I dont have users, but when I do have a user, I dont know what is going on
You need to send user_id to the view:
path('messages/notification/(?P<user_id>[a-zA-Z0-9/_\.-]*)', notifications)
and:
$.get('messages/notification/{{ user.pk }}')
Update
You have to know their user id to get their notifications:
$.get('messages/notification/12234')
I assume you have a User model somewhere?
Also, user_id is coming in as a string, so need to int() that:
user = User.objects.get(pk=int(user_id))
Or use:
path('messages/notification/<int:user_id>', notifications)
So for does who saw this later, what I did is to change the
path('messages/notification/', notifications)
To
url(r'^ajax/notification/$', notification),
I want to delete a user from the database that django comes with, i entered the admin site using my superuser but when i try to delete any user manually, which i created for testing purposes, it gives the error y mentioned above, the traceback inserted below is the one from the logs.
Error
Traceback (most recent call last):
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1727, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1397, in response_action
response = func(self, request, queryset)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/actions.py", line 40, in delete_selected
modeladmin.delete_queryset(request, queryset)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1098, in delete_queryset
queryset.delete()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/models/query.py", line 711, in delete
deleted, _rows_count = collector.delete()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/models/deletion.py", line 318, in delete
sender=model, instance=obj, using=self.using
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/transaction.py", line 240, in __exit__
connection.commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 262, in commit
self._commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
[06/May/2020 02:47:33] "POST /admin/auth/user/ HTTP/1.1" 500 142907
These is my model
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserRegister(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
first_name = models.CharField(max_length=256, default='', blank=False,)
last_name = models.CharField(max_length=256, default='', blank=False)
email = models.EmailField(unique=True, blank=False,default='')
def __str__(self):
return self.user.username
This is my form
from django import forms
from .models import *
from django.contrib.auth.models import User
#Create your forms here!
class UserRegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','password')
class UserRegisterInfoForm(forms.ModelForm):
class Meta():
model = UserRegister
fields = ('first_name','last_name','email')
This is my view
def UserRegisterFormView(request):
registered = False
if request.method == 'POST':
userform = UserRegisterForm(data=request.POST)
userinfoform = UserRegisterInfoForm(data=request.POST)
if userform.is_valid() and userinfoform.is_valid():
user = userform.save()
user.set_password(user.password)
user.save()
profile = userinfoform.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(userform.errors, userinfoform.errors)
else:
userform = UserRegisterForm
userinfoform = UserRegisterInfoForm
return render(request,'register/register.html'{'userform':userform,'userinfoform':userinfoform,'registered':registered})
You can delete the database except the init.py file. Then run makemigrations and migrate commands again.
If that dosen't fix it, then copy all the files in that folder into another folder, delete that folder, create a new one in your project directory, then pasted everything back in (be careful with your urls.py, don't forget to change them). Then run the makemigrations and migrate commands.
I am trying to restify my backend using django-rest-gis, in such a way that POST request adds data to database and GET request lists down the data. However, I am getting following error:-
Internal Server Error: /api/
Traceback (most recent call last):
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/generics.py", line 241, in get
return self.list(request, *args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/mixins.py", line 48, in list
return Response(serializer.data)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework_gis/serializers.py", line 20, in data
return super(ListSerializer, self).data
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework_gis/serializers.py", line 28, in to_representation
("features", super(GeoFeatureModelListSerializer, self).to_representation(data))
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 686, in to_representation
self.child.to_representation(item) for item in iterable
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 686, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework_gis/serializers.py", line 100, in to_representation
fields = list(self.fields.values())
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields
for key, value in self.get_fields().items():
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 1031, in get_fields
field_names, declared_fields, extra_kwargs
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 1378, in get_uniqueness_extra_kwargs
field_names, declared_fields, extra_kwargs
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 1450, in _get_model_fields
if field_name in declared_fields:
TypeError: unhashable type: 'list'
[25/May/2019 04:48:29] "GET /api/ HTTP/1.1" 500 147185
I have followed many answers on stackoverflow but could only get that it comes when you have a mutable type as key in dictionary
models.py
from django.contrib.gis.db import models
# Create your models here.
class test1(models.Model):
date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
location = models.PointField(blank=False)
plg = models.PolygonField(srid=4326, geography=True, null=True, blank=True)
city = models.CharField(max_length=50, blank=False)
state = models.CharField(max_length=50, blank=False)
def __str__(self):
return "%s" % (self.state)
serializers.py
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from .models import test1
class test1Serializer(GeoFeatureModelSerializer):
class Meta:
model = test1
geo_field = ['location','plg']
auto_bbox = True
id_field = False
fields = ('city','state')
views.py
from .models import test1
from .serializers import test1Serializer
from rest_framework.generics import ListCreateAPIView
class test1SerializerCreate(ListCreateAPIView):
serializer_class = test1Serializer
queryset = test1.objects.all()
GeoFeatureModelSerializer only takes one field and it doesn't take the list, check with one field and it should work. Use Rest for multiple fields and you can parse in views. Or you can make a new GeometrySerializerMethodField field and return two geometry in that
geo_field cannot be list.
It can be this way:
class test1Serializer(GeoFeatureModelSerializer):
m_geo_field = GeometrySerializerMethodField()
def get_m_geo_field(self, obj):
return # do whatever you like
class Meta:
model = Location
geo_field = 'm_geo_field'