Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can't set up custom django User model
I want to set up my own django User model because I need additional fields, but I am getting the error. I read a lot of posts but I didn't find solution. What is the problem? Code models.py: class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True), email = models.EmailField(max_length=50, unique=True), city = models.TextField(max_length=30, blank=True), friends = models.ManyToManyField("Account", blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username'] Code admin.py admin.site.register(User) Code admin settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig' ] AUTH_USER_MODEL = 'users.User' Error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 608, in get_field return self.fields_map[field_name] KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any( File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named 'username' -
skip an iteration of the for loop in python
I need a hand, I don't understand how to fix it. Look at the photo to better understand my speech, where the new field is populated the value of new is subtracted from the total and I don't want it to be subtracted immediately but the next round. How can I do? def UserAndamentoListView(request): giorni = [] mese = [] new_user = [] tot_user = [] tot = User.objects.all().count() for day in range(5): giorni.append(datetime.datetime.now() - datetime.timedelta(days=day)) new = User.objects.filter(date_joined__contains = giorni[day].date()) new_user.append(new) tot -= new.count() tot_user.append(tot) context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user} return render(request, 'andamento.html', context) -
Can't see the address when nginx processes the port and outputs 502 Bad Gateway
I encountered a problem when learning nginx. I have 2 servers on 2 different ports. I want a page with information stored on port 8000 to be returned when accessing "http://localhost/api/v1/clients/". Now I get error 502 Bad Gateway. В консоли: connect() failed (111: Connection refused) while connecting to upstream, client: 111.11.0.1, server: localhost, request: "GET /api/v1/clients/ HTTP/1.1", upstream: "http://111.11.0.2:80/api/v1/clients/", host: "localhost" If I go to the address: "http://localhost:8000/api/v1/clients/", everything is fine. What's my mistake? nginx: upstream backend { server 127.0.0.1:8000; server 127.0.0.1:3000; } server { listen 80; server_name localhost; location /api/v1/clients/ { proxy_pass http://backend_client/api/v1/clients/; } } docker: services: backend_client: build: ./Client volumes: - ./Client/:/app ports: - "8000:8000" restart: always command: "gunicorn --bind=0.0.0.0:8000 django_app.wsgi" nginx: image: nginx:1.17 container_name: ngx ports: - "80:80" volumes: - ./nginx:/etc/nginx/conf.d depends_on: - backend_client -
How to validate and return access and refresh tokens after user.save()
I'm verifying the user OTP to change password and after change password I'm unable to create access and refresh token using JWT , Normally when user get log in I use following method MyTokenObtainPairView which return both access and refresh token with all other stuff to UserSerializerWithToken. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I coppied similar appraoch to return UserSerializerWithToken after set_password and user.save() UserSerializerWithToken is class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = CustomUser fields = ['id', 'isAdmin', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) and the problematic function is @api_view(['PUT']) def reset_password(request): data = request.data email = data['email'] otp_to_verify = data['otp'] new_password = data['password'] user = CustomUser.objects.get(email=email) serializer = UserSerializerWithToken(user, many=False) if CustomUser.objects.filter(email=email).exists(): otp_to_verify == user.otp if new_password != '': user.set_password(new_password) user.save() # here password gets changed return Response(serializer.data) # else: message = { 'detail': 'Password cant be empty'} return Response(message, status=status.HTTP_400_BAD_REQUEST) else: message = { 'detail': 'Something went wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) I receive the toke but not getting access and refresh toke to use it to login next time. I'm assuming user.save() dosnt … -
how to run a loop or any other method for the below mentioned django project
Model.py: ``` from django.db import models class ddlname(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField() endate=models.DateField() def __str__(self): return self.name``` views.py: ``` from django.shortcuts import render, HttpResponse, redirect from .forms import nameform from .models import ddlname def dashboard(request): if request.method=='GET': form=nameform() return render(request,'home.html',{'form':form}) else: form=nameform(request.POST) if form.is_valid(): form.save() return redirect('/homedetails') def homedetails(request): context={'homedetails':ddlname.objects.all().order_by('stdate','sttime')} return render(request,'homedetails.html',context)``` forms.py: ``` from dataclasses import fields from django import forms from .models import ddlname class nameform(forms.ModelForm): class Meta: model=ddlname fields='__all__'``` I am getting the output from stdate to endate when i input the details in the template, but i am facing difficulty in getting same data for multiple dates. for example(my stdate input is 2022-2-11 and endate input is 2022-2-15, along with name(Test), when i input this details I get a single data as (test,2022-2-11,2022-2-15), where I need my output as (test,2022-2-11,2022-2-11 | test,2022-2-12,2022-2-12 | test,2022-2-13,2022-2-13....finally as per endate test,2022-2-15,2022-2-15). request some one to help me on this. -
NoReverseMatch Django using pk
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P[0-9]+)/\Z'] 9 <p>Location: {{school_detail.location}} </p> 10 <h3>Students:</h3> 11 {% for student in school_detail.students.all %} 12 <p>{{student.name}} who is {{student.age}} years old</p> 13 {% endfor %} 14 15 16 </div> 17 18 <div class="container"> 19 <p><a class='btn btn-warning' href="{% url 'basic_app:update' pk=school_details.pk %}">Update</a></p> 20 21 </div> 22 {% endblock %} -
Run bash text scripts after docker run
I have django application, a test.sh script and dockerfile. I have built dockerfile and run it by docker run -d -p 80:80 IMAGE_NAME. Dockerfile FROM python:3.8-slim-buster RUN apt-get install -y ca-certificates wget RUN apt install gunicorn3 -y COPY ./ ./ RUN pip3 install -r requirements.txt RUN chmod +x ./test.sh CMD ["sh", "test.sh"] ENTRYPOINT ["gunicorn --bind 0.0.0.0:80 core.wsgi:application"] test.sh #!/bin/bash python manage.py test Gunicorn is running successfully. Now I want to run test.sh script with docker run -it --rm IMAGE_NAME test.sh. When i run that command the server runs but never executes test.sh but gunicorn server runs. How can I run test.sh from docker run -it --rm IMAGE_NAME test.sh? -
How to render Page attributes in a model when displayed in StreamField?
I have the following StructBlock and Page model: class PostGrid(blocks.StructBlock): title = blocks.CharBlock() post_1 = blocks.PageChooserBlock() post_2 = blocks.PageChooserBlock() class Meta: template = 'post-grid.html' class BlogIndex(Page): body = StreamField([('POSTS', PostGrid()),]) class Meta: template = 'base.html' class PostPage(Page): hero_title = models.CharField(max_length=255) I want to render the attributes of post_1 and post_2 in the body StreamField: base.html: {% for block in page.body %} {% include_block block %} {% endfor %} post-grid.html: {{ value.post_1.url }} {{ value.post_1.hero_title }} value.post_1.url renders the URL fine. However, value.post_1.hero_title is blank. How do I render the Page attributes? -
Modern best approach to using Django ORM with async?
The world of async Django is changing rapidly, and it's hard to tell what is current and what is dated. So, what is the current best approach to using the Django ORM (or, possibly, another ORM) for the best/smoothest async capability? What do people use successfully today? Lots of references out there, including: https://forum.djangoproject.com/t/asynchronous-orm/5925/70 https://channels.readthedocs.io/en/latest/topics/databases.html -
Adding id to url route in Async testing with Django
I've built a simple chatroom and now I want to code a test to verify if Its connecting. Following the tutorial in Channels docs i come up with the following test: class ViewTestCase(TestCase): @classmethod def setUp(self): user_moderator = User.objects.create_superuser(first_name='tester', username='test1', password='123', email='testuser@gmail.com') user_player = User.objects.create_user(first_name='player', username='player1', password='1234', email='testplayer@gmail.com') pack1 = Pack.objects.create(deckStyle='Fibonacci',deck=['1','2','3']) self.room = PokerRoom.objects.create(status='Pending',name='planning',styleCards='Fibonacci', user=User.objects.get(username='test1'), deck=Pack.objects.get(deckStyle='Fibonacci'),index=1) user_player = ParticipatingUser.objects.create(name='player',idRoom=PokerRoom.objects.get(name='planning'), status='Pending') self.story = Story.objects.create(storyName='testplanning', idRoom=PokerRoom.objects.get(name='planning'), status='Pending') async def test_consumer(self): application = URLRouter([ url(r'ws/chat/(?P<room_name>[A-Za-z0-9_-]+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi()), ]) communicator = WebsocketCommunicator(application,"/ws/chat/room_id/participant/participant_id)/") connected, subprotocol = await communicator.connect() assert connected await communicator.disconnect() My problem is that I need to substitute room_id and participant_id inside my WebsocketCommunicator. participant_id is just an commom id and my room_id is a UUIDField. I've been using the following method to extract these ids in my others tests: def test_something(self): room_id = PokerRoom.objects.get(name='planning').id user_id = User.objects.get(username='tester').id ... But if I use the same method inside async def like this: async def test_something(self): room_id = PokerRoom.objects.get(name='planning').id user_id = User.objects.get(username='tester').id ... I get this error django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How can I solve this? -
Django How to Look up querydict in template?
when i look inside querydict it with {{get_copy}} it shows <QueryDict: {'grub_id__in': ['Yelek', 'Tunik', 'Tulum', 'Tshirt']}> as i know that how to look up querydict {%for key,val in get_copy.items%} {{key}}{{val}} {%endfor%} but it shows only one of val value output: grub_id__in Tshirt -
Django relationships between child and parent model
I am busy with a project where I have two models and I'm not sure how to do as I am fairly new to programming. what I would like to do is have a template that renders all the instances of first model and then on the same template I want to have all the sales associated with each of those instances as well as the instances with different states(for example if an instance of first model is linked to 2 sales that has a state of "Confirmed" it should say 2 next to that instance name.) class QAAgent(models.Model): user=models.OneToOneField(User,on_delete=models.SET_NULL,null=True) Qa_name = models.CharField(max_length=15) def __str__(self): return self.user.username States = (('Pending',"Pending"),("Confirmed","Confirmed"),("Requested","Requested),("Cancelled","Cancelled"),("Not interested","Not interested")) class Sale(models.Model): QA = models.ForeignKey(QAAgent,on_delete=models.SET_NULL,blank=True, null=True,related_name="sale") State = models.CharField(choices=States,default="Pending",max_length=15) Date_created = models.DateTimeField(auto_now_add=True) Date_edited = models.DateTimeField(auto_now=True) def__str__(self): return self.client_name + " " + self.client_surname -
Limiting instances in database Django
How can i limit the amount of instances in database based on Entity? So i want to only have 5 photos at most attached to an Entity. Also I want to limit a photo to be max 5mb. Do you have any idea how to do it? class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False) image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) -
how to Make an LMS using django?
hi I want to learn about making fast and responsible LMS using Django. is there any course for teaching this? and what can I do to make the website page fast and easy to use and secure just like Udemy? -
Access data across schemas in multi-tenant SaaS system using ORM
In our multi-tenant system (using Postgresql), we want to allow different tenants to "associate" with each other, and share some data. So if Tenant A is associated with Tenant B, when showing the shared data, our queries will need to get data from schema A AND schema B. I've found examples that show how to do so with straight Postgresql code; something like this: select * from S1.table1 UNION ALL select * from S2.table1 ...though ours would be much more complicated than that. But I've not found anything that explains how to do it with Django's ORM. In other words, how would I do the above with the query syntax we actually use in our site: queryset = MyTable.objects.filter(client_id__in=clients, status=Status.ACTIVE) -
Data from django database isnt visible
Data from the database is visible except one. This is the HTML file where the exchange name is not visible. I want the exchange name to be visible but it is not. Rest are visible. {% for balance in balances|dictsortreversed:"amount_fiat" %} <tr class="spacer"> <td class="cell"><div class="btn btncur round">{{ balance.currency }}</div></td> <td >{{ balance.amount|floatformat:-8 }}</td> <td >{{ balance.exchange_name }}</td> <td> {{ balance.amount_fiat|floatformat:-8 }} ({{ balance.amount_fiat_pct|floatformat:-2 }}%) </td> </tr> {% endfor %} Database where exchange_name lies Relevant files: models.py class ManualInput(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) currency = models.CharField(max_length=10, default='BTC') amount = models.FloatField(default=None, blank=True, null=True) exchange_name = models.CharField(max_length=30) def __str__(self): return "%s %s %s %s %s" % (self.user.username, self.timestamp, self.currency, self.amount, self.exchange_name) forms.py class ManualInputForm(forms.ModelForm): currency = forms.ModelChoiceField( queryset=models.Currency.objects.all(), empty_label=None) exchange_name = forms.ModelChoiceField( queryset=models.ManualExchange.objects.all(), empty_label=None) class Meta: model = models.ManualInput fields = ('currency', 'amount', 'exchange_name',) Please tell me where is the error -
How to create custom paginator in django
I'm trying to use django built-in paginator but it's not working cuz I'm not using database storage object I'm creating a website with other api... heres my code: def index(request): response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json") data = response.json() p = Paginator(data, 3) pn = request.GET.get('page') print(pn, p, data) page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj } return render(request, 'index.html', context) do i need to create custom paginator if so how should i? or is there solution? -
Django how to create an clone database?
postgresql is my primary data base. If any object create in my original database then I want it will also keep an duplicate object in my secondary database. I read Django documentation for create an clone database but didn't work. here is my code: #replicarouter.py class PrimaryReplicaRouter: def db_for_read(self, model, **hints): """ Reads go to a randomly-chosen replica. """ return 'replica_database' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_set = {'default', 'replica_database'} if obj1._state.db in db_set: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ All non-auth models end up in this pool. """ return True settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '9l2ENsuudW0Kfarhyn', 'USER': 'postgres', 'PASSWORD': 'tusar', 'HOST': 'localhost', 'PORT':5432, }, 'replica_database': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'farhyn_website', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } DATABASE_ROUTERS = ['my_path.replicarouter.PrimaryReplicaRouter'] -
Django deployment on heroku
I have successfully deployed my Django project on Heroku but when I try to load the URL, it's showing a 505 error. I have checked my settings and everything seems to be intact. Please I need an urgent help -
Django 4.0 shows path not found even after configuring all urls and views properly
So my django app looks like this -assaydash --dashboard (app) --members (app) --djangobackend (django project directory) --static --manage.py djangobackend/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard.apps.DashboardConfig', 'members.apps.MembersConfig', ] djangobackend/urls.py urlpatterns = [ path('admin/', admin.site.urls, name='admin'), path('', include('dashboard.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] members/urls.py urlpatterns = [ path('login_user', views.login_user, name="login"), path('logout_user', views.logout_user, name='logout'), ] members/views.py def login_user(request): if request.method == "POST": ... else: messages.success(request, ("There Was An Error Logging In, Try Again...")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) def logout_user(request): logout(request) messages.success(request, ("You Were Logged Out!")) return redirect('home') index.html <a href="{% url 'login' %}" > <span class="d-sm-inline d-none">Sign In</span> </a> On the index page when i click on the a tag it shows me a debug page with path not found. Even though the url exists and i have included it in my main urls.py and i have added the app in the settings.py as well. please help and let me know what is wrong here. Notice that the url for name login was detected by the template but the path wasn't found. Also the other urls on the debug page are from my dashboard app which works fine -
Unable to set_password using POST request
I'm trying to make a function which can reset user password of OTP matached to the stored value in user model. I'm able to make a successful post request and JSON response I'm getting { "detail": "Password have been changed" } But problem is password in actual dosent change but remains the older one. Can anybody identify what is the problem in my function. My API view is : @api_view(['POST']) def reset_password(request): data = request.data email = data['email'] otp_to_verify = data['otp'] new_password = data['password'] user = User.objects.get(email=email) if User.objects.filter(email=email).exists(): otp_to_verify == user.otp #user model has a field name otp if new_password != '': user.set_password(make_password(data['password'])) user.save() message = { 'detail': 'Password have been changed'} return Response(message, status=status.HTTP_200_OK) else: message = { 'detail': 'Something wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) else: message = { 'detail': 'Something went wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) So I'm not sure what might be the problem as it's passing silently without giving any errors but in the end password does not change. -
elasticsearch.exceptions.SerializationError + Django
Am embedding elastic search in my application, though when I run it I get this error : raise TypeError("Unable to serialize %r (type: %s)" % (data, type(data))) TypeError: Unable to serialize <QuerySet [<AccountTypes: MENTOR>]> (type: <class 'django.db.models.query.QuerySet'>) elasticsearch.exceptions.SerializationError: ({'owner': {'id': 2, 'email': 'huxy@gmail.com', 'username': 'huxy', 'auth_provider': 'email', 'account_types': <QuerySet [<AccountTypes: MENTOR>]>, 'profile': <Profile: None Idris>, 'uuid': UUID('d4a5cae3-44ad-49c0-bf89-cc5f4d993667'), 'status': 'PENDING'}, 'tags': [], 'comments': [], 'grade_level': {}, 'title': 'Math is fun', 'body': 'Math is nice, now I like it so much, this is awesom', 'image': '', 'status': 'DRAFT'}, TypeError("Unable to serialize <QuerySet [<AccountTypes: MENTOR>]> (type: <class 'django.db.models.query.QuerySet'>)")) What could be the one thing that am missing, below is my code snippets. This is my model for user : class User(MainProcess, django_models.AbstractBaseUser, TimeStampedModel, django_models.PermissionsMixin): """ User model for the user creation """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) email = models.EmailField(_('Email'), db_index=True, unique=True) is_verified = models.BooleanField(_('Is verified'), default=False) is_staff = models.BooleanField(_('Is staff'), default=True) is_active = models.BooleanField(_('Is Active'), default=True) username = models.CharField(_('Username'), max_length=255, blank=True, null=True) account_types = models.ManyToManyField(AccountTypes, related_name='account_types') auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) status = models.CharField( choices=UserProcess.states, default=PENDING, max_length=100, blank=True) objects = UserManager() USERNAME_FIELD = 'email' class Meta: verbose_name = 'User' verbose_name_plural = 'Users' Then this is a … -
Django ForeignKey replace dropdown with Popup
A very stupid question, but I just could not figure out how to it simple. In my model (says Measurements) I have a ForeignKey to link the device that we want to add Measurements (device_link = models.ForeignKey(Device, null=True, blank=True,on_delete=models.PROTECT)) I made a Form to create a new Measurements and globally it works well and straightforward. But to choose the Device, Django use a select field via Dropdown menu. So if we have a lot of devices it could be very difficult to choose the desired device. So, I'd like to replace dropdown select menu with a link that open popup window with a list of devices. User choose the device, click and then get back to the form inserting selected device. Sounds simple, but I could not find how to do it in Django. What I have tried already : django-addanother It works very well and do almost that I want... but not exactly, it allow to Add new Device instead of choose. django-autocomplete-light Seems to be very close to that I want, but I could not find any popup example. django-select2 I could not understand if it could do that I want. I tried to make a little test … -
ERROR: RuntimeError - input(): lost sys.stderr
i finished my e commerce project in Django and i want to deploy it in AWS Elastic Beanstalk and after i go some steps i faced this error "ERROR: RuntimeError - input(): lost sys.stderr" while initialize EB CLI repository with the eb init in the foolowing command "eb init -p python-3.7" any one who can help me please? -
'>' not supported between instances of 'dict' and 'dict' in Django 3.0
I am using Django 3.0 and Python 3.7 here is my views.py @login_required def updated_other_order_status(request, pk): s1 = [] purchase_item_quantity = OtherOrderItem.objects.filter(other_order_id=pk) data = set() a = [x.id for x in purchase_item_quantity if x.id not in data and not data.add(x.id)] stock_quantity = StockMovements.objects.filter(other_order_id=pk) data1 = set() b = [x.other_order_item.id for x in stock_quantity if x.other_order_item.id not in data1 and not data1.add(x.other_order_item.id)] if data == data1: for j in data1: stock_quantity = StockMovements.objects.filter(other_order_id=pk, other_order_item_id=j).aggregate(Sum('quantity')) purchase_item_quantity = OtherOrderItem.objects.filter( other_order_id=pk, id=j).aggregate(Sum('quantity')) if stock_quantity > purchase_item_quantity: OtherOrder.objects.filter(id=pk).update(flag=1) if stock_quantity >= purchase_item_quantity: s1.append('true') else: s1.append('false') if 'false' in s1: OtherOrder.objects.filter(id=pk).update(status=3) else: OtherOrder.objects.filter(id=pk).update(status=2) else: pass return redirect(reverse('get_other_orders_list_data')) here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/stock/views.py", line 5254, in updated_other_order_status if stock_quantity > purchase_item_quantity: TypeError: '>' not supported between instances of 'dict' and 'dict' How could i solve this issue " TypeError: '>' not supported between instances of 'dict' and 'dict' "