Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Block content not rendering
I want to retrieve all posts from my Post model on one view template(allposts.html), and all posts from the politics category on another view template(political.html), and then display them on different sections of the index.html template. However, I am getting a blank page. What could be the issue? Here is my code index.html <!-- ======= Post Grid Section ======= --> <section id="posts" class="posts"> <div class="container" data-aos="fade-up"> <div class="row g-5"> {% block allposts %} {% endblock %} <!-- Some sections skipped --> <div> <div class="post-meta"><span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>Jul 5th '22</span></div> <h3><a href="single-post.html">What is the son of Football Coach John Gruden, Deuce Gruden doing Now?</a></h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio placeat exercitationem magni voluptates dolore. Tenetur fugiat voluptates quas, nobis error deserunt aliquam temporibus sapiente, laudantium dolorum itaque libero eos deleniti?</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="assets/img/person-2.jpg" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">Wade Warren</h3> </div> </div> </div> </div> {% block content %} {% endblock %} Here is the political.html content that I am trying to render {% extends 'index.html' %} {% block content %} {% for politics in politics %} <div class="row"> <div class="post-entry-1 border-bottom"> <a href="single-post.html"><img src="{{post.image.url}}" alt="" class="img-fluid"></a> <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> … -
How to cache django rest framework (retrieve) with persistent cache
I have the following Django REST view: class AnnotationViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Annotation.objects.all() serializer_class = AnnotationSerializer Accessing a single method will call the retrieve function thanks to mixins.RetrieveModelMixin. I would like to speed up the function since it requires multiple queries and it uses a lot of CPU. In particular: I'd like a persistent cache that could be used after restarting the application The cached data needs to be different based on the record retrieved (e.g. http://127.0.0.1/annotations/1 vs http://127.0.0.1/annotations/2, etc) As of now I tried to overwrite the view retrieve method: @method_decorator(cache_page(60 * 60 * 24 * 365)) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) and to set the default cache to disk: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/home/django_cache', } } I don't think it is working, as I need to cache about 2 million items (I have about 2 millions records): the folder /home/django_cache uses less than a Mb and it's size changes every time I call the API. -
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') with unique_togther field
I am having the same issue as the user from this post, however, all of the proposed solutions did not work for me. I am using MySQL 8.0.24 with Django 3.1. Similar to them, I had a model without a unique_together field as shown below class Show(models.Model): english_name = models.CharField(max_length=400) kanji_name = models.CharField(max_length=200, blank=True) romanji_name = models.CharField(max_length=400, blank=True) show_type = models.CharField(max_length=100, blank=True) # a bunch of other fields... class Meta: verbose_name_plural = 'Series' ordering = ('-created',) unique_together = ['english_name', 'kanji_name', 'romanji_name', 'show_type'] def __str__(self): return self.english_name It was only until I changed class Meta to this class Meta: verbose_name_plural = 'Series' ordering = ('-created',) unique_together = ['english_name', 'kanji_name', 'romanji_name', 'show_type'] That I started receiving this error whenever I migrated my database. django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') I followed the steps in the post I linked above to ensure the utf8 was used, I was able to confirm that the dataset was using that character set, but it didn't resolve my issue. Is there anything else I can do to ensure that the unique_together field can be used? -
How do I overlay text on a PDF file scanned as an image?
I cannot figure out how to overlay variables as text on to a PDF uploaded as a scanned document. The use scenario is to process the PDF and place text in it as though the PDF is a background image. Text is unremarkable, and the process is intended to produce a customized PDF for the user. I was trying to use XHTML2PDF... I might be going in the wrong direction. How would I do that? -
Django Home url set to folder
I have an issue where I would like my address (whether local or live) to point to my projects app as my home page, yet every change I make breaks the other URLs. My main site URL patterns are: urlpatterns = [ path('admin/', admin.site.urls), path("projects/", include("projects.urls")), path("blog/", include("blog.urls")), ] I have tried to change the path("project/", include("projects.urls")) to path("", include("projects.urls")) which breaks the blog index. my blog has the following pattern: urlpatterns = [ path("", views.blog_index, name="blog_index"), path("<slug:slug>/", views.blog_detail, name="blog_detail"), path("<category>/", views.blog_category, name="blog_category"), ] And my projects: urlpatterns = [ path("", views.project_index, name="project_index"), path("<slug:slug>/", views.project_detail, name="project_detail"), path("project/<tag>/", views.project_tag, name="project_tag"), ] -
Reverse for 'orderlist_order_change' with arguments '('',)' not found. 1 pattern(s) tried: ['orderlist/order/(?P<object_id>.+)/change/\\Z']
I need the form to insert the id value on save when using django admin models.py class Order(models.Model): id = models.CharField(max_length=32,primary_key=True)# customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ... admin.py class OrderAdmin(admin.ModelAdmin): readonly_fields = ['id'] def save_model(self, request, obj, form, change): form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999)) form.save() super().save_model(request, obj, form, change) error: NoReverseMatch at /orderlist/order/add/ Reverse for 'orderlist_order_change' with arguments '('',)' not found. 1 pattern(s) tried: ['orderlist/order/(?P<object_id>.+)/change/\Z'] Request Method: POST Request URL: http://127.0.0.1:8057/orderlist/order/add/ Django Version: 3.2.10 Exception Type: NoReverseMatch Exception Value: Reverse for 'orderlist_order_change' with arguments '('',)' not found. 1 pattern(s) tried: ['orderlist/order/(?P<object_id>.+)/change/\Z'] Exception Location: E:\CodeFiles\Venv\py378django3.2\lib\site-packages\django\urls\resolvers.py, line 698, in _reverse_with_prefix Python Executable: E:\CodeFiles\Venv\py378django3.2\Scripts\python.exe Python Version: 3.7.8 -
how to implement Graphql Proxy in python
I'm trying to build a simple Graphql proxy service that receives graphql requests and forwards them to a remote server and I can return the response to the main server. I am using Django for the main project and the remote server is also using Django graphene to return. -
Constant deletion routine can harm the performance of the database or application?
I created a view that does some checks between models as these models are updated/added. When this check finds an inconsistency it creates a record and a specific model of record of inconsistencies. My question is about the strategy I used in this view. view def farm_check(farm_id): farm = get_object_or_404(Farm, pk=farm_id) to_delete = FarmProblem.objects.filter(farm=farm) for delete in to_delete: delete.delete() check_city = Registration.objects.filter(farm=farm).filter(~Q(city=farm.city)) check_uf = Registration.objects.filter(farm=farm).filter(~Q(uf=farm.uf)) check_car = Registration.objects.filter(farm=farm,car__isnull=True) check_ccir = Registration.objects.filter(farm=farm,ccir__isnull=True) check_nirf = Registration.objects.filter(farm=farm,nirf__isnull=True) check_area = Registration.objects.filter(farm=farm,area__isnull=True) list_area_pk = map(lambda x: x.pk,check_area) check_app = Registration.objects.filter(farm=farm,app__isnull=True).exclude(pk__in=list_area_pk) for check in check_city: problem = 'Cidade inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='City',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='City',specific=check.number,item=problem) item.save() for check in check_uf: problem = 'UF inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='UF',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='UF',specific=check.number,item=problem) item.save() for check in check_car: problem = 'CAR inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='CAR',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='CAR',specific=check.number,item=problem) item.save() for check in check_ccir: problem = 'CCIR inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='CCIR',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='CCIR',specific=check.number,item=problem) item.save() for check in check_nirf: problem = 'Sem número de NIRF' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='NIRF',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='NIRF',specific=check.number,item=problem) item.save() for check in check_area: problem = 'Área indeterminada' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='Area',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='Area',specific=check.number,item=problem) item.save() for check in check_app: problem … -
Add Custom bootstap template to Django CMS Project
I hope you are well. The reason i'm writing to you is because ive been utilizing the Django cms bootstrap carousel plug in. Im all set however i am struggling to figure out how to add me newly added custom template to my application. Im wondering if there is something i need to add to my settings.py file like CAROUSEL_TEMPLATES = [ ' ' ] I would be very grateful if you could point me in the right direction? -
Django view function isnt working correctly
so the basic goal of my project is to allow teachers and admin to login to the system and take attendance for the students. my new issue is that i have a view function that is suppose to check to see if students student is already added to the respective class and if they are it will exclude them from the drop down menu and display the students who aren't in the class but it not doing that instead it is showing me a blank drop down menu. the way i have it set up is that the admin clicks the add student button then it will convert a .html page to modal which brings up the list of students to select from. When i add the form responsible for saving the student to the class in the Django admin it work perfect but i cant seem to get it to work in the user section Ui. I am new to Django and this is my first project so any help is really appreciated Views #check to see if students already exist in class and display those who aint to be added @login_required def manage_class_student(request, classPK=None): if classPK is None: … -
Creating a subForm within a Form to populate an Abstract Form
I have been trying to figure this out by banging my head and scouring the forums and Google. Hope someone has had experience with this. I am trying to create some text mining subform within PostForm Class that calls a script.So an user enters a DOI or PMID and searches the PUBMED database.I am successful with the script pulls data from a server, but would like to figure out the user then continues to fill the rest of the data. So together with the Called data and the User entry save as post. Here I am using the Django-Machina Blog as the platform. So a User would enter a DOI or PMID, returns a query, that a user can then enter information in contents. [Form][1] AbstractModel: class AbstractPost(DatedModel): """ Represents a forum post. A forum post is always linked to a topic. """ topic = models.ForeignKey( 'forum_conversation.Topic', related_name='posts', on_delete=models.CASCADE, verbose_name=_('Topic'), ) poster = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='posts', blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Poster'), ) anonymous_key = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Anonymous user forum key'), ) # Each post can have its own subject. The subject of the thread corresponds to the # one associated with the first post subject = models.CharField(verbose_name=_('Subject'), max_length=255) doi … -
Django Generating Custom ID
Okay so, I have seen numerous "answers" to this question, most notably, this one. from django.db.models import Max id = models.CharField(primary_key=True, editable= False, max_length=10) def save(self, **kwargs): if not self.id: max= Custom.objects.aggregate(id_max=Max('id'))['id_max'] self.id= "{}{:05d}".format('IT-', max if max is not None else 1) super().save(*kwargs) Now, thanks to this, I really just apply the code to my model, and it should work. Well, it doesn't. It wants to, but it can't, let me explain: on the backend of the django application I tried adding a new row, but when saving it, it throws an OperationalError, (1366, "Incorrect integer value: 'IT-00002' for column id), (my prefix being 'IT-'). Now, from what I can gather, the prefix is being included yes, but the column isn´t changing from integer. I have saved, migrated all changes and it isn´t working. I have even tried changing the data type in phpmyadmin, but because it also has the 'AUTO_INCREMENT' property, it can't be changed to anything other than an integer. How can I change this? -
TypeError: cannot unpack non-iterable function object while using get() in Django
I have a model called WatchList with a object called listing which corresponds to the Listings model. I want to make a page where all the listings that a user has added to his watchlist appear. I am trying to filter through the WatchList objects through the user and get access to the listing object, so I can get all the objects from that particular listing (there may be more than one). views.py def watchlist(request): watchlists = WatchList.objects.filter(user=request.user) watchlist_listing = watchlists.get(listing) listings = Listings.objects.all().filter(watchlist_listing) return render(request, "auctions/watchlist.html",{ "listings": listings }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class WatchList(models.Model): listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") error message TypeError: cannot unpack non-iterable function object This error is caused by this line watchlist_listing = watchlists.get(listing) . But if I change the code to watchlist_listing = watchlists.get('listing') this error too many values to unpack (expected 2) occurs. How do I fix this and get access … -
Why does Django related_name isn't working
I am working in my Django (DRF) app. I have these models class CustomUser(AbstractBaseUser, PermissionsMixin): ... class SupportChat(models.Model): support = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="support_chat" ) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="chat" ) I want to get chats of the users in views.py @api_view(['GET']) def get_my_chats(request): res = {} admins = CustomUser.objects.filter(user_type='Admin') res["admins"] = CustomUserSerializer(admins, many=True).data #my_request_chats = SupportChat.objects.filter(user=request.user) my_request_chats = request.user.chat if my_request_chats is not None: res["my_request_chats"] = SupportChatSerializer(my_request_chats, many=True).data res["my_request_chats"] = None my_response_chats = SupportChat.objects.filter(support=request.user) if my_response_chats is not None: res["my_response_chats"] = SupportChatSerializer(my_response_chats, many=True).data res["my_response_chats"] = None return Response(res) Problem -- Can't get chats of the user (my_request_chats is NULL) Received response like this { "admins": [ // valid data ], "my_request_chats": null, "my_response_chats": null } I checked that request.user have chats (in admin panel) -
Django resize chart in table
I have a basic chart created with chart.js which is later displayed in table. I have a problem to manipulate his height/width to fit it correctly to table in django template. Chart is displayed in for loop in table and code looks like: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> <table class="table table-bordered"> <thead>Details </thead> <tbody> {% for key, value in game_details.items %} <tr> <th>Game</th> <th>Played</th> <th>Won</th> <th>Lost</th> <th>Pending</th> </tr> <tr> <td>Game </td> <td>{{ value.all }}</td> <td>{{ value.win }}</td> <td>{{ value.lost }}</td> <td>{{ value.pending }}</td> </tr> <tr> <td colspan="5" style="max-height: 10px"> <canvas id="myChart{{ key }}" width="200" height="200"></canvas> <script> const ctx{{ key }} = document.getElementById('myChart{{ key }}').getContext('2d'); const myChart{{ key }} = new Chart(ctx{{ key }}, { type: 'doughnut', data: { labels: ['W', 'L', "P"], datasets: [{ label: '# of Votes', data: [{{ value.win }}, {{ value.lost }}, {{ value.pending }}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(153, 102, 255, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(153, 102, 255, 1)', ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </td> </tr> {% endfor %} </tbody> </table> and it looks like that: Changing the width or height … -
NameError: name 'Any' is not defined in Django
When I use the autocomplete suggestion in VSCode to make a get_context_data() function: def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: return super().get_context_data(**kwargs) I get a NameError: NameError: name 'Any' is not defined I am new to using type hints in Python - do I need to import something for type Any? -
how to get all field on modelform on django
I have a model called Product class Product(models.Model): id name nation Number price i want to filter using all of the above attributes, which will be passed in query_params at this moment i am using DjangoFilterBackends with filter_fields but to support all attributes i have to mention all the attributes in filter_fields like below in views filter_fields = ['id', 'name', 'nation', 'Number', 'price'] its working fine, but in actual model the fields are alot, which is causing code quality degradation. is there any way to include all fields in filter_fields ?? i tried filter_fiels = ['__all__'], but its not working. -
how to show options in select with forms.ModelChoiceField - Django
I have this problem: I need to show in a select the data of a model, I have been working with form template to customize it, but when it comes to a select I don't know how to show the options in template it only shows 'rol' in the options. My model: class Rol(TimeStampedModel): name = models.CharField(verbose_name=_('Name'), max_length=100) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.IntegerField(verbose_name=_('Sort Order'), default=0) My forms: class ProfileForm(forms.ModelForm): rol = forms.ModelChoiceField(queryset=Rol.objects.all().order_by('sort_order'), to_field_name='name') class Meta: model = User fields = ['email', 'first_name', 'last_name','rut', 'phone', 'gender', 'rol'] exclude = ('username',) def __init__(self, user=None, *args, **kwargs): self.user = user super(ProfileForm, self).__init__(*args, **kwargs) My HTML: <tr> <td class="table-text typo-grey"><label class="float-left">Rol</label></td> <td class="rol centered"> <div class="ui input"> <select type="mail" id="id_{{form.rol.html_name}}" name="{{form.rol.html_name}}" maxlength="100"> {% for rol in form.rol %} <option value="{{ form.rol.html_name|default:'' }}"=>{{form.rol.html_name}}</option> {% endfor %} </select> </div> </td> </tr> If u any advice or something, please coment, thanks. -
Django - multi-table inheritance - convert Parent to Child
I have models that look like this: class Property(Model): ... class Meta: # not abstract class Flat(Property): ... class House(Property): ... Is it possible to convert already existing Property to House or Flat? I know that House or Flat additional fields are in different tables so this should be doable by creating such a row and making some relation. How can I do that? -
Django import export get() returned more than one
I have a small Django application with cities_light, smart_selects, and import_export. I am able to properly export from the admin site into csv files using resources and ForeignKeyWidget from import_export. However, there is something wrong with my import and I'm not sure how to fix it. When trying to import through the admin site from the same exported csv file, I get jobs.models.City.MultipleObjectsReturned: get() returned more than one City -- it returned 2!. This question is similar to this one but I still do not understand what is wrong. Would greatly appreciate if the responses contain links to the documentation that explain what I am doing wrong, since I've gone through ReadTheDocs but have been unsuccessful at finding my mistake. Thanks. models.py class Country(AbstractCountry): pass connect_default_signals(Country) class Region(AbstractRegion): def __str__(self): return self.name country = models.ForeignKey(Country, on_delete=models.PROTECT) connect_default_signals(Region) class SubRegion(AbstractSubRegion): pass connect_default_signals(SubRegion) class City(AbstractCity): def __str__(self): return self.name region = models.ForeignKey(Region, on_delete=models.PROTECT) connect_default_signals(City) class JobPost(models.Model): title = models.CharField(max_length=100) company = models.CharField(max_length=100) urlCompany = models.URLField(blank=True) urlApplication = models.URLField(blank=True) contactEmail = models.EmailField(max_length=100, blank=True) jobType = models.CharField(max_length=100, blank=True) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True) region = ChainedForeignKey( Region, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, sort=True, blank=True ) city = ChainedForeignKey( City, chained_field="region", chained_model_field="region", show_all=False, auto_choose=True, sort=True, blank=True … -
how to get data from foreign key to save in database in django
I have two models that are related with many to many relationship. I need the data of the second model to be stored in the database when creating the object from the first model so that later if the values of the second model change, it will not affect the values we entered in the first model. How should I act? # models.py class First(models.Model): percent = models.IntegerField() two = models.ManyToManyField(Two, blank=True) class Two(models.Model): title = models.CharField(max_length=50, null=True) amount = models.PositiveIntegerField(null=True) # forms.py class FirstAddForm(forms.ModelForm): class Meta: model = First def save(self, commit=True): instance = super(FirstAddForm, self).save(commit=False) instance.percent = self.cleaned_data['percent'] / 100 . # How should I act? # . if commit: instance.save() self.save_m2m() return instance # views.py def FishDetailView(request, pk=None): first = First.objects.all() . . for i in First: two= Two.objects.filter(first__id=i.id) . . context = { 'first': first 'two': two, } -
Django DELETE Endpoint gives permission denied, but every other endpoint works fine
I tried to search around including how HTTP DELETE and POST are called. But can't seem to understand why DELETE endpoint doesn't work. The POST endpoint has the exact same Permissions and Serializer, but when I try to DELETE via Postman, it says permission denied. Doesn't make any sense. #this one works fine class PhoneNumberCreateApi(generics.CreateAPIView): permission_classes = [custompermission.IsStaff] queryset = Phone.objects.all() serializer_class = PhoneNumberSerializer #this one does not class PhoneNumberDeleteApi(generics.DestroyAPIView): permission_classes = [custompermission.IsStaff] queryset = Phone.objects.all() serializer_class = PhoneNumberSerializer Any insight is appreciated. Never seen this error before. -
Django: Reverse for 'download_excel/309' not found. 'download_excel/309' is not a valid view function or pattern name
I am currently working on designing a Django app that would allow a person to download an excel with data from a page. I am trying to connect a hyperlink to a view function but it keeps returning the reverse match. I am able to go directly to the url and it downloads the excel but when I can't load the index.html file because of the error. Am I naming the hyperlink wrong? urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('Excel/<int:study>', views.Excel, name='Excel'), path('download_excel/<int:study>', views.download_excel, name='download_excel'), ] index.html <html> <title>Download File</title> </head> <body> <enter> <h1>Download File using Django</h1> <a href="{% url 'polls:download_excel/309' %}">Download State Impulsivity Excel</a> </enter> </body> </html> views.py def download_excel(request, study): with BytesIO() as b: writer = pd.ExcelWriter(b, engine='xlsxwriter') Retrieve(study) df = pd.DataFrame(data) df.to_excel(writer, sheet_name='Sheet1') writer.save() Names(study) filename = str(name) + "_" + str(current_time) + ".xlsx" response = HttpResponse( b.getvalue(), content_type=mimetypes.guess_type(filename) ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
Django Apscheduler
I'm looking to use Django Apscheduler or Django Celery to allow a user to input a cron expression and add it to the jobs list to be run at the user specified time. I also would like the user to be able to edit the cron expression if needed down the road. From django apscheduler docs I'm aware updates and creates aren't registered till the server is restarted and I'm okay with the server being restarted nightly to import the new jobs. -
Object of type bytes is not JSON serializable when trying to return jwt_token
Really confused because this functionality was working a few days ago and I made no substantial changes to my code. I am getting this traceback: Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response File "C:\Users\15512\anaconda3\lib\site-packages\django\core\serializers\json.py", line 105, in default return super().default(o) File "C:\Users\15512\anaconda3\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializable To summarize, I am sending a name to the Twilio library with the expectation of receiving a JWT_token. The API endpoint would then return a dict with a key: title and jwt_token This is what my view for the end point looks like: class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() full_data = {'token': jwt_token} # print(type(jwt_token)) return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False) I've also tried to have this in the return statement: JsonResponse({"token": jwt_token})