Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
inlineformsetfactory validate_min validate other form than first
I want to write a form that contains a question and at least 2 answer choices. A user should provide at least 2 choices for the question to validate. To do that I am using inlineformsetfactory with the kwargs: { ... 'min_num': 2, 'validate_min': True, 'max_num': 20, 'validate_max': True, 'extra': 2 } The problem I am facing is: Django does not look if 2 answers are given but rather if answer[0] and answer[1] are filled. This is what I see upon submitting my form. Possible duplicate of this post - that unfortunately does not have an answer either. It seems that Djangos method of checking out-of-order forms does not really exist. In case that you are wondering why I don't provide my full inlineformsetfactory - I use a the extra-views package that allows for class based InlineFormSetFactory but works just like the normal django function. -
Why am I obtaining this error message trying to migrate a Django application from SQL Lite DB to Postgres DB?
I am pretty new in Django and Python and I am trying to follow this videotutorial about how to migrate a Django application from SqlLite to Postgres database: https://www.youtube.com/watch?v=lR4N4rhGdjo But I am finding some problem. Following the details on what I have done: I am working on Ubuntu 20.04 and I have a Django application made by someone else that uses SQLLite and that have to be migrated on Postgres. Following the previous tutorial I have done the following steps: First of all I installed Postegres and PgAdmin4 on my Ubuntu system. Then I created a DB named dgsrgdb that have to be my new database for my application: It have defined 2 users: one is the "root" user and the other one an user that can operate only on this specific DB. I installed this package to let Python\Django operate with Postgres: pip3 install psycopg2-binary I performed the backup of my original SqlLite DB by this command: python3 manage.py dumpdata > datadump.json and I obtained the datadumo.json file that should contains the data inside the original DB that have to moved on the new Postgres DB. Into the Django settings.py file I replaced this configuration: DATABASES = { 'default': … -
Local React app pointing to hosted Django server CORS no 'Access-Control-Allow-Origin' header
I am running a local version of my react app on localhost:3000 and am trying to hit endpoints on a Django server hosted on heroku Error encountered on each axios request: Access to XMLHttpRequest has been blocked by CORS policy: no 'Access-Control-Allow-Origin' header is present Current settings.py for Django server: ALLOWED_HOSTS=['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'corsheaders', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'accounts', 'blog', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', # Whitenoise 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', #'django.middleware.clickjacking.XFrameOptionsMiddleware', # Machina #'machina.apps.forum_permission.middleware.ForumPermissionMiddleware', ] # CORS CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = False Since I am allowing all origins to make requests, it seems like this type of CORS issue should be disabled. I have tried removing all other middleware except CorsMiddleware and it it did not make a difference. A bit stumped at this point because my configuration seems correct as per https://github.com/adamchainz/django-cors-headers Here is an example api call from my react app that is causing the "no 'Access-Control-Allow-Origin' header" function callCSRFApi(){ return axios.request({ method: 'GET', url: 'http://example.com/csrf/', }); } One thing to note is that I am hitting endpoints on the Django server even though it is not configured as a django_rest api. I have also tried setting a custom … -
DRF auth_token "non_field_errors": [ "Unable to log in with provided credentials." ] using custom user model
I'm trying to create a rest api using an existing database. I am also using drf token authentication and have created tokens for all existing users. When I try to enter my username and password to get my token from my ObtainAuthToken View I receive the following error: "non_field_errors": [ "Unable to log in with provided credentials." ] My code is as follows: Views.py from django.shortcuts import render from django.db import connection from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework import generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from api import serializers from api import models from itertools import chain # Create your views here. class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter, SimpleRouter from api import views urlpatterns = [ path('login', views.UserLoginApiView.as_view()), ] models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager, UserManager from django.conf import settings from django.dispatch import receiver from django.urls import reverse class UserProfileManager(BaseUserManager): … -
destroyable server for dev integration
A little background: In my company we develop multiple features in parallel and test each feature individually. So typically what happens is: - Multiple backend devs work on a feature by the time frontend devs work on some feature. - Stagings are busy for testing and UAT of previous features. - Its not advisable to use stagings for integration and dev testing. - Backend is micro-service architecture mostly in python (Django) which requires migrations and two features can not be merged every time on stagings. - Frontend devs need to wait for staging to be free for integration and dev testing which delays productivity. - Having more stagings will not fix the issue since there are many developers waiting in the queue. - Dev testing and integration can take more than a day. - Using Ngrok has a issue, backend dev will be blocked and can not change branches for next feature. Any suggestions how we can be more productive and tackle this issue? -
'str' object has no attribute 'is_authenticated'
I am using Django 3.8.5. I am building a chat app. AND i am stuck on an Error. views.py def chat(request): if request.method == 'GET': if request.method.is_authenticated: chat_boxes = ChatBox.objects.filter(Q(user_1=request.user) | Q(user_2=request.user)) groups = ChatGroup.objects.filter(members=request.user) else: chat_boxes = [] groups = [] return render(request, 'chathome.html', {'chat_boxes':chat_boxes,'groups':groups}) else: form = ChatGroupForm(data=request.POST,files=request.FILES) group = form.save(commit=False) group.author = request.user group.save() group.members.add(request.user) group.group_admins.add(request.user) return redirect('profile',pk=group.id) The Problem When i open browser it is showing 'str' object has no attribute 'is_authenticated' Any Help would be appreciated. Thank You In Advance -
django-seed generates more data than I request
I'm trying yo generate fake data for my app but I need to generate specific type of users, I check docs for django-seed and I get this code from his page django-seed from django_seed import Seed seeder = Seed.seeder() from myapp.models import Game, Player seeder.add_entity(Game, 5) seeder.add_entity(Player, 10) inserted_pks = seeder.execute() and I tried to generate data of this way seeder = Seed.seeder() seeder.add_entity(User, 1, { 'first_name': lambda x: seeder.faker.name(), 'last_name': lambda x: seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: False, }) seeder.add_entity(User, 10, { 'first_name': lambda x: seeder.faker.name(), 'last_name': lambda x: seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: True, }) seeder.execute() So, I need to generate 10 admins and 1 no admin, but I get only 20 admin, then try creating 2 instances of the seeder. seeder = Seed.seeder() seeder.add_entity(User, 1, { 'first_name': lambda x: seeder.faker.name(), 'last_name': lambda x: seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: False, }) seeder.execute() admin_seeder = Seed.seeder() admin_seeder.add_entity(User, 10, { 'first_name': lambda x: admin_seeder.faker.name(), 'last_name': lambda x: admin_seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: True, }) admin_seeder.execute() this time I get 20 admins and … -
How to select an object automatically FK item (django)
I have a question and answer quiz and when I put it in HTML I have such a result image To save a question, I must first manually select the question. So I want this to happen automatically. Each question will appear automatically. But I could not understand the view I have to change if html and what I have to change this is my code --> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) base.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> {% for i in e %} <form method="POST" novalidate> {% … -
How can I filter already generated django products?
I am using Product class in my models, and in the html I am going through for loop of products. So my question is can you recomand any tutorial or course for that. Filter by category, type, min and max price. Plz dont ban this question. Its very importnant for me ) -
DJANGO: is there any kind of limit with the post requests?
I'm developing an app which you upload an excel file with a lot of rows(could be 10.000 or more rows) and it has to process all those rows. That means that I have to ask through ajax for some data per row. The thing is that when I try this with a big file (arround 5000 rows) it just stops after a lot of requests and doesnt give me any clue, no errors, no warning, nothing. This is the log i receive -----a lot of these more...------ [13/Jan/2021 16:54:46] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:46] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:47] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:47] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:47] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:48] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:48] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:48] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:49] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:49] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:50] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:50] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:50] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:51] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 --- Here it just reload the page --- [13/Jan/2021 16:55:10] "GET /consumos/importar_consumos HTTP/1.1" 200 67866 … -
can't access data from front-end "MultiValueDictKeyError"
Here is My Views from django.contrib import messages from django.contrib.auth import authenticate from django.contrib.auth.models import * from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import * from .models import * def login(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('username') password = request.POST.get('password') User._meta.get_field('email')._unique = True # username verification if User.objects.filter(username=username).exists(): user = auth.authenticate(username=username, password=password) # Email Verification elif User.objects.filter(email=email).exists(): username = User.objects.get(email=email.lower()).username user = authenticate(username=username, password=password) # Forign key data collect from Phone model to User model else: messages.info(request, 'Enter valid username/email/Phone') return render(request, 'login.html') # authenticate if user is not None: auth.login(request, user) return redirect('user_search') else: messages.info(request, 'incorrect password.') return render(request, 'login.html') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('login') @login_required def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] phone = request.POST['phone'] if Customer.objects.filter(c_phone=phone).exists(): messages.info(request, 'Phone number already registered') return render(request, 'register.html') else: user = Customer.objects.create(c_name=username, c_email=email, c_phone=phone) user.save() return redirect('product_list', id=user.pk) else: return render(request, 'register.html') @login_required def product_list(request, id): product = Products.objects.all() customer = Customer.objects.get(pk=id) form = CustomForm() return render(request, 'product_list.html', {'product': product, 'customer': customer}) @login_required def user_search(request): if request.method == 'POST': phone = request.POST['phone'] if Customer.objects.filter(c_phone=phone).exists(): user = Customer.objects.get(c_phone=phone) print(user.pk) return redirect('product_list', id=user.pk) else: return redirect('register') … -
django_filters: How to make DateTimeFromToRangeFilter inline fields?
I have two questions: I am using django_filters and the field DateTimeFromToRangeFilter. This field appears like two fields aligned vertically (see picture). How can i make this fields display inline? I also would like to add a text before of every field. Is there a way to do this in django? Thank you. -
How to define MEDIA location when using django-tenants?
I am using django-tenants and I want to have folder for every tenant MEDIA files, but at the moment it is OK for me to have shared static files. My settings part for STATIC and MEDIA: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" # MULTITENANT_RELATIVE_MEDIA_ROOT = "" # (default: create sub-directory for each tenant) MULTITENANT_RELATIVE_MEDIA_ROOT = "%s" So, in views I tried to define location as I did before without django-tenants: file_location = settings.MEDIA_ROOT + image.svg This would work, but it just drops the file to: 'C:\\Users\\PcUser\\Documents\\GitHub\\ProjecName\\media/image.svg' Without tenant subfolder... I tried to do it this way: file_location = settings.MULTITENANT_RELATIVE_MEDIA_ROOT + image.svg But it would save to: '%s/image.svg Maybe I should get the schema name from request and just add the folder in views.py? What would be the right way? Documentation is not really clear on this part, and I cannot put together any concept in my head. Could any one help me out? Thanks! -
onchange function doesn't work with some fields
This funtion is to show the product price when i choose a product from a dropdown list. I'm working on django project, when a 'price_buy' field is set to DecimalField on models, this function doesn't work, but if FloatField, it works fine. Also if another field is None, i get this error msg (Uncaught ReferenceError: None is not defined at HTMLSelectElement.select.onchange ((index):552)). How i can resolve this problem ?. <script type="text/javascript"> document.querySelectorAll("select").forEach((select) => { select.onchange = function(){ var price_buy = 0; const value = this.value; {% autoescape off %} const products = {{ products }} {% endautoescape %} for (var index=0; index < products.length; index++ ) { if (products[index].id == value) { price_buy = products[index].price_buy; } } const name = this.name.replace("product", "price_buy") console.log(price_buy, name); document.querySelector(`input[name=${name}]`).value = price_buy; } }); </script> Django Model: class Product(models.Model): name = models.CharField(max_length=64) price_buy = models.DecimalField() production = models.FloatField(blank=True, null=True) -
Change representation of Superclass without field depending of Subclass object (__str__)
I am running a django app and have a setup like this: ModelSuper(models.Model): class Meta: abstract = False ModelSub1(ModelA): name = models.CharField(...) def __str__: return self.name ModelSub2(ModelA) name = models.CharField(...) def __str__: return self.name ModelForeign(models.Model): element = models.ForeignKey(ModelA) def __str__: return self.name So ModelForeign has a FK to ModelSuper. What happens now is that when I create an instance of ModelForeign I can choose if it belongs either to ModelSub1 or to ModelSub2. But the string representation is ModelSuper Onject (3) where (3) is the id. Normally I can change this representation by overwriting the __str__ method on the model, but since I do not have any fields on the Supermodel I can't return anything. What I tried: I have already implemented the __str__ method in the Submodels but that does not help. I wanted to make the Super model abstract. But this does not let me point FKs to the Supermodel, so I can't do this. My setup requires this FK I used a generic FK with django's ContentType framework. This is also not an option because it messes completely with my app and is also not recommended from an SQL perspective. Also when I do API-calls I get … -
Page not found at /register using restframework
so i'm building a simple auth system using restframework and i got this error using postman : Page not found at /register i guess i need to provide only urls.py from the app from django.urls import path from .views import RegisterView urlpatterns = [ path('/register',RegisterView.as_view(),name="register") and here is urls from main app from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('/',include('useraccounts.urls')) ] -
Django ORM error: UnicodeDecodeError: 'utf-8' codec can't decode byte
When I use SomeModel.objects.get(id=), I get this exception: UnicodeDecodeError: 'utf-8' codec can't decode byte... As I see that field comment (type TextField) of this object has a german word. But SomeModel.objects.get(id=) works well with english words -
Why use React with Django?
What is the advantage of using Django with React instead of just Django, where you hit the DB and render the information, style it with CSS and HTML? Is it Performance/scalability/maintenance?? I see a lot of React and Django projects but don't understand the necessity of React for a small/medium sized business? I mean, if you want some async tasks you could just use AJAX, right? -
QuerySet has no field_names?
So I'm currently upgrading a Django app from 1.8 to 3.1 and came upon the following error: AttributeError: 'QuerySet' object has no attribute 'field_names' I have tried to find deprecation information on this attribute and checked the QuerySet API for information but couldn't find anything relevant. Has anybody gone through the same? -
How to make full page tabs, that act individually?
Sorry I'm showing a lot of code but I cant convey my meaning well enough. So my first page works perfectly, you type in a URL, information from that product shows up then the user clicks it then the name of the product become the tab name and the url path. I want to make this work with tabs where each time you press a new tab it takes you to the starter page and each tab acts as an individual page. How could I do this using JavaScript. HTML <!DOCTYPE html> <html> <head> <title> </title> </head> <body> <!DOCTYPE html> <html> <head> <title> </title> </head> <body> <!-- Required meta tags --> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport"><!-- Bootstrap CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/homepage/main.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <header> <link href="/static/homepage/main.css" rel="stylesheet" type="text/css"> <div class="tabcontainer" id="tabcon" style="background-color: aquamarine"> <ul id="navigation1"> <li class="tabli" id="button1"><button class="tabs" onclick="window.location.href='#page1'" >tab 1</button></li> <ul id="navigation2"> <li id="tabli"> <button onclick="newTab()" class="addbut" style="text-align: center"> + </button> </li> </ul> </ul> </div> </div> <div id="smallSearch"> </div> <script src="https://cod'e.jquery.com/jquery-3.2.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script> <div class="container"> <script src="//cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js"> </script> <link href="//cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css" rel="stylesheet"> <div class="containFORM" id="containFORM"> <form id="myForm" method="post" name="myForm" onkeydown="return … -
How to change Uniqueconstrain error to a custom one?
here is an example of a model with Uniqueconstrain class Volume(models.Model): id = models.AutoField(primary_key=True) journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal") volume_number = models.CharField('Volume Number', max_length=100) comments = models.TextField('Comments', max_length=4000, blank=True) class Meta: constraints = [ models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint') ] -
Recreate applied migration in Django
I have a situation where on an important environment for my application a migration file was generated with the latest code changes and applied to the database. Since there were several changes on the models the name was auto generated with a timestamp. Unfortunately the file was lost after that and not committed to a version control system. Now I'm pretty sure that using the same version from which this migration file was created I can recreate exactly the same migration file, but it will carry different name (with different timestamp) and will cause Django to fail (since the migration removes a table). In this situation where I know the newly generated file is matching the one that is lost but applied to the DB can I just rename the new file to match the name of the one that was applied - so that Django can recognise the migration as applied? I'm not sure how Django evaluates applied migrations and recognising the files.. Is it only by the name of the file like it is stored in the migration history table? Also is there a better solution from the one I'm thinking about? -
Explicitly fields aren't returned in serializer in django-rest-framework
I'm trying to get a serializer of a model with a field from another model wich are related by a foreing key relation. The desired result should be: "coordinates": [ { "coordinate": "42.0677", "coordinate_type": "shooting_latitude" }, { "coordinate": "-8.0990", "coordinate_type": "shooting_longitude" } ] And the models are: class CoordinatesType(models.Model): coordinate_type = models.CharField(max_length=100, null=False, blank=False) coordinate_description = models.TextField(null=False, blank=False) class Coordinates(models.Model): coordinate_type = models.ForeignKey('hauls.CoordinatesType', null=False, blank=False, on_delete=models.CASCADE) coordinate = models.DecimalField(max_digits=10, decimal_places=4, null=False, blank=False) I can do it whit a nested serializer: class CoordinatesTypeSerializer(serializers.ModelSerializer): class Meta: model = CoordinatesType fields = ['coordinate_type'] class CoordinatesSerializer(serializers.ModelSerializer): coordinate_type = CoordinatesTypeSerializer(read_only=True) class Meta: model = Coordinates fields = ['coordinate', 'coordinate_type', ] In this case, the result of the serializer is: "coordinates": [ { "coordinate": "42.0677", "coordinate_type": { "coordinate_type": "shooting_latitude" } }, { "coordinate": "-8.0990", "coordinate_type": { "coordinate_type": "shooting_longitude" } } ] And then I could override the to_representation() method to avoid the nesting data and get the desired result. But, in this case with only one nested field, I think it could be simpler create an explicit field and I tried: class CoordinatesSerializer(serializers.ModelSerializer): coordinate_type = serializers.CharField(read_only=True, source="coordinatestype.coordinate_type") class Meta: model = Coordinates fields = ['coordinate', 'coordinate_type', ] But looks like the serializer ignore the explicit field … -
Django GraphQL JWT: tokenAuth mutation returns "str object has no attribute decode"
Currently I'm running a basic example of django-graphqljwt from the documentation page. https://django-graphql-jwt.domake.io/en/latest/quickstart.html import graphene import graphql_jwt class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() schema = graphene.Schema(mutation=Mutation) However if I run the tokenAuth mutation it throws me the below error in the GraphiQL interface. Note that if I enter incorrect credentials it throws an "Please enter valid credentials" instead of the below. { "errors": [ { "message": "'str' object has no attribute 'decode'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "tokenAuth" ] } ], "data": { "tokenAuth": null } } -
Django filter JSON field array for multiple indexes lookup with Q model?
Im using Django with Postgres and im having some trouble regarding filtering data into JSON field. --Here is my json object "dimensions": [ { "dimension": "140/200", "price": 163.52 }, { "dimension": "160/230", "price": 214.91 }, { "dimension": "200/290", "price": 338.72 } OR "dimensions": [ { "dimension": "160/230", "price": 214.91 }, { "dimension": "80/150", "price": 70.08 }, { "dimension": "140/200", "price": 163.52 }, { "dimension": "80/200", "price": 93.44 } --Here are my views and what i have tried: if min_price and max_price: queryset = queryset.filter( Q(product_options__options__data__dimensions__price = float(min_price), product_options__options__data__dimensions__contains=[{'price': float(min_price)}]) & Q(product_options__options__data__dimensions__price = float(min_price), product_options__options__data__dimensions__contains=[{'price': float(min_price)}])) -And finally im able to filter them using range filter queryset = queryset.filter(Q(product_options__options__data__dimensions__1__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__2__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__3__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__4__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__5__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)) But here is my question is there any possibility to make this a single query because im hitting db multiple times with all indexes from 0 to n. I have tried with gte and lte but same. I need something like queryset = queryset.filter(Q(product_options__options__data__dimensions__{'Here to filter all indexes'}__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)