Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
REST API taking too much time to respond
I have built an API using Django & django-rest-framework. The Django Server is currently deployed on Heroku's Free Hobby Dyno. this is how my API call looks right now, GET https://feasta-postgres.herokuapp.com/menu/get_category/?admin_id=5 I am currently testing my API through POSTMAN. PROBLEM I have noticed that when I call this API for the First time, it takes too much (~1 second) time to respond. Then it becomes Faster for the subsequent calls. Then after some interval it again becomes slow. This is the event waterfall for my first request call, This is the event waterfall for my subsequent request calls, As we can see in the first image, the handshakes are eating up most of the time. Questions Is there any way to optimize the first request? If yes then How? Will this also occur when I call this API from a Deployed React website or is this only a Postman problem? My Best Guess I am using a Free Heroku Dyno, that's why Heroku is being "lazy" to process my request. Upgrading it to the paid one will do my job. -
DRF This field is required
I am working on a DRF backend API and React client. Whenever I send the data back to the server I get an error category: this field is required which is true, but I am providing that field. I have modified the actual create() viewset function in order to add additional data to the logic: class QuestionViewSet(viewsets.ModelViewSet): """ API endpoint that allows user to view and edit Question model """ queryset = Question.objects.all().order_by('-updated_at') serializer_class = QuestionSerializer permission_classes = [permissions.IsAuthenticated] filterset_fields = ['created_by', 'created_at', 'updated_at', 'status', 'score'] def create(self, request, *args, **kwargs): serializer = QuestionSerializer(data=request.data, context={'request': request}) if not serializer.is_valid(): return Response(serializer.errors, status=400) serializer.save(created_by=request.user) return Response({ 'question': serializer.data }) I am getting that 400 status response whenever I send a message that is printed in the same backend console: <QueryDict: {'question': ['test'], 'category': ['2']}> The serializer itself: class QuestionSerializer(serializers.ModelSerializer): category = CategorySerializer() answers = AnswerSerializer(many=True, source='answer_set', allow_null=True, required=False) expert = UserSerializer(required=False) moderator = UserSerializer(required=False) created_by = UserSerializer(required=False) class Meta: model = Question fields = [ 'id', 'category', 'question', 'status', 'expert', 'moderator', 'created_by', 'created_at', 'updated_at', ] I have tried changing category for category_id but it does not work either. My client function is something like this: const query = useQuery(); const urlSufix … -
Unable to Add New Blank Field in Django (DataError)
I am try to create an django application with Seller, Books apps. It was running fine but I wanted to add one more field in my db and added one more field in books\models.py with blank=True. I am trying to add new blank field but unable to migrate. I try to run the code : python manage.py migrate. Error and and code is: models.py from django.db import models from datetime import datetime from book_sellers.models import Seller # Create your models here. class Book(models.Model): seller = models.ForeignKey(Seller,on_delete = models.DO_NOTHING) bname = models.CharField(max_length=100) isbn = models.CharField(max_length=40,blank=True) genre1 = models.CharField(blank=True,max_length=32,choices=[("1","Motivational"),("2","Fiction"),("3","Business"),("4","Children"),("5","Health"),("6","Story")],) genre2 = models.CharField(blank=True,max_length=32,choices=[("1","Motivational"),("2","Fiction"),("3","Business"),("4","Children"),("5","Health"),("6","Story")],) genre3 = models.CharField(blank=True,max_length=32,choices=[("1","Motivational"),("2","Fiction"),("3","Business"),("4","Children"),("5","Health"),("6","Story")],) writerName = models.CharField(max_length=100,blank=True) price = models.IntegerField() number_of_enquiry = models.CharField(max_length=100,blank=True) description = models.CharField(max_length=1000) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') list_date = models.DateTimeField(default = datetime.now(),blank = True) is_published = models.BooleanField(default = True) def __str__(self): return self.bname ** Getting this Error ** Traceback (most recent call last): File "C:\Users\HP\OneDrive\Desktop\PROJECT\BookStore\manage.py", line 22, in <module> main() File "C:\Users\HP\OneDrive\Desktop\PROJECT\BookStore\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = … -
Checkbox filter django
I'm improving my English, be patient I'm using django-filter and in some part of my HTML I have this structure {% if viagens.count == 0 %} <div class="row justify-content-center"> <h3 class="text-danger">O colocador nao fez nehuma viagem</h3> </div> {% else %} <div class="row"> <form action="" method="GET"> {% csrf_token %} # here I want a checkbox that automatically submit the form </form> </div> {% for viagem in viagens %} <p>Placeholder</p> {% endfor %} {% endif %} I don't have javascript knowledge, I need this with pure HTML and Django -
CDN script link not found in Django using bokeh
In my Django base template, I need to download a bokeh script from CDN: <!DOCTYPE html> <html> <head> <link href=”https://cdn.bokeh.org/bokeh/release/bokeh-2.3.1.min.css" rel=”stylesheet” type=”text/css”> <link href=”https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.1.min.css" rel=”stylesheet” type=”text/css”> <script src=”https://cdn.bokeh.org/bokeh/release/bokeh-2.3.1.min.js"></script> <script src=”https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.1.min.js"></script> {{ script | safe }} <title> Hello World! </title> </head> <body> {{ div | safe }} </body> </html> The bokeh documentation here advises the exact location for its respective version. And they do exist. Without the script, a Django view that is supposed to render a bokeh chart at div does not show anything. Below is my views.py: from django.shortcuts import render from bokeh.plotting import figure, output_file, show from bokeh.embed import components def homepage(request): #Graph X & Y coordinates x = [1, 2, 3, 4, 5] y = [1, 2, 3, 4, 5] #Set up graph plot for displaying line graph plot = figure(title = 'Line Graph', x_axis_label = 'X-Axis', y_axis_label = 'Y-Axis', plot_width = 400, plot_height = 400) # Plot line plot.line(x, y, line_width = 2) # Store components script, div = components(plot) # Return to Django homepage with component sent as arguments which will then be displayed return render(request, 'pages/base.html', {'script': script, 'div': div}) Am I missing anything with respect to the bokeh part here? Thanks. -
using django-tables2 in dashbord
Trying to put django table into dashboard.html page. I can visualize my table in another html file but cant fix how to put inside the dashboard page models.py class Asset(models.Model): type = models.ForeignKey(AssetType, on_delete=models.CASCADE) lc_phase = models.ForeignKey("Asset_Life_Cycle.LifeCyclePhase", on_delete=models.CASCADE) name = models.CharField(max_length=30) # BaseSpatialField.srid() geom = models.GeometryField() views.py from .models import Asset import django_tables2 as tables class AssetTable(tables.Table): class Meta : model = Asset class AssetTableView(tables.SingleTableView): queryset = Asset.objects.all() table_class = AssetTable template_name = 'deneme.html' Tried this but didnt work {% for asset in queryset %} <p>Name {{asset.name}} </span> </p> {% endfor %} -
Django ORM "|" operator returning duplicate items
Say I have a Model class that looks something like: class User: ... projects = models.ManyToManyField(Project, blank=True) subscribed_projects = models.ManyToManyField(Project, blank=True) I have some view logic that returns the contents of both querysets: return self.request.user.projects.all() | self.request.user.subscribed_projects.all() In my particular scenario, assume that the same project won't be in both. Here's the current relationships for one of the users: >>> me = User.objects.get(id=1) >>> me.projects.all() <QuerySet [<Project: A>, <Project: B>, <Project: C>, <Project: D>, <Project: E>]> >>> me.subscribed_projects.all() <QuerySet [<Project: F>]> Here's the part I cannot explain: >>> me.projects.all() | me.subscribed_projects.all() <QuerySet [<Project: A>, <Project: B>, <Project: C>, <Project: D>, <Project: D>, <Project: E>, <Project: F>]> Project "D" appears twice here, even though it only appears in one of the querysets! Now, I can achieve the behavior I want by adding distinct() or using union() instead, but why is it behaving this way? -
service on gke pod that was running fine for a year suddenly starts failing with db connection error
I have been a running a service on gke for more than a year without any problems, but just yesterday I started seeing "some backend services are in an UNHEALTHY" state on the kubernetes services/ingress dashboard. When I look into the pod I see the error message below. I never had any problem before and haven't changed anything with my configuration. How should I go about fixing this ? /usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py”, line 217, in ensure_connection self.connect() File “/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py”, line 195, in connect self.connection = self.get_new_connection(conn_params) File “/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py”, line 178, in get_new_connection connection = Database.connect(**conn_params) File “/usr/local/lib/python3.7/site-packages/psycopg2/init.py”, line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused -
Filtering objects with json data | Django
When i try to filter the object with the name that i got from the json data the queryset is empty but when i try to filter it with hardcoded value the queryset exists. The name is exactly same in the json data and in the object but it returns empty. name = w.get('name') its type is str. The value is new_template_duke_1 Can you please help why the queryset is empty in this line templates = templates.filter(template_name=name) waba = res.get('waba_templates') templates = MerchantWhatsappTemplate.objects.filter( merchant=merchant, approved=False, rejected=True ) qs = templates.filter(template_name="new_template_duke_1") print(qs) <<<<<<<< Not empty if not templates.exists(): return for w in waba: category = w.get('category') name = w.get('name') <<<<<< "new_template_duke_1" status = w.get('status').upper() rejected_reason = w.get('rejected_reason') templates = templates.filter( template_name=name ) print(templates) <<<<<<< Empty queryset -
How to upload image file with react and django rest framework
Hello All I'm working on a fullstack app using react on the frontend and django on the backend, I'm using the default session authentication and also serving react as a django template through index.html file. I'm currently serve my pages through the django server itself, so everything is will be under the URL: http://localhost:8000/ and I'm also using redux to manage the state. I'm trying to update the UserProfile model by uploading the user image from react and store it in the backend server but it saves the image filename instead of creating a new media folder. UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_no = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') bio = models.TextField(max_length=500, default='') skills = models.CharField(max_length=255, default='') avatar = models.ImageField( default='', blank=True, null=True, upload_to='avatars') def __str__(self): return self.user.username settings.py file 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 # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Getting an Import Error While trying to Run Cron Job with Django App
I'm trying to create a CRON job to run a script every minute however I'm getting the error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Inside my crontab -e command: * * * * * /usr/bin/python3 /Users/user/Documents/Program/App/manage.py command Running this my terminal says I get new mail every minute but when I click on the message I get the above importError. I am using a .env file at the root of my directory to keep my API keys secure but I don't think that's important.I'm also not using a virtual environment at the moment but I have tried and however I can't find the correct python version installed into the virtual environment. Running this command python3 ./manage.py command from the command works as expected which is why this is really confusing. -
Django Admin not limiting choices on ManyToMany field
I suddenly am having a problem with my django admin panel. I have the following models: class Role(models.Model): name = models.CharField("Name", max_length=32) class Person(models.Model): name = models.CharField("Name", max_length=64) role = models.ForeignKey(Role) class Team(models.Model): rep = models.ManyToManyField( Person, related_name="rep_on", limit_choices_to={'role__name': 'Sales Rep'}) eng = models.ManyToManyField( Person, related_name="eng_on", limit_choices_to={'role_id__name': "Engineer"}) (The two options in the limit_choices_to dictionaries are the two methods I've tried. In the past it seemed like role_id__name worked, but now it doesn't.) If I create roles for the Sales Rep and Engineer, and create a bunch of people and attach roles, when I create a Team in the admin, I get dropdowns like I expect: There are two problems. Each dropdown contains every Person object, so limit_choices_to doesn't seem to work at all, and of course these relationships are generic "TEAM-PERSON RELATIONSHIPS" and I'd like to be able to at least label those correctly. I swear this worked before, and now it's not working. Any ideas as to what could be causing this? -
Django query by related object with calculated value
I have this Class structure: class A(models.Model): pass class B(models.Model): CHOICE_1 = 'example-1' CHOICE_2 = 'example-2' CHOICE_3 = 'example-3' EXAMPLE_CHOICES = [ (CHOICE_1, 'Example 1'), (CHOICE_2, 'Example 2'), (CHOICE_3, 'Example 3') ] choice = models.CharField(max_length=20, choices=EXAMPLE_CHOICES) important = models.BooleanField() parent = models.ForeignKey(A, on_delete=models.CASCADE, related_name="child") I need to get all A objects that have related B objects filter by: At least one child have important=True At least one child have CHOICES_1 or CHOICE_2 in choice attr. So far the query would be: A.objects.filter(child__important=True, child__choice__in=[CHOICE_1, CHOICE_2]) HERE IT COMES THE QUESTION Also, I need to get an extra calculated field which value should be: If A has only CHOICE_1 childs --> calculated value = "Example 1 only" elif A has only CHOICE_2 childs --> calculated value = "Example 2 only" elif A has childs, some CHOICE_1 and some CHOICE_2 --> calculated value = "Both" -
How to read csv file using pandas from django server
I'm learning Django I have a CSV file in the Django server now I want to show it on an HTML page. can you help me that how to show it on the HTML page? OR How to read a csv file using pandas in html page? -
Django multiple models relationship
I'm making some models and I want to be able to create a match. Each match has its own game. Every game can have a set of rules. The user, when creating the match can choose the game and also, choose one or many rules of the respective game, to apply to the match. Also, the user can create a custom rule. How this is going to be, in terms of models? And how it would work? About the custom rule, I can create a new field for it on the Match model. I thought that the models could be something like that: class Match(models.Model): game = models.OneToOneField(Game) custom_rule = models.CharField(max_length=100) class Game(models.Model): name = models.CharField(max_length=100) class GameRule(models.Model): game = models.ForeignKey(Game) rule = models.CharField(max_length=100) But I'm not sure if it would work. Can someone help me? -
Trying to set non-model field in model form to some other field that exists in the model
I have a form that I need to add an extra field to - and it needs to have an initial value of the data model's time field (called seg_length_time). I didn't expect the code to work because I know I need to convert the time into a string from the model, but I can't seem to figure out how to set the field to begin with. See code below: class SegmentForm(forms.ModelForm): str_seg_length_time = forms.CharField(max_length=8) class Meta: model = Segment exclude = ('seg_length_time_delta', 'seg_length_time', 'seg_run_time', 'seg_run_time_delta' , 'seg_remaining_time', 'seg_remaining_time_delta', 'program_id', 'audit_user', ) def __init__(self, *args, **kwargs): obj = Segment.objects.get(id=self.pk) self.fields['str_seg_length_time'].initial = obj.seg_field_length super().__init__(*args, **kwargs) The snippet of the model is below: class Segment(models.Model): class Meta: ordering = ['sequence_number'] program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', # link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190) bridge_flag = models.BooleanField(default=False) seg_length_time = models.TimeField(null=True,default=None, blank=True) . . (other code below this) I haven't included the whole thing, but you get the idea. The field shows up on the form as nothing (Blanks), if I don't do some sort of initial code to set it from the model. Can I get the object by id, or - dont I already have the object in the … -
Removing an apostrophe from a Django Jinja Template?
I would like to remove an apostrophe from a Django template variable in HTML using Jinja. The variable item.product is Paul's Phone which I am using to open a Boostrap Modal: id="move_{{ item.product|cut:' ' }}" This will remove the spaces, which is good. The outcome now is Paul'sPhone, but I can't remove the apostrophe by doing this: data-target="#move_{{ item.product|cut:' ', ''' }}" How do I get around these tags to remove the apostrophe from that variable? -
how to check the submit in django
I'm new to Django my problem is when the user refreshes the page the rate always increases even the user answer the question or not how to prevent rate increase if the user doesn't answer the question I don't know how to solve that any help <form id="resultform" action="/game1/" method="POST"> {% csrf_token %} <input type="hidden" name="std_email" id="std_email" value="{{std_email}}" /> <input type="hidden" name="std_quest" id="std_quest" value="" /> <input type="hidden" name="std_answer" id="std_answer" value="" /> </form> <button type="button" class="btn btn-primary btn-circle btn-xl" onclick="checkAnswer()" > Check </button> def game(request, std): qest = getQuestion() context = { 'question': qest, 'std_name': std[0].name, 'std_rate': std[0].rate, 'std_email': std[0].email, } return render(request, 'qgame.html', context) def getQuestion(): tmp = UserQuestion.objects.all() length = tmp.count() rand = random.randint(1, length) qest = UserQuestion.objects.get(pk=rand) return qest def checkAnswer(request): if(request.method == "POST"): std_quest = request.POST['std_quest'] std_ans = request.POST['std_answer'] std_Email = request.POST['std_email'] std = Student.objects.filter(email=std_Email) if(std_quest == std_ans): rate = std[0].rate rate += 1 Student.objects.filter(email=std_Email).update(rate=rate) return game(request, std) elif(std_quest != std_ans): rate = std[0].rate rate -= 1 Student.objects.filter(email=std_Email).update(rate=rate) return game(request, std) -
Allow only staff member to delete post don't allow any other user to delete
inside views.py can we overide some method inside Postdelete to achieve this i have tried using class PostDelete(DeleteView): model = Post def get_queryset(self): if self.request.user.is_staff: return super(PostDelete, self).get_queryset() def get_success_url(self): return reverse('dashboard') -
Wagtail form builder: How to preserve query string/url parameter from form page for corresponding landing page?
In a wagtail project with a wagtail form builder [1] the default implementation redirects the user after successful form submission to a landing page [2]. In my somewhat special implementation of my form page (AbstractEmailForm) I use a query string (here: ?embed=true) to adjust the rendered page/layout for being "embeddable" (via an iFrame). That works. But after submitting the form on such a page, the method render_landing_page[3] gets called and renders a landing page for that form. But my query string is lost. How do I preserve the query strings from the form page to the corresponding landing page? [1] https://docs.wagtail.io/en/stable/reference/contrib/forms/index.html [2] https://docs.wagtail.io/en/stable/reference/contrib/forms/customisation.html#custom-landing-page-redirect [3] https://github.com/wagtail/wagtail/blob/571b9e1918861bcbe64a9005a4dc65f3a1fe7a15/wagtail/contrib/forms/models.py#L270 -
Unable to save images to model after scraped with beautiful soup
I have tried to saving images to my database immediately I scraped it from a website using beautiful soup and it has refused to save I have tried rectifying this for more than three months now but it seems impossible. What do I do to resolve this. Am very very tired and frustrated with this. This images are urls containing url on database this will give me an error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' this error is as a result of my attempts to save this scraped image with beautiful soup below are images list that refused to be saved on my models , this images are been scraped with beautiful soup something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg why this code brought the above error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this is my model.py example code class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') but i get this error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' but if … -
is it better to include token in the User model for Django+Jwt?
i'm looking at different ways of using django rest framework with jwt, and most cases would do it in a "normal" way (as the Getting started in the simple Jwt Documentation says), but i encoutred some ones that extends the User model and include the Token inside, something like : class User(AbstractBaseUser, PermissionsMixin): # .....(usual fields(username, password,...)) @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token is this way better? or is it just a different way to handle it? what difference does it make? -
Ajax in django form
My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !! I want my type in the input submit and when I do this the Ajax request will not work and the page will reload. $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); my form : <form action="" class="filter-form"> <input type="submit" name="price" value="new"> <input type="submit" name="discount" value="discount"> <input type="submit" name="old" value="old"> </form> -
static file directory not found (heroku)
I am making a site with Django 2.2 . But when i try to run git push heroku master an error occours . I tried all the stackoverflow answers but nothing worked. here is my directory: ├───.idea │ └───inspectionProfiles ├───.vscode ├───CheemsCode_Site │ └───__pycache__ └───homepage ├───migrations │ └───__pycache__ ├───static │ ├───css │ ├───img │ │ ├───portfolio │ │ ├───team │ │ └───testimonials │ ├───js │ └───vendor │ ├───bootstrap │ │ ├───css │ │ └───js │ ├───bootstrap-icons │ │ └───fonts │ ├───boxicons │ │ ├───css │ │ └───fonts │ ├───glightbox │ │ ├───css │ │ └───js │ ├───isotope-layout │ ├───php-email-form │ ├───purecounter │ └───swiper ├───templates └───__pycache__ here is my settings.py: """ Django settings for CheemsCode_Site project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/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 # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'sq@0@!_3yqx%c=%vd_xe4h($n47066smhg3)u2+ro2+gfp8qxa' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application … -
Django BuiltinSignatureError when using DRF
I am not able to figure out the error. The API sometimes returns data and at times it does not. class CreateQuiz(generics.ListCreateAPIView): serializer_class = QuizSerializer def get_queryset(self): classId = self.kwargs.get('classId',None) subject = self.kwargs.get('subject',None) category = Category.objects.filter(class_id=classId,category=subject).values_list('id',flat=True)[0] # chapter = self.kwargs.get('chapter',None) subcategory=self.kwargs.get('chapter',None) subcat = SubCategory.objects.filter(id=subcategory).values_list('sub_category',flat=True)[0] total_marks = 30 questionIDs = Question.objects.raw('''somesql''',params=[category,subcategory,total_marks,category,subcategory,total_marks]) # # and qq.sub_category_id IN %s questions= MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question') essayquestions= Essay_Question.objects.filter(question_ptr_id__in=questionIDs) user = User.objects.get(id=1) if MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question').exists(): print("create quiz") quiz = Quiz() quiz.durationtest="10:00" quiz.random_order=True quiz.save() quizid = Quiz.objects.filter(id=quiz.id).values_list('id',flat=True)[0] quiz = Quiz.objects.get(id=quiz.id) quiz.title = "Practice Exam : "+ quiz.category.class_id.classVal +" "+quiz.category.category +" ("+subcat+") " quiz.save() with connection.cursor() as cursor: cursor.execute("INSERT INTO quiz_subcategory_quiz(subcategory_id,quiz_id) VALUES (%s,%s)",(subcategory,quiz.id,)) for obj in questionIDs: if Question.objects.filter(id=obj.id,quiz__id=quiz.id).exists(): print("Do nothing") else: question = Question(id=obj.id) question.quiz.add(quiz.id) question.save() obj, created = UserQuiz.objects.update_or_create( user_id = user.id,quiz_id=quiz.id ) return Quiz.objects.filter(id=quizid) else: response = JsonResponse({"error": "there was an error"}) response.status_code = 403 # To announce that the user isn't allowed to publish return response return Quiz.objects.filter(id=quizid) My Serializer Class class QuizSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields=( 'id', 'title', 'description', 'url', 'category', 'random_order', 'pass_mark', 'draft', 'durationtest', ) I get the following error and its happening randomly. Any suggestions please. Field source for QuizSerializer.title maps to a built-in function type and is invalid. Define a property or …