Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fixing django inspectdb after importing postgresql sample database
Context: I'm playing around with setting up a DRF project using the postgresql sample database located here: Postresql Sample DB Problem: The sample database is already set up with intermediate tables film_category and film_actor. When using manage.py to inspectdb it generates these intermediate tables explicitly (FilmCategory and FilmActor) and they serve no purpose in the code as they only contain the ids for the two related fields. If I were to create them using the Django ORM I could just declare: class Film(models.Model): ... actors = models.ManyToManyField(Actor, related_name='films') Django creates these tables "behind the curtain" so they take up no space in my code. I attempted to just set up a ManyToManyField like so: actors = models.ManyToManyField(Actor, db_table='film_actor', related_name='films') categories = models.ManyToManyField(Category, db_table='film_category', related_name='films') When attempting to migrate, however, this fails giving me the following error: psycopg2.errors.DuplicateTable: relation "film_actor" already exists I don't think I want to create this ManyToManyField without explicitly telling it which db_table to use because I believe that would generate an entirely new intermediate table and I lose access to all the data already stored in those intermediate tables in the original sample database. I was able to get it to work without errors and the … -
Post field not returned by __str__
My question is similar to Display field other than __str__ but slightly different. The example in the link seems to only change the options in the dropdown, and not what gets posted when you select them. I am trying to make a dropdown that populates with a users first and last name. The issue I am having is that my People model that I am querying has a __str method that returns a users badgenumber, not their first and last name. The code posted below works to populate the dropdown options with the users names. When you select one from the list it even fills the field in with the correct info. But when you submit the post it is still posting the badgenumber associated with the first/last name you pick, not their first and last name. How do I get it to post something not returned by the __str method? forms.py class InitiatorSelect(forms.ModelChoiceField): def label_from_instance(self, person): return person.fullname initiator_name = InitiatorSelect( label="Initiator", queryset=baws.models.People.objects.filter(distributor=True), required=True, widget=local_fields.ListTextWidget(attrs={ "force": "true", "dvalue": "true", "autocomplete": "off", "class": "form-control" }), -
makemigrations - No changes detected -Django
I am new to Django, and im trying to create a company profile for user to fill up. when i make migrations, i got the following error which is no changes detect. heres the model.py class Company(models.Model): name = models.CharField(max_length=100) about = models.TextField(gettext_lazy('about'), max_length=500, blank=True) role = models.CharField(max_length=100) address=models.CharField(max_length=100) contact=models.CharField(max_length=100) def __str__(self): return f'{self.user.username} Profile' I didnt create anything in other .py file only model and i have another class which is profile in the same model.py as company. Do correct or lmk if i make any mistake, thanks! -
Django form not correctly updated
I've made a Django site with dinamically generated forms. The site is based on Leaflet.js as frontend, a JS library for web mapping. I cloned the form from the HTML in the JS script, to bind the form as a pop-up of every geographical feature. My idea is to update this popups/forms, as the user were updating data in the field, for example inputting data about a feature ("This house is abandoned", "This tree is very big", just stupid examples). The problem is that the AJAX query is not sending the correct data, but the empty form present in the HTML document. How I can refer the updated form to send the data? The POST request is correctly sent, but comes empty, since it's just sending the empty form. My AJAX query: $(document).on('click', '#submitButton', function(e){ e.preventDefault(); $.ajax({ type : "POST", headers: {'X-CSRFToken': csrf_token}, url: "update_note/", data: { id: $('#id_id').val(), note_heading: $('#id_note_heading').val(), note_des: $('#id_note_des').val(), dataType: "json" }, success: function(json){ $('#form_pop').val(''); // remove the value from the input console.log(json); // log the returned json to the console console.log("success"); // another sanity check }, failure: function() { console.log('error') } }); return false }); How I bind the hidden form in the HTML to … -
Django Authentication method is not working
I am trying to use the default Django from django.contrib.auth authenticate() method to authenticate if the user exists. I am doing this right after the user registers. The user registers and their username, email, and password is inputted into the database then they are taken to the login page but it is not working. Here is my views.py from django.shortcuts import render,redirect from .models import Student from django.contrib.auth.models import User from django.contrib.auth import authenticate, login # Create your views here. def index(request): if request.method == "POST": fname = request.POST.get('fname') lname = request.POST.get('lname') pnumber = request.POST.get('pnumber') email = request.POST.get('email') password = request.POST.get('password') student = Student(fname = fname, lname = lname, pnumber = pnumber, email = email, password = password) student.save() user = User.objects.create_user(fname, email, password) user.save() return render(request, ('SignUpPage.html')) def loginUser(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) return redirect('mainPage') else: return render(request, ('LoginPage.html')) return render(request, ('LoginPage.html')) def mainPage(request): return render(request, ('MainPage.html')) Here is my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('login', views.loginUser, name="login"), path('mainPage',views.mainPage, name='mainPage') ] Here is my html code <!DOCTYPE html> … -
Django processing form input name
I have changed the input's name attribute to some custom name, but the view calls form_invalid method. Why my Form isn't saving (validating)? html: <tr> <th><label for="id_photo">Image:</label></th> <td> <input type="file" name="custom_photo_name" accept="image/*" required id="id_photo" multiple> </td> </tr> the line in view: self.request.FILES.getlist('custom_photo_name') Doesn't the self.request.FILES takes the values according to name attribute? -
send template data from signal in django
As soon as the django user_logged_in signal works, I want to send data to my template at that moment.I need to check if my signal is working. from django.contrib.auth.signals import user_logged_in @receiver(user_logged_in) def post_login(sender, user, request, **kwargs): isLogged = True # base.html I want to send this to 'isLogged= True' base.html I don't know if I can do this with context processor.I just want to send data to base.html file as soon as user logs in -
Representing Django M2M data export in a CSV
The problem I am trying to solve is to export all the entries of a Django model as CSV. The field names are supposed to be headers, with each row having an appropriate value under each column. The challenge here is that the model has a few M2M relationships. Each associated M2M model has multiple fields in it. I have added a subset of the main model and some related models below: class Semester(TimeStampedModel): title = models.TextField() uuid = models.UUIDField(blank=False, null=False, default=uuid4, editable=False, verbose_name=_('UUID')) class CreditClass(TimeStampedModel): title = models.TextField() category = models.CharField(max_length=32) is_active = models.BooleanField(default=False) credits = models.IntegerField() class Student(TimeStampedModel): name = models.TextField() age = models.IntegerField() active_semesters = models.ManyToManyField(Semester) enrolled_classes = models.ManyToManyField(CreditClass) Each student will have a different count for associated model entries. For example, Student A in the 3rd semester will have an association with 3 Semester objects while a student B in the 5th Semester will have 5. The credit class count is also the same case. Therefore, defining static headers in CSV is difficult, given the data will vary on each row. That said, the only plausible solution in my mind: Export each M2M model data in the form of a list of JSON, dump the list … -
Difficulty converting html page with CSS and images to PDF in Django
I am trying to convert an HTML page which uses quite the bootstrap and styling. I tried everything from reportlab to weasyprint to xhtml2pdf and nothing works! I did not find anything online to help me do this simple task. I even tried looking for paid APIs that do this kind of jobs. What is the best way to achieve this? -
i was trying run a pretrained chatbot but got this error......(link to project file:https://github.com/lukalabs/cakechat) please help me
(chatvirt) PS C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1> python tools/fetch.py Using TensorFlow backend. 2022-05-14 22:49:09.001133: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 Traceback (most recent call last): File "tools/fetch.py", line 15, in <module> from cakechat.dialog_model.factory import get_trained_model File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\factory.py", line 8, in <module> from cakechat.dialog_model.inference_model import InferenceCakeChatModel File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\inference_model.py", line 1, in <module> from cakechat.dialog_model.keras_model import KerasTFModelIsolator File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\keras_model.py", line 11, in <module> from cakechat.dialog_model.abstract_model import AbstractModel File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\abstract_model.py", line 6, in <module> from cakechat.dialog_model.quality.metrics.utils import MetricsSerializer File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\quality\__init__.py", line 2, in <module> from cakechat.dialog_model.quality.metrics.lexical_simlarity import calculate_lexical_similarity, get_tfidf_vectorizer File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\quality\metrics\lexical_simlarity.py", line 3, in <module> from sklearn.feature_extraction.text import TfidfVectorizer File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\__init__.py", line 64, in <module> from .base import clone File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\base.py", line 13, in <module> from .utils.fixes import signature File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\utils\__init__.py", line 16, in <module> from .fixes import _Sequence as Sequence File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\utils\fixes.py", line 92, in <module> from scipy.sparse.linalg import lsqr as sparse_lsqr # noqa File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\scipy\sparse\linalg\__init__.py", line 114, in <module> from .isolve import * File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 6, in <module> from .iterative import * File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 10, in <module> from . import _iterative ImportError: DLL load failed: The specified module could not be found. -
'Product' matching query does not exist
this is the views code, the item is in the database but it still brings DoesNotExist, i have also tried get_object_or_404 im trying this url http://127.0.0.1:8000/store/shirts/mavi-jeans/ def product_detail(request, category_slug, product_slug): try: single_product = Product.objects.get(category__slug=category_slug, slug=product_slug) except Exception as e: raise e context = {'single_product':single_product} return render(request, 'store/product_detail.html', context) urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='products_by_category'), path('<slug:category_slug>/<slug:product_slug>/', views.product_detail, name='product_detail'), ] -
HTTP retrieval failure when creating drop-in audio chat using Twilio
I am leveraging the Twilio Programmable Voice API to create a drop in audio chat room when a user completes a signup form. I am using ngrok to listen to both my React frontend app and Django backend app so I can expose my local server to the internet. However, when I complete the form, I get the prompt to activate my mic and then hear the error Sorry, an application error has occurred, goodbye before my call drops. My Twilio error logs shows the error: Error - 11200 An attempt to retrieve content from https://f5b7-104-182-176-156.ngrok.io/voice_chat/rooms/Emmanuel returned the HTTP status code 404 HTTP retrieval failure Possible Causes Web server returned a 4xx or 5xx HTTP response to Twilio Misconfigured Web Server Network disruptions between Twilio and your web server No Content-Type header attached to response Content-Type doesn't match actual content, e.g. an MP3 file that is being served with Content-Type: audio/x-wav, instead of Content-Type: audio/mpeg When I do a GET on an endpoint that should show me all my rooms http://127.0.0.1:8000/voice_chat/rooms I get an empty list, indicating that no rooms have been created? Here is my React code: ... const NewRoom = () => { const [state, setState] = useGlobalState(); … -
Better solution to a increasing number game?
I am trying to build a game where on the server side I am providing a random number ex. 4.31. Then on the browser side users see a number growing from 1.00 to 4.31. They don't know the number provided from the server and have to just guess when to stop by clicking on a button. Right now I have a solution where I run everything as a background process using apscheduler. I run the function of increasing the number by 0.01 each 0.1 seconds and send the result to the front end using channels. I can't send the random number calculated in the background to front end as I think this is not safe. I am wondering if there is a better/more efficient solution to this as calling a function every 0.1s forever seems odd to me? I am happy to give more explanation/code examples if my question seems unclear. -
URL Variable Subdirectory Error in Django
A view in my Django app takes a URL variable/argument which in my case is a URL like: https://google.com so it would look something like this: localhost:8000/api/https://google.com Because the URL variable above contains slashes, Django will try to find new subdirectories whereas I want Django to ignore them. How can I achieve that??? -
Django - Form not saving when submitted
Good afternoon all, One of my form does not seem to save when submitted. I cannot see why, in particular as I have a similar form working just fine using the same code. For some reason it work just fine using the admin panel. My assumption is that I am missing something that tells the form it needs to be saved. But cannot find what. Any ideas? Models RATING=( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) class ProductReview(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review_text=models.TextField(max_length=250) review_rating=models.IntegerField(choices=RATING,max_length=150, default=0) date_added = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) Views def add_review(request, product_id): product = Product.objects.get(pk=product_id) form = ReviewAdd(request.POST or None, instance=product) #instance=product (populate field with existing information) if form.is_valid(): form.save() return redirect('product') return render(request, 'main/add_review.html',{'form':form}) URL from django.urls import path from . import views urlpatterns = [ ... path('product/add_review/<product_id>', views.add_review,name="add_review"), ] Forms class ReviewAdd(forms.ModelForm): class Meta: model = ProductReview fields = ('review_text', 'review_rating') labels ={ 'review_text': '', 'review_rating': '', } widgets = { 'review_text': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Review'}), } Admin from django.contrib import admin from .models import Venue, User, Product, ProductReview from django.urls import path admin.site.register(User) admin.site.register(ProductReview) class ProductReview(admin.ModelAdmin): list_display=['user','product','review_text','get_review_rating'] HTML Page {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block title %} {% endblock %} {% block … -
ifcopenshell geom.settings OverflowError
im tying to serialize an ifc file to gltf using ifcopenshell: settings = ifcopenshell.geom.settings#(APPLY_DEFAULT_MATERIALS=True) sr_2 = ifcopenshell.geom.serializers.gltf(v_path.joinpath(glb_file_nom), settings) but I got this error: settings | Error in formatting: OverflowError: in method 'IteratorSettings_get', argument 2 of type 'uint64_t' when I run on blender I got this: Traceback (most recent call last): File "/snap/blender/2106/3.1/python/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<blender_console>", line 1, in File "/home/fcr/.config/blender/3.1/scripts/addons/blenderbim/libs/site/packages/ifcopenshell/ifcopenshell_wrapper.py", line 857, in repr (", ".join(map(lambda x: "%s = %r" % (x, self.get(getattr(self, x))), d()))) File "/home/fcr/.config/blender/3.1/scripts/addons/blenderbim/libs/site/packages/ifcopenshell/ifcopenshell_wrapper.py", line 857, in (", ".join(map(lambda x: "%s = %r" % (x, self.get(getattr(self, x))), d()))) File "/home/fcr/.config/blender/3.1/scripts/addons/blenderbim/libs/site/packages/ifcopenshell/ifcopenshell_wrapper.py", line 220, in get return _ifcopenshell_wrapper.IteratorSettings_get(self, setting) OverflowError: in method 'IteratorSettings_get', argument 2 of type 'uint64_t' what am I missing? -
what is the use of creating a new way of url pattern in this code and what does it symbolize?
Blockquote file path of the url hello guys i am just a beginner in django so i cant understad what is the use of using this url pattern in this code from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEIDIA_URL, document_root=settings.MEDIA_ROOT) -
How would we set up LoginRequiredMixin? I am Getting following Error
Settings: LOGIN_URL = 'login_view' Views: class MyView(LoginRequiredMixin,View): template_name = "login.html" login_url = 'login.html' redirect_field_name = 'redirect_to' login_view = MyView.as_view() Url: urlpatterns = [ path('admin/', admin.site.urls), path('',include('blogApp.urls')), path("login_view/",view=MyView.as_view(template_name = "storefront/login.html"), name="login_view"), ] And Template is in ./templates/storefront/login.html I am getting Page not found (404) -
Django Framework : Problems with views settings
im learning Django framework and having some issues that i dont get it. Actually i have apps like Polls/ Blog/ and my homepage/ installed and working as i want. My problem is to display each data into my homepage_index.html like : _ how many Question my polls contain _ how many Article my blog contain Both of informations are from different apps. From Django Tutorial i found a solution to display by example my last 3 Question.objects like this. homepage/views.py : from django.views import generic from django.utils import timezone from polls.models import Question class homepage(generic.ListView): template_name = 'homepage/homepage_index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:3] my homepage_index.html working : {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a style="color: white; text-decoration: none;" href="{% url 'polls:detail.html' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} How can i define in my homepage/views.py with multiple context_object_name and multiple queryset please ? I tryied to read many documentations but im still failing -
REGISTER WITH ORM DJANGO [closed]
if I add in the database there is insertion in the customUser table and not in the customer table please help me it's urgent -
Django : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Error When Click Button for send data. Please Helping me to solve problem. Error When Click Button for send data. Please Helping me to solve problem. Error When Click Button for send data. Please Helping me to solve problem. detail.html td> <!-- <a href="{% url 'Detail_pem' %}"><button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </a> --> <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> --> <script> var id_order = document.getElementsByClassName('id_order') for (i = 0; i < id_order.length; i++) { id_order[i].addEventListener('click', function(){ var orid = this.dataset.product var ornm = this.dataset.act console.log('orid :', orid) console.log('ornm :', ornm) codata(orid, ornm) }) } function codata(orid, ornm){ console.log('orid :', orid, 'ornm :', ornm) const url = "Detail" fetch(url, { method :'POST', headers : { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'orid':orid, 'ornm':ornm}), }) .then((response) =>{ return response.json(); }) .then((data) => { console.log('Success:', data); }) } </script> {% endblock %} view.py def Detail(request): data = json.loads(request.body.decode("utf-8")) orid = data['orid'] ornm = data['ornm'] print('id :', orid,'nama :', ornm) context = {'orid ':orid , 'ornm':ornm} return render(request, 'store/detail.html', context ) -
Heroku Django Postgre
So, I was building a Django app, I created an intro field for a post formular, I did that in my models.py file: class Post(models.Model): title = models.CharField(max_length=100) intro = models.CharField(max_length=1024) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('donut-post-detail', kwargs={'pk': self.pk}) I renamed 'description' into 'intro' so, when I did the makemigrations command it maked me a file named: 0002_rename_description_post_intro.py I hosted it into heroku, commited changes and migrated it when this happened: ~ $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, users Running migrations: Applying blog.0002_rename_description_post_intro...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "description" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, … -
Custom rest_framework_simplejwt authentication class for reading HTTPonly cookies ignores permission_classes = (permissions.AllowAny,)
I have defined a custom authentication class that extends the default rest_framework_simplejwt.authentication.JWTAuthentication as follows: myaccount.authenticate.py def authenticate(self, request): header = self.get_header(request) if header is None: # If header is None, get token from cookie raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_ACCESS_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) return self.get_user(validated_token), validated_token I then added the following to settings.py 'DEFAULT_PERMISSION_CLASSES':[ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES':[ 'myaccount.authenticate.CustomJWTAuthentication' ] } views.py class Login(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): pass When I make a call to the above view despite having permissions set to AllowAny, I get the following response. { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } What could I have missed? Thank you. -
Python list overwritten each time the previous items
The objective of my application is to create a copy of documents and insert them into the database for each annotator, for example, let's say the master user has 3 documents and two annotators, let's say the first annotator has the email testmail1@mail.com and the second one has the email testmail2@mail.com, finally, I need to insert in the database 3 documents for testmail1@mail.com and 3 other documents for testmail2@mail.com. So to do this, I created first a list containing the copy of documents, and I didn’t assign the annotator created_documents_in_iaa = [] created_documents_in_iaa += [DocumentIAATask( name=document.name, spans=document.spans, entity=document.entity, original_document=document, IAA_Task=iaa_task) for document in all_documents_in_iaa.iterator(chunk_size=1)] And after that, I added an annotator to each document, and I append each modified created_documents_in_iaa list to the tsks_list: tasks_list = [] for user in users_instance_list: try: for i in range(len(created_documents_in_iaa)): created_documents_in_iaa[i].annotator = user tasks_list.append(created_documents_in_iaa) except Exception as e: print(e) Finally, I created a copy of documents in the PostgreSQL database: for task in tasks_list: DocumentIAATask.objects.bulk_create(task) However, in the result, I found 6 documents inside the table of the first annotator, and nothing for the other one, after I debugged the code, I found that tasks_list overwritten each time the list, that's means when I … -
Best approach to implement server-side caching on a Django GraphQL API?
I have an Angular frontend that uses Apollo Graphql client to interface with a Django Graphql backend (using graphene). It all works well, but the API is very slow, especially when there are concurrent users. I am trying a few things to speed up the API server. One of the things that I am seriously considering is to use server-side caching. I'm aware that there are some caching solutions that exist for Django out of the box, but these seem to be for caching the views. Is it possible to use these methods to cache Graphql API requests? What is the most effective caching solution for caching the responses to graphql queries in Django? I'm posting some of my project's code here so that you get a sense of how my API works. This is a sample of the Query class containing the various graphql endpints that serve data when queries are received from the client. And I suspect this is where we'll need most of the optimization and caching applied:- class Query(ObjectType): # Public Queries user_by_username = graphene.Field(PublicUserType, username=graphene.String()) public_users = graphene.Field( PublicUsers, searchField=graphene.String(), membership_status_not=graphene.List(graphene.String), membership_status_is=graphene.List(graphene.String), roles=graphene.List(graphene.String), limit=graphene.Int(), offset=graphene.Int()) public_institution = graphene.Field(PublicInstitutionType, code=graphene.String()) public_institutions = graphene.Field(PublicInstitutions, searchField=graphene.String(), limit = …