django.urls.exceptions.NoReverseMatch - django-smart-selects - python-3.x

I am trying to implement django-smart-selects in my project but get errors when trying to add a record in my model from django admin. Here's my code:
models.py
class PricingConfiguration(CreateUpdateMixin):
name = models.CharField(max_length=50)
description = models.CharField(max_length=250)
appointent_category = models.ForeignKey(
AppointmentCategory,
null=True,
blank=True,
related_name="pricing_appointment_category",
on_delete=models.CASCADE,
)
speciality = models.ForeignKey(
Speciality,
null=True,
blank=True,
related_name="pricing_speciality",
on_delete=models.CASCADE,
)
sub_speciality = ChainedForeignKey(
SubSpeciality,
chained_field="speciality",
chained_model_field="speciality",
show_all=False,
auto_choose=True,
sort=True,
null=True,
blank=True,
)
urls.py
from django.urls import include, path, re_path
from django.contrib import admin
from rest_framework.routers import DefaultRouter
app_name = "configuration"
urlpatterns = [
re_path(r"^admin/", admin.site.urls),
re_path(r"^chaining/", include("smart_selects.urls")),
]
Errors:
django.urls.exceptions.NoReverseMatch
django.urls.exceptions.NoReverseMatch: Reverse for 'chained_filter' not found. 'chained_filter' is not a valid view function or pattern name.
Traceback (most recent call last)
File "/usr/local/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__
response = self.get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response
response = self._middleware_chain(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 149, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/local/lib/python3.9/site-packages/django_extensions/management/technical_response.py", line 40, in null_technical_500_response
raise exc_value.with_traceback(tb)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response
response = response.render()
File "/usr/local/lib/python3.9/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/usr/local/lib/python3.9/site-packages/django/template/response.py", line 83, in rendered_content
return template.render(context, self._request)
File "/usr/local/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 195, in render
return template.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 172, in render
return self._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 312, in render
return nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 312, in render
return nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 994, in render
return render_value_in_context(output, context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 973, in render_value_in_context
value = str(value)
File "/usr/local/lib/python3.9/site-packages/django/utils/html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/usr/local/lib/python3.9/site-packages/django/forms/boundfield.py", line 34, in __str__
return self.as_widget()
File "/usr/local/lib/python3.9/site-packages/django/forms/boundfield.py", line 93, in as_widget
return widget.render(
File "/usr/local/lib/python3.9/site-packages/django/forms/widgets.py", line 246, in render
context = self.get_context(name, value, attrs)
File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/widgets.py", line 283, in get_context
'rendered_widget': self.widget.render(name, value, attrs),
File "/usr/local/lib/python3.9/site-packages/smart_selects/widgets.py", line 107, in render
url = URL_PREFIX + ("/".join(reverse(view_name, kwargs=kwargs).split("/")[:-2]))
File "/usr/local/lib/python3.9/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'chained_filter' not found. 'chained_filter' is not a valid view function or pattern name.
I have also tried different variations in urls.py like following
urlpatterns = [
re_path(r"^admin/", admin.site.urls),
re_path(r"^admin/", include("smart_selects.urls")),
]
and
urlpatterns = [
re_path(r"^chaining/", include("smart_selects.urls")),
]
but nothing seems to be working.
My django version is 3.2.5 and I'm using latest version of django-smart-selects. If anyone can let me know how to fix this issue, it would be really appreciated. Thanks.

Related

discord.py Error - ClientConnectorCertificateError

I have an error trying to run my python discord bot.
Here's my code:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return None
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('<redacted>')
When I run this, I get the following error code: aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123)')]
Full error traceback:
Traceback (most recent call last):
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\connector.py", line 936, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 1050, in create_connection
transport, protocol = await self._create_connection_transport(
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 1080, in _create_connection_transport
await waiter
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\asyncio\sslproto.py", line 529, in data_received
ssldata, appdata = self._sslpipe.feed_ssldata(data)
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\asyncio\sslproto.py", line 189, in feed_ssldata
self._sslobj.do_handshake()
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\ssl.py", line 944, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\shalev\.vscode\extensions\ms-python.python-2020.9.111407\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\Users\shalev\.vscode\extensions\ms-python.python-2020.9.111407\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\shalev\.vscode\extensions\ms-python.python-2020.9.111407\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 267, in run_file
runpy.run_path(options.target, run_name=compat.force_str("__main__"))
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 265, in run_path
return _run_module_code(code, init_globals, run_name,
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "f:\python projects\among us bot.py", line 17, in <module>
client.run('<redacted>')
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 678, in run
return future.result()
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 658, in runner
await self.start(*args, **kwargs)
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 621, in start
await self.login(*args, bot=bot)
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 472, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 288, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 185, in request
async with self.__session.request(method, url, **kwargs) as r:
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
self._resp = await self._coro
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 480, in _request
conn = await self._connector.connect(
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\connector.py", line 523, in connect
proto = await self._create_connection(req, traces, timeout)
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\connector.py", line 858, in _create_connection
_, proto = await self._create_direct_connection(
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\connector.py", line 1004, in _create_direct_connection
raise last_exc
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\connector.py", line 980, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "C:\Users\shalev\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\connector.py", line 938, in _wrap_create_connection
raise ClientConnectorCertificateError(
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123)')]
Can anyone help me with this?
Try updating discord.py.
pip install -U discord.py
Worked personally for me.

TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts'

While adding groups with permission from Django Admin Panel and adding other M2M relationships too. I got this error!!
It says : TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts'
I can't find the error, Probably a noob mistake.
class GroupSerializer(serializers.ModelSerializer):
permissions = PermissionSerializerGroup(many=True, required=False)
class Meta:
model = Group
fields = ('id', 'name', 'permissions')
extra_kwargs = {
'name': {'validators': []},
}
def create(self, validated_data):
print(validated_data)
permissions_data = validated_data.pop("permissions")
obj, group = Group.objects.update_or_create(name=validated_data["name"])
obj.permissions.clear()
for permission in permissions_data:
per = Permission.objects.get(codename=permission["codename"])
obj.permissions.add(per)
obj.save()
return obj
Here is the Traceback:
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1638, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1522, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1566, in _changeform_view
self.save_related(request, form, formsets, not add)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1107, in save_related
form.save_m2m()
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/forms/models.py", line 442, in _save_m2m
f.save_form_data(self.instance, cleaned_data[f.name])
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1618, in save_form_data
getattr(instance, self.attname).set(data)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1008, in set
self.add(*new_objs, through_defaults=through_defaults)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 946, in add
through_defaults=through_defaults,
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1129, in _add_items
], ignore_conflicts=True)
TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts'
I solved this issue by downgrading Django version to 2.2.12
It seems that Django v3.0+ has this issue
This has been fixed in github: https://github.com/martinphellwig/django-query-signals/commit/a3ed59614287f1ef9e7398d325a8bbcc11bf0b3c but it's not in pypi, you need to install django-query-signals from git

flask_restful - TypeError: Object of type Record is not JSON serializable

I try to provide a custom object inside a rest api, created with flask_restful.
Object: Record
import json
class Record():
#CLASS RECORD
def __init__(self, DateTime, DateTimeText, Status, Icon, Temp):
#INITIALIZE
self.DateTime = DateTime
self.DateTimeText = DateTimeText
self.Status = Status
self.Icon = Icon
self.Temp = Temp
def __repr__(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=False, indent=4)
Result: print(record)
{
"DateTime": 1583949600,
"DateTimeText": "2020-03-11 18:00:00",
"Status": "Clouds",
"Icon": "04n",
"Temp": 280.57
}
Rest API:
from flask_restful import Resource, Api, reqparse
class _Weather(Resource):
#WEATHER
def get(self):
#GET WEATHER
return {'value': Weather.Record}
self.Api.add_resource(_Weather, '/api/weather')
Error:
all other calls works fine, only me custom object (http://localhost:80/api/weather) returns the following error stack:
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 472, in wrapper
return self.make_response(data, code, headers=headers)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 501, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\representations\json.py", line 21, in output_json
dumped = dumps(data, **settings) + "\n"
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Record is not JSON serializable
I try a lot of different approaches, found here on stack. Non of these works for my.
Python 3.8.2
You have a couple of options here.
Make a tojson() method for your Record class and call that for your return value. It will basically just return the underlying __dict__ for your object.
def tojson(self):
return self.__dict__
Pass Weather.Record.__dict__ directly as your return value
So your return statement will look like one of these:
return {'value': Weather.Record.__dict__}
Or, using jsonify from Flask:
return jsonify({'value': 'Weather.Record.__dict__})
Or replace Weather.Record.__dict__ with Weather.Record.tojson() if you add that method to the class.

Unable to upload image on remote server(Heroku) with my flask app

My app image upload works very well on localhost but when I deployed to Heroku, it gives me Attribute Error and Runtime Error. How do I solve this?
I remove the validators on the filefield in my form as suggested by some people here but it did not solve the problem
##########
#views.py
def add_post():
form = AddPostForm()
if request.method == 'POST':
if form.validate_on_submit():
filename = images.save(request.files['post_image'])
url = images.url(filename)
new_post = Post( form.post_title.data,
form.post_description.data,
current_user.id, form.is_public.data,
filename, url, form.Share_location.data,
form.home_delivery.data, form.share_date.data,
form.total_slot.data, form.slot_value.data,
form.payable_amount.data, form.no_of_months.data,
form.no_of_weeks.data, form.no_of_days.data,
form.month_sub.data, form.week_sub.data,
form.day__sub.data)
db.session.add(new_post)
db.session.commit()
flash('New shared Item, {}, added!'.format(new_post.post_title),
'success')
return redirect(url_for('posts.public_posts'))
else:
flash_errors(form)
flash('ERROR! Share item was not added.', 'error')
return render_template('add_post.html', title='Add Item', form=form)
#############
#__init__.py
app = Flask(__name__, instance_relative_config=True)
if isfile(join('instance', 'flask_full.cfg')):
app.config.from_pyfile('flask_full.cfg')
else:
app.config.from_pyfile('flask.cfg')
app.config.from_pyfile('flask.cfg')
db = SQLAlchemy(app)
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
#flask.cfg
UPLOADS_DEFAULT_DEST = TOP_LEVEL_DIR + '/project/static/img/'
UPLOADED_IMAGES_URL = 'https://bulkieshare.herokuapp.com/static/img/'
UPLOADED_IMAGES_DEST = TOP_LEVEL_DIR + '/project/static/img/'
UPLOADED_IMAGES_URL = 'https://bulkieshare.herokuapp.com/static/img/'
I want to successfully upload an image file to my remote database but I kept getting these error messages from Heroku.
#Here is the error message:
[2019-07-12 09:08:40 +0000] [16] [ERROR] Error handling request /add
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/flask_uploads.py",
line 327, in config
return current_app.upload_set_config[self.name]
File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/local.py",
line 347, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'Flask' object has no attribute 'upload_set_config'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-
packages/gunicorn/workers/sync.py", line 135, in handle
self.handle_request(listener, req, client, addr)
File "/app/.heroku/python/lib/python3.6/site-
packages/gunicorn/workers/sync.py", line 176, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
2309, in __call__
return self.wsgi_app(environ, start_response)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
2295, in wsgi_app
response = self.handle_exception(e)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py",
line 35, in reraise
raise value
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
2292, in wsgi_app
response = self.full_dispatch_request()
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py",
line 35, in reraise
raise value
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
1813, in full_dispatch_request
rv = self.dispatch_request()
File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line
1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/.heroku/python/lib/python3.6/site-
packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "/app/project/posts/views.py", line 68, in add_post
filename = images.save(request.files['post_image'])
File "/app/.heroku/python/lib/python3.6/site-packages/flask_uploads.py",
line 414, in save
if not self.file_allowed(storage, basename):
File "/app/.heroku/python/lib/python3.6/site-packages/flask_uploads.py",
line 370, in file_allowed
return self.extension_allowed(extension(basename))
File "/app/.heroku/python/lib/python3.6/site-packages/flask_uploads.py",
line 380, in extension_allowed
return ((ext in self.config.allow) or
File "/app/.heroku/python/lib/python3.6/site-packages/flask_uploads.py",
line 329, in config
raise RuntimeError("cannot access configuration outside request")
RuntimeError: cannot access configuration outside request
10.31.79.212 - - [12/Jul/2019:09:08:40 +0000] "POST /add HTTP/1.1" 500 0
"-" "-"

unit testing for unverified user trying to login

I've been trying to test for a user that hasn't been verified.
class TestLoginApi(TestCase):
URL = '/rest-auth/login/'
EMAIL = 'testuser#test
PASSWORD = 'password'
DATA = {'email': EMAIL, 'password': PASSWORD}
#classmethod
def setUpTestData(cls):
cls.user = get_user_model().objects.create_user(username='testuser', email=cls.EMAIL,
password=cls.PASSWORD)
def test_login_api_without_verification(self):
response = self.client.post(self.URL, self.DATA, format='json')
The "response" line throws the following error
Error
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
yield
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 601, in run
testMethod()
File "/Users/docdocengineering3/GitHub/website/project/authorization/Tests/test_login.py", line 34, in test_login_api_without_verification
response = self.client.post(self.URL, self.DATA, format='json')
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 548, in post
secure=secure, **extra)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 350, in post
secure=secure, **extra)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 416, in generic
return self.request(**r)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 501, in request
six.reraise(*exc_info)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/six.py", line 686, in reraise
raise value
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.get(self, type(self))(*args2, **kwargs2)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/views.py", line 49, in dispatch
return super(LoginView, self).dispatch(*args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/views.py", line 92, in post
self.serializer.is_valid(raise_exception=True)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/serializers.py", line 237, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/serializers.py", line 435, in run_validation
value = self.validate(value)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/serializers.py", line 105, in validate
email_address = user.emailaddress_set.get(email=user.email)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get
self.model._meta.object_name
Exception: EmailAddress matching query does not exist.
I have no idea why this is happening. It isn't a setup problem as I've tried actually running the system, creating a user (not verifying) and when I "PostMan" the same link, I get the correct error back
{"non_field_errors": [ "E-mail is not verified." ] }
So it works in the actual product but not when testing. Anyone know why? Any help is greatly appreciated.
This is the only test that I can't get to work, all the rest runs correctly.
You probably have your setting EMAIL_VERIFICATION set to mandatory.
So you either change it to none in tests or manually create EmailAddress object (it's required by django-allauth when mandatory verification is on)

Resources