Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError while create new user using serializer
I'm making registration of new user. For this purpose I have a RegistrationView: class RegistrationView(APIView): def post(self, request): serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): new_user = serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And a RegistrationSerializer: class RegistrationSerializer(serializers.Serializer): is_accepted = serializers.BooleanField(required=True) first_name = serializers.CharField(required=True) last_name = serializers.CharField(required=True) email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True) second_name = serializers.CharField(required=False) company = CompanySerializer(required=False) requisites = RequisitesSerializer(required=False) address = serializers.CharField(required=False) def validate_is_accepted(self, value): if not value: raise serializers.ValidationError('Вы не дали согласия на обработку персональных данных.') def create(self, validated_data): validated_data.pop('is_accepted') validated_data['username'] = 'user' + str(User.objects.count()) return Client.objects.create_user(is_active=False, **validated_data) I use is_accepted field to determine is new user accepted to process his personal data. This field, obviously, isn't contained in User model. It's only for registration purposes, so I need to remove this field before creating new user. And as you see I do it in create method of RegistrationSerializer. However when I try to register new user it looks like is_accepted field hasn't been removed because I get the traceback below. So I checked it using logging and it's ok - is_accepted field isn't contained in validated_data which I put as argument to create_user method. It contains only model fields. So I don't understand this error. … -
how to get datetime to int in django? use datetime only hour and minute
I wanted to save the time as an int type so I could get the difference between the two times. i import datetime and try to like this now = datetime.now() but i get this : 2017-11-18 05:47:35.262111 how to get only hour and minute to int ex) 0547 I could not solve it. -
I'm trying to add category field to Django filer image model
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Could someone help me with this topic? code example is from http://django-filer.readthedocs.io/en/latest/extending_filer.html#providing-custom-image-model my code (all in myPlugins app): models.py from filer.models.abstract.BaseImage class CustomImage(BaseImage): category = models.CharField(max_length=20, blank=True, null=True,) class Meta: app_label = 'myPlugins' admin.py from django.contrib import admin from filer.admin.imageadmin import ImageAdmin from filer.models.imagemodels import Image class CustomImageAdmin(ImageAdmin): pass CustomImageAdmin.fieldsets = CustomImageAdmin.build_fieldsets( extra_main_fields=('default_alt_text', 'default_caption', 'category'), extra_fieldsets=( ('Subject Location', { 'fields': ('subject_location',), 'classes': ('collapse',), }), ) ) admin.site.unregister(ImageAdmin) admin.site.register(Image, CustomImageAdmin) in settings.py I've added: FILER_IMAGE_MODEL = 'myPlugins.models.CustomImage' and I'm getting an error: ValueError: Cannot create form field for 'image' yet, because its related model 'myPlugins.models.CustomImage' has not been loaded yet -
Django URL dispatcher not working
urls.py in project folder: url('aaa', include('main_app.urls')), urls.py in main_app folder: url('aaa', views.index), If I type /aaa in the address bar and press enter, it doesn't work. How do I make it work? From my understanding, in the urls.py of the project folder, Django checks for a matching string in the urls.py of the main_app folder. In the project folder it is aaa and in the main_app folder it is also 'aaa', yet it doesn't work? -
django on production 500 server error for one User related Model in Admin
I have deployed my Django(1.10) site on google compute engine, everything was working fine, but suddenly one of my model throwing 500 Server Error in admin. I have googled around but couldn't find any solution. All other models are displaying properly in django admin except only one and that's TaggedArticles model. Idon't have changed anything in my site, what's can be wrong? as it happens suddenly to my site. Here's my code: settings.py: """ Django settings for brain project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # For a test push to trigger build from codeship. # Second thing for CodeShip deployment push # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '35.202.165.136', 'brainresearchtagging.com', 'www.brainresearchtagging.com', ] # INTERNAL_IPS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
django.db.utils.ProgrammingError:column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data",
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data", "project_id", "pro... What should I change in code to resolve this error? Here's the traceback: Traceback (most recent call last): File "/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data", "project_id", "pro... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 53, in handle project_abstract = data['project_abstract'] File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table … -
It doesn't work (html and javascript and Iframe)
Related.. (HTML, JAVASCRIPT, Iframe) I add code into Iframe's element using javascript(Dynamically.). After I set all of things. JavaScript in Iframe doesn't work( onclick=functionName(defined inside iframe)... doesn't identify javascript function) what's wrong... this is my snippet. //initialize var destiframe = $('#tmpresult').contents(); destiframe.find('head').empty(); destiframe.find('body').empty(); //add script and style destiframe.find('head').append("<style></style>"); destiframe.find('body').append('<script type="text/javascript"></script>'); //attach customized code jQuery.each( code, function( i, code ) { switch(i){ case 0: destiframe.find('style').append(code.value); break; case 1: destiframe.find('body').append(code.value); break; case 2: destiframe.find('script').append(code.value); break; default: console.log("empty set"); break; -
Test POST method to Django REST viewsets
Docs says only mapping of GET user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) tests.py: def test_admin_can_create_role(userprofiles, aoo_admin, bug_manager, note_admin): aoo = User.objects.get(username='aoo') factory = APIRequestFactory() view = RoleViewSet.as_view() url = reverse('api:role-list') data = { 'name': 'FirstAdmin', 'type': Role.RoleType.admin, 'company': 1, } request = factory.post(url, data=data, format='json') force_authenticate(request, user=aoo) response = view(request) assert 201 == response.data viewsets.py class RoleViewSetPermission(permissions.BasePermission): message = 'Only Manager or Admin are allowed' def has_permission(self, request, view): user = request.user return user.has_perm('roles.add_role') \ and user.has_perm('roles.change_role') \ and user.has_perm('roles.delete_role') class RoleViewSet(viewsets.ModelViewSet): permission_classes = (RoleViewSetPermission,) queryset = Role.objects.all() serializer_class = RoleSerializer filter_backends = (filters.DjangoFilterBackend, SearchFilter) filter_class = RoleFilter search_fields = ('name', 'description', 'user__username', 'company__name', 'company__name_th') def filter_queryset(self, queryset): try: company = self.request.user.user_profile.companyappid.company except AttributeError: logger.error(f'{self.request.user} has AttributeError') return Role.objects.none() else: logger.info(f'{self.request.user} is {company} member') return queryset.filter(company=company) Trackback: cls = <class 'poinkbackend.apps.roles.api.viewsets.RoleViewSet'>, actions = None, initkwargs = {} @classonlymethod def as_view(cls, actions=None, **initkwargs): """ Because of the way class based views create a closure around the instantiated view, we need to totally reimplement `.as_view`, and slightly modify the view function that is created and returned. """ # The suffix initkwarg is reserved for identifying the viewset type # eg. 'List' or 'Instance'. cls.suffix = None # actions must not … -
Django 1.6 queryset
I have the following query and I am trying to set it in the Django 1.6 ORM SELECT * FROM pharol.product where name like "%PARACETAMOL%" or principe_active like "%PARACETAMOL%" order by case when name like 'PARACETAMOL%' then 0 else 1 end, name From the query I have already set the query but it is subtracting order by case when name like 'PARACETAMOL%' then 0 else 1 end, name any ideas? Thanks -
django manage.py runserver hangs after second request (intermittent)
My Django 1.11 app (using runserver) hangs after several requests. It doesn't matter whether it's accessed by Chrome, Postman, or curl. When it hangs, not even Ctrl+C can close it. The python.exe process must be killed. I tried debugging it but when Django is stuck, Python cannot be paused to get the threads/stack. -
get_list won't display my list on individual rows
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly, this example is if there was two check boxes selected: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. I.E. I want to see retreivecheckbox as 88 89 and not [88,89] Using the following template my app … -
Connectindo to Twisted Server from Django
I have a twisted server and a django webserver. I want the django server to send a message to the twisted server. The django server sends the first message but the second message displays the error message "ReactorNotRestartable". My Django Code: Eu tenho um servidor twisted e um servidor web django. Quero que o servidor django envie uma mensagem para o servidor twisted. O servidor django envia a primeira mensagem mas a segunda em diante exibe a mensagem de erro "ReactorNotRestartable". Meu código Django: from twisted.spread import pb from twisted.internet import reactor class EchoClient(object): def connect(self): clientfactory = pb.PBClientFactory() reactor.connectTCP("localhost", 8789, clientfactory) d = clientfactory.getRootObject() d.addCallback(self.send_msg) def send_msg(self, result): d = result.callRemote("echo", "hello network") d.addCallback(self.get_msg) def get_msg(self, result): print "server echoed: ", result reactor.stop() def main(): EchoClient().connect() reactor.run(installSignalHandlers=0) -
How to brodcast to multiple rooms on Django channel?
i'm making a chat for 1 on 1, i made it using django channel. the model I use is as below: class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='author') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient') message = models.TextField(max_length=3000) message_html = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.message while for url django for chat with the other person : url(r'^to/(?P<username>[\w.@+-]+)/$', views.ChatView.as_view(), name='chat_page') and routing in django channels: chat_routing = [ route("websocket.connect", chat_connect, path=r'^/(?P<username>[\w.@+-]+)/'), route("websocket.receive", chat_receive, path=r'^/(?P<username>[\w.@+-]+)/$'), route("websocket.disconnect", chat_disconnect, path=r'^/(?P<username>[\w.@+-]+)/$')] channel_routing = [ include(chat_routing, path=r'^/to'),] so for example if foo wants to chat to bar then it can with http://localhost:8000/to/bar and this works well with django channels but when broadcast is updated only the room "bar", whereas room "foo" does not get the message so i want to broadcast the message to two room: http://localhost:8000/to/bar AND http://localhost:8000/to/foo this is my code to send message in consumer.py Group("to-%s" % username).send({'text': json.dumps(my_dict)}) how this can be achieved, Thank you for the help -
Django models testing with pytest
When i run the following test, import pytest from mixer.backend.django import mixer from ..models import User pytestmark = pytest.mark.django_db(transaction=False) class TestUser: def test_model(self): obj = mixer.blend(User, email='test@test.com') assert obj.pk == 1, 'Should create a user instance' i get an error ==================================== ERRORS ==================================== _______________ ERROR collecting users_app/tests/test_models.py ________________ users_app/tests/test_models.py:5: in <module> pytestmark = pytest.mark.django_db(transaction=False) E AttributeError: MarkDecorator instance has no attribute 'django_db' !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!! =========================== 1 error in 0.74 seconds ============================ my test_settings.py looks like this from .settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } } EMAIL_BACKEND = 'django.core.mail.backends.locmem.Emailbackend' What is wrong with my pytest? I have tried to change to pytest.mark.django_db to the real database name(which is an sqlite database too). -
Django ModuleNotFoundError
I can't make a simple Django project work at all. I get the same error as listed in this question which I found: Python/Django =- ModuleNotFoundError: No module named 'restaurants' The only difference for me is that it says "No module named entries". This doesn't seem to have a resolution and I don't understand the comment on it either. My directory structure is like this: app |- manage.py |- app |- __init__.py |- entries | |- __init__.py | |- apps.py | |- models.py | |- views.py | |- admin.py | |- tests.py | |- migrations - __init__.py | |- urls.py |- settings.py |- __pycache__ |- wsgi.py I have added the entries app to the INSTALLED_APPS list in settings.py. But from there it just seems to run into a problem. I have been trying to work this out for ages and I just don't get it (even though it is probably easy). -
how to use supervisor when I should running a celery in django which is in a virtualenv?
yesterday, i deployed a django project with nginx,uwsgi,celery,supervisor. it seems ok. but some questions come about. generally saying, this time i deployed a django,use the local python, but if i must use the python Environment in a virtual,what should i do ? for example,i code some task(whith django-celery) which will be used by django site to contorl some timing task,and the django project based python3(the python3 envrionment is in a virtualenv). so the celery should be used by python3,which is in a virtualenv,not the local python environment. it means that if i setting the commond in supervisor "commond=python ****/manage.py celery" would error come. the uwsgi has some setting about this, i can set the path of virtualenv. but in supervisor, i had not get some setting or some way to use the virtualenv. help please. -
django hot processing performance
i run django framework in windows7 , but i note that it work hard and it consumes more processing capacity like shown in the picture below , i want to reduce it but i dont know how or which settings should be modified; -
new username is created instead of getting updated
I am trying to create a list of employee. I can assign username, password and email to that employee and also can update employee information where I should able to update username, password or email either. I could create an employee and also create the username and password along with update employee info but when changing the username or password or email of the employee a new user is created. Here is what I have tried class EmployeeForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = models.Employee fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number', 'email', 'gender', 'role', 'username', 'password', 'avatar',) def employee(request): form = EmployeeForm(request.POST or None) if request.method == "POST" and form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] office_instance = OfficeSetup.objects.get(owner=request.user) form = form.save(commit=False) form.office = office_instance user = User.objects.create_user( username=username, password=password, email=email) user.save() form.save() messages.success(request, 'Thank you') return redirect('employee-list') messages.warning(request, 'Error') context = { 'form': form } return render(request, 'dashboard/hrm/employee.html', context) Edit part def edit_employee(request, id): instance = get_object_or_404(Employee, id=id) form = EmployeeForm(request.POST or None, instance=instance) if request.method == "POST" and form.is_valid(): employee = Employee.objects.get(id=id) prev_username = employee.username username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] office_instance = OfficeSetup.objects.get(owner=request.user) form = form.save(commit=False) form.office = office_instance … -
Pug & Django: reverse URL + variable inline?
Desired output: You're currently following xx artists Assuming I'm using Pug in a Django template, how would I achieve that if I don't want to hardcode the URL (which I have named as artists in my URL), and if the artist count is also a variable? I can do this: p You're currently following #{user_artists_count} artists but how can I make the last part a link to a Django URL with the name artists? -
django templatetag working incorrectly
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. Using the following template my app prints correctly, however, all on one row. {% for app in retreivecheckbox %} {{ app }} {% endfor %} When I try … -
Zappa/AWS - Emails won't send and just timeout
Currently, I have tried both plain-old Django SMTP and a few different api-based Django libraries for my transactional email provider (Postmark). When I run my development server, everything works perfectly. Emails send via the Postmark API with no problem. When I deploy to AWS with Zappa, visit my website, and do a task that is supposed to send an email (Ex. Resetting a user's password) the page continually loads until it says Endpoint request timed out. I have tried setting the timeout of my AWS Lambda function to a longer duration in case Django decides to throw an error. Here is the error that was thrown. Just keep in mind this error only happens in production. I created a custom management command in able to retrieve this error. HTTPSConnectionPool(host='api.postmarkapp.com', port=443): Max retries exceeded with url: /email/batch (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6cfbd5dd30>: Failed to establish a new connection: [Errno 110] Connection timed out',)): ConnectionError Traceback (most recent call last): File "/var/task/handler.py", line 509, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 376, in handler management.call_command(*event['manage'].split(' ')) File "/var/task/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/var/task/django/core/management/base.py", line 330, in execute … -
Django File upload - Path to file
I am uploading a file using the model.FileField method, but I am at a loss on how to actually return the path of the uploaded file (I can't recreate the path as there can be duplicate files and the imagename changes) Views.py if form.is_valid(): newdoc = Invoices(docfile = request.FILES['docfile']) newdoc.save() Models.py class Invoices(models.Model): docfile = models.FileField(upload_to='invoices/') timestamp = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=20, default="default_user") I found some references to document.uploaded_file path etc, but they throw an error - no property document. Is it possible using the method above to get the actual path to the saved file including the possibly changed filename? -
Django (allauth) to ignore dot in the username
I would like to follow google's username convention where they take in a username as it is with dot, but consider any username with different dot placement to be identical. Since google shows the name with dot if the user signs up with it, they must store that name verbatim in the database. Should I create another field without the username, so that it would be more efficient to search for duplicates at the signup or siginin request? Or is there a query method to do this within Django? So far I am using the User model from Django as it is, so I'd prefer not having to inherit it to make a new subclass. -
Django - loop over list in template to check if a value exists, display something later
I find a list of Upvote model instances attached to a specific question, so I can check if the current user has already upvoted the question. I want to display a different button if the user has already upvoted this particular question. The problem is, the current {% if .. %} tags don't work, because a question can have many upvotes. I only need the {% if ..%} tags to simply check to see if one of the upvote.user == request.user. How do I approach this situation? I'm looking at different solutions, like creating a variable and setting that to True if a match was found (seems difficult), or writing a custom template tag. I feel like I'm over-complicating this issue though. HTML Template {% for question in questions %} {% for upvote in question.upvote_set.all %} {% if upvote.user == request.user %} # Display the upvote button {% else %} # Display a different button {% endif %} {% endfor %} models.py class Question(models.Model): # ... code user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='question', null=True, blank=True) class Upvote(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) -
URLCache not working when using p2_OAuth2 Data Loader
I'm trying to cache various REST calls in my iOS app and can't seem to find an approach that works. Our objective is to leverage caching to solve for offline situations and this is just a start to try to get caching working at a basic level. Some of the details here: REST responses include this header (using Django REST Framework): Cache-Control: private, max-age=3600 AppDelgate Code: let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as String let dir = cacheDirectory.appendingFormat("/urlCache/") let memoryCapacity = 10 * 1024 * 1024 let diskCapacity = 50 * 1024 * 1024 let cache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: dir) URLCache.shared = cache Although I don't believe I really need to do this to get some level of caching working? Initialization of OAuth2 classes: init(context: AnyObject, accessToken: String) { oauth2.authConfig.authorizeContext = context oauth2.authConfig.authorizeEmbedded = true oauth2.authConfig.authorizeEmbeddedAutoDismiss = true oauth2.logger = OAuth2DebugLogger(.debug) oauth2.accessToken = accessToken loader = OAuth2DataLoader(oauth2: oauth2) striveaiRoot = URL(string: Bundle.main.infoDictionary!["StriveAIRoot"] as! String)! self.accessToken = accessToken } Example code calling the REST API via DataLoader: func getFeed(callback: @escaping ((OAuth2Response) -> Void)) { let uri = striveaiRoot.appendingPathComponent("feed") let size = URLCache.shared.currentMemoryUsage NSLog("using %d of cache", size) let req = oauth2.request(forURL: uri, cachePolicy: .useProtocolCachePolicy) self.loader?.perform(request: req, callback: callback) …