Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the field options in a form view
I need to overide the field options in a FormView. However I am not able to figure out in which method or where exactly in the class I need to do it. Currently I have this for the view: views.py class ManageGroupMembersListView(FormView): model =AadGroupmember template_name = 'permissions/group_members.html' success_url = lazy(reverse, str)("manage_groupmembers") form_class = ManageGroupMemberForm __init__(): self.fields['id_aadgroup'] = ['opt1', 'opt2', 'opt3'] -
How to avoid duplicate objects in django pagination when order_by('?')
I am using viewset in rest framework. I am getting same objects in different paginated pages. How can I avoid it. class Viewset(viewsets.ModelViewSet): queryset = Model.objects.all().order_by('?') serializer_class = MySerializer pagination_class = StandardPagination -
After shutting down computer how to reactivate a django server
'm very new to django web development in python and I'm currently following a course on building a simple django website. The problem is, I went to sleep and decided to shut down my computer. After sometime I need to reactivate the website or something because the website just says 'This site can't be reached'. I opened up the code and I'm not sure if I'm suppose to write a certain command in the terminal or something. The terminal is empty when before it was running the website and had stuff there. I do understand that it is going to stop running the website when I shut down my computer because it's my computer hosting it, but I just need to know how to start running it again. So how do I 're-activate' a django website? -
Django Timesince does not show correct value
I want to display "timesince" value for a date in my application. The date is correct but the timesince value is wrong. Screenshot was taken at August 10, 4:39PM. Received Date and Timesince equivalent The first item should show 30 minutes since time is 4:09PM. Here's my HTML code: <tbody> {% if completed_trips %} {% for trip in completed_trips %} <tr> <td>{{ trip.id }}</td> <td>{{ trip.date_depart }}</td> <td>{{ trip.equipment }}</td> {% for k,v in materials.items %} {% if k == trip.material %} <td>{{ v }}</td> {% endif %} {% endfor %} <td>{{ trip.farm }}</td> <td>{{ trip.destination }}</td> <td>{{ trip.load }}</td> <td>{{ trip.date_arrive }}</td> <td>{{ trip.date_arrive | timesince }}</td> </tr> {% endfor %} {% else %} <tr> <td colspan="9" class="text-center">No trips to show.</td> </tr> {% endif %} </tbody> -
Who will review my coding for my web application?
I am a self-taught web application developer. But I don't know that my code is highly clean, maintainable and augmentability. I want to review my code to someone. The development language is python (django). github https://github.com/YuminosukeSato/MovieReview -
select_for_update not working even though it is inside a transaction
I am trying to fetch a customer object from the db. I have writtern a separate service for that. But my problem is that select_for_update is not working when i try to get customer through it but raw orm query works. Error that i am getting django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction. Customer service class CustomerService: @staticmethod def get_customer(select_for_update=False, **params_dict) -> Customer: """ param: customer mobile number return: Customer object raises exception INVALID_CUSTOMER if customer does not exist """ try: customer = Customer.objects if select_for_update: customer = customer.select_for_update() customer = customer.get(**params_dict) return customer except Customer.DoesNotExist: raise ParseException(INVALID_CUSTOMER, errors='INVALID_CUSTOMER') This doesn't work- @transaction.atomic def create(self, request, *args, **kwargs): customer = CustomerService.get_customer({"id": customer_id}, select_for_update=True) but this does @transaction.atomic def create(self, request, *args, **kwargs): try: customer = Customer.objects.select_for_update().get(id=customer_id) except Customer.DoesNotExist: raise ParseException(INVALID_CUSTOMER, errors='INVALID_CUSTOMER') -
Django, default migration giving naive datetime error
After setup a Django project. python manage.py runserver works with no problem. But when I run the command python manage.py migrate and set the defualt migration file. it's starts giving raise ValueError("make_aware expects a naive datetime, got %s" % value) ValueError: make_aware expects a naive datetime, got 2022-08-10 07:39:19.737670+00:00 actually, I am not very sure is this version bug or something. I am using 4.1 but even if I downgrade it to 4.0, still having the same error after the migrate command. By the way it's migrating the defaults. But after migration under the applied column of django_migrations table this date 2022-08-10 07:39:19.737670 not suitable for the make_aware. -
AttributeError: type object 'Post' has no attribute 'objects'
My in y django project, i have a post model for my blog, but i have this error ): "AttributeError: type object 'Post' has no attribute 'objects'". my model my serializer my view -
drf error arise when i tryed to request POST : Got a `TypeError` when calling `Item.objects.create()`
I tried to create Item instance. but everytime i tried to request POST, arise type error like this... what should i do..? please please check my problem ㅠ__ㅠ Got a TypeError when calling Item.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Item.objects.create(). You may need to make the field read-only, or override the ItemSerializer.create() method to handle this correctly. TypeError: Item() got an unexpected keyword argument 'category' models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Category(models.Model): NATIONAL_CHOICES = ( ('outer', '아우터'), ('dress', '원피스'), ('top', '상의'), ('pants', '바지'), ('skirt', '스커트'), ('shoes', '신발'), ('accessory', '악세사리'), ) big_category = models.CharField(max_length=20, choices=NATIONAL_CHOICES) small_category = models.CharField(max_length=20) class Item(models.Model): user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING) description = models.TextField() feature = models.TextField() product_defect = models.TextField() size = models.CharField(max_length=6) wear_count = models.IntegerField() price = models.IntegerField() class Location(models.Model): city = models.CharField(max_length=10) gu = models.CharField(max_length=10) dong = models.CharField(max_length=10) class LocationSet(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='location_sets') location_id = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location_sets') class Photo(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='photo_sets') photo = models.ImageField(upload_to='item_post', blank=True, null=True) class StylePhoto(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='style_photo_sets') user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='style_photo_sets') photo = models.ImageField(upload_to='item_post', blank=True, … -
How to merge admin panels from different Django projects?
I want to merge admin panel from two separate projects into one admin panel. Every have their models and admin panel. Is there any way to implement it using Django admin instruments? It seems I have to write at least one private API (from one of this project) to implement it and than add it to another project admin manually. Is there any way to make it easier than implement private API? I've tried to find any cases like that, but I didn't find any. -
Invalid block tag on line 73: 'ifequal', expected 'empty' or 'endfor'. Error after replay is set
I am trying to set the replay button on my web application in Django, I am using django-messages, and I have set all libraries to the latest version for Django and python. Everything was working fine until I tried to set the replay button. inbox.html {% load static %} {% block content %} {% if user.is_authenticated %} {% load i18n %} {% if message_list %} <section class="sidebar"> <div class="sidebar--inner"> <div class="is-settings--parent"> <div class="sidebar-menu"> <ul> <li class="inboxItem isActive"><a href="#0">Inbox (<span class="numCount"></span>) </a></li> <li class="sentItem"><a href="#0">Sent</a></li> <li class="spamItem"><a href="#0">Spam</a></li> <li class="trashItem"><a href="#0">Trash</a></li> </ul> </div> </div> </div> </section> <section class="view"> <section class="emails is-component"> <div class="emails--inner"> <div> <h1 class="email-type">Inbox</h1> {% for message in message_list %} <div class="inbox"> <div class="email-card"> <div class="is-email--section has-img"> <div class="sender-img" style=""> </div> </div> <div class="is-email--section has-content"> <div class="sender-inner--content"> <p class="sender-name">From: {{ message.sender.username }}</p> <p class="email-sum">Subject: <a href="{{ message.get_absolute_url }}"> {{ message.subject }}</a></p> <p class="email-sum">Time: {{ message.sent_at|date:_("DATETIME_FORMAT") </p> </div> </div> <div class="email-action"> <span> <a href="{% url 'messages_delete' message.id %}"> <img src="https://gmailapp.surge.sh/assets/images/trashcan.png" alt="" class="action-icon trash"> </a> </span> <-- This line: --> {% ifequal message.recipient.pk user.pk %} <span> <a href="{% url 'messages_reply' message.id %}"> <img src="" alt="" class="action-icon"> </a> </span> {% endifequal %} </div> </div> </div> {% endfor %} </div> </div> </section> {% … -
How should I go building login serializer & View which uses DRF for Token Authentication?
This is how my Signup Serializer looks like class AuthUserSerializer(serializers.ModelSerializer): class Meta: model = AuthUser fields = ('first_name', 'last_name', 'email', 'password', 'role') def create(self, data): return AuthUser.objects.create(**data) Here is the view of it: class Signup(CreateAPIView): serializer_class = AuthUserSerializer queryset = AuthUser.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() headers = self.get_success_headers(serializer.data) token, created = Token.objects.get_or_create(user=serializer.instance) return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers) And data is getting inserted in DATA successfully, and token is being generated properly. Now I want to make login endpoint where user will enter his email and password and if true return the token. Kindly assist me, on how should I go building this login serializer & view. -
Django - fresh database and no such table
I'm using my complex jobs app in production and it works fine, with sqlite database. I'm trying to create new database from scratch and I cannot do that nor using migrations nor trying to make them once again: When I'm trying to reuse my migrations: rm db.sqlite3 python manage.py migrate Traceback (most recent call last): File "/backend/server/manage.py", line 22, in <module> main() File "/backend/server/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/backend/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/backend/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/backend/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/backend/env/lib/python3.10/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/backend/env/lib/python3.10/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/backend/env/lib/python3.10/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/backend/env/lib/python3.10/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/backend/server/jobs/admin.py", line 57, in <module> class TagCategoryDefaultImportanceAdmin(admin.TabularInline): File "/backend/server/jobs/admin.py", line 59, in TagCategoryDefaultImportanceAdmin extra = len(Role.objects.all()) File "/backend/env/lib/python3.10/site-packages/django/db/models/query.py", line 269, in __len__ self._fetch_all() File "/backend/env/lib/python3.10/site-packages/django/db/models/query.py", … -
How should the data of a collection API be?
I'm coding a BlogApi application with Django and Django Rest Framework. So I have a post model that contains the data that a post of the blog should have and When I was making some serializers and views for the endpoints, I faced a question: Because the data of a single post is long, so should I make the posts data shorter in the list (or collection) endpoints or keep them how they are? In general I want to know that should the data of an element in collection APIs be brief? -
Establish MySQL connection on Elastic Beanstalk for django application
I have django app running on Elastic Beanstalk but facing difficulty in database connectivity. For some reasons the database is hosted on EC2 instance and currently can not move it to the RDS, So my concern is can we connect the database hosted on some EC2 instance to the Elastic Beanstalk application. And is it possible to connect database hosted on EC2 which is not in the same region as of Elastic Beanstalk. -
raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword
Hey guys I can't populate my database with dummy data.The scale of the error I got is: (raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'Topic' into field. Choi ces are: accessrecord, date, id, name, topic_name, topic_name_id, url Below is the codes for generating dummy data using Faker import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() # faker pop script import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games', 'Music'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # iget the topic for the entry top = add_topic() # create fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create the new Webpage entry webpg = Webpage.objects.get_or_create(Topic=top,url=fake_url,name=fake_name)[0] # create fake access record for Webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__=='__main__': print("populating script") populate(20) print("populating complete!") -
Passing Stripe Checkout ID to Django URL
The success page, which contains the download link to download a file after completing the purchase should be accessible only after having done the payment. The idea is to pass the {CHECKOUT_SESSION_ID} to the success url. Only if the correct url .../success/?session_id={CHECKOUT_SESSION_ID} is inserted the page is accessible. How can I pass the {CHECKOUT_SESSION_ID} to my url? Here is my views.py file: def success(request): return render(request, 'checkout/success.html') def index(request): # sendMail() try: checkout_session = stripe.checkout.Session.create( line_items = [ { 'price': 'price_1LUvcWKKYbcIekP0ZtUlCmAI', 'quantity': 1, }, ], mode = 'payment', success_url = 'http://127.0.0.1:8000/checkout/success' + '/?session_id={CHECKOUT_SESSION_ID}', cancel_url = 'http://127.0.0.1:8000/create/', ) except Exception as e: return str(e) return redirect(checkout_session.url, code=303) And this is my urls.py file: from django.urls import path from checkout.views import * app_name = 'checkout' urlpatterns = [ path('', index, name='index'), path('success/', success, name='success'), ] This is the html file which I copied from stripe. It is called by a "Pay Now" button. <!DOCTYPE html> <html> <head> <title>Buy cool new product</title> <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script> <script src="https://js.stripe.com/v3/"></script> </head> <body> <section> <div class="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div class="description"> <h3>Stubborn Attachments</h3> <h5>$20.00</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit" id="checkout-button">Checkout</button> </form> </section> </body> </html> -
Django form Data
Please I gotta a model I created with three fields input1,input2,total. So I generated a model form so that if I input the values of input 1 and input2 it will automatically multiply the the inputted values. Then on calling the save method it will save the inputted values and computed value to the database -
Response 403 Error When Trying to Login To Website Using Python Requests WRONG
I am trying to pull data from this website, but I am getting a Response 403 error when running session.post. Please see code below for reference. Any help would be appreciated. URL = 'https://www.pin-up.casino/' LOGIN_ROUTE = 'ajax/players/authorization' HEADERS = { 'HOST' : 'www.pin-up.casino', 'Accept-Encoding' : 'gzip, deflate, br', 'Content-Length':'1417', 'Origin':URL, 'Connection':'keep-alive', 'Referer':URL + 'slots', 'Cookie':'pinup-authToken=cboahm274uuuq6tebgv0; pinup-language=EN; _ga_73G7FP5X9S=GS1.1.1660101630.6.1.1660104282.50; _ga=GA1.2.230685168.1659939034; pinup-login1=; _gid=GA1.2.1822135906.1659939039; pinup-quizRewrite=1; __cf_bm=sJgdmyIQSs7.tAinAP8KeX53z7anDxilmvGRT23F1ow-1660104275-0-AWW0o9EH6zmL0aeyroPLM/4TMClgoUjMFabEaeDtao2IpLiOga8gUM46KHSXbPsuSMlfdF1kBARcPJm2B4eD4ZbM5YnenKfmfF7PQz/Sp+R395M2hgt47OL4A+BWBIapFw==; pinup-prevPage=/slots; pinup-hash1=', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode' :'no-cors', 'Sec-Fetch-Site': 'e-origin', 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0', 'TE': 'trailers', } login_payload = { 'email':'gamail', 'registDis' : "false", 'rulesEnable' : "true", 'password' :"password", 'timezone' :"5.5", 'screenSize' : "1706x899+(1708x960)", 'doNotTrack': "unspecified", 'page': "/slots", 'token' : "03ANYolquUWuPrFGd3q02tVCfla2iI9aTVMWEXNmUvqefYbRmB9rJYWZJzzHJIbFoiyjhgHmqmTGfM3ueqMmutoUIGdpKm26-ue1wSTowSVdFWkwmKQy59DhQ0po_7iiEC7VVBl48zG_M8q77dSXZ3FBkM6PryNozemsiH69Cga7OCj0vRqA3iDeZcSPU1g89Eqom7w2jiUgK0nUeJ9XO5ID1isfA4i1Z2LCM3Laf9dCSjc3V_s9OeJq28F-c__2kPZBJ0UzH37LEziVqjK2mhT32WD9q8rnYYYruFyoNDO4G0VoFMI54GFz-Yg-QlMzyU9j9jM-JYHaUcNAP580wBfV6m6OQSn1lmboxJGVTp-wSUMYVoO-taQ4sVSW-nqVUrYzw5x4WGLX6QGxA2ZQH8gElGcPObJFWAguGwMnFQjeEF0jFKLMAys8Ww4ZGvPtGiSNpvpVGRNbLhaec9JWGUy0wWwhlkNpTSOz__cByMgXvB5FS24e7E3B_WIc2ZD…e5hk0dw6cM8k828VBQxXd113qRNDEIQQcm_uvivdZREDNyNG2goDG8ZzvmhZxuS9aZ11ngRfJis74CbZXuH3uyRe5mr6ZRE8INvE2PKcT1XY5kPp9N7wqK13_ufkf8DsYQYbQouwQ4SbgWE3kEgLQmnzbutwAkdawIbTtI_GBzYhlURBkRpYtpLSPEkM2QN9tQxQ-W_PFl9i0woYMp4kg_mcxXSqKCzOIpHAtX9poTN2eezwxrDaOe3HyqFt_3aHQL8d1gHcKLcsi0axvJC4WN_xD8-Y4MyyaDiv1KZrSSSvQoqJD6WGKdiyeR7Alzhsm91WfW_m7sQ_WKfKNAgQxCrO9988mDQOZsWfK795r_tigq3msl88lmuiPZrDn5012QKrCsXQ3ZwHpfNWzOknO_G_HAZdW6VxdcMnj_xgP1lM-wStDqqJC4cozjErGL7vgvY_5kaYUwPF98Jzto_OHPDd89X9zu9qibqU2cgXNZcvy3NuCoRsGupvTkdC9Q", } s = requests.session() p = s.get(URL, headers=HEADERS) print(URL + LOGIN_ROUTE) login_req = s.post(URL + LOGIN_ROUTE, headers = HEADERS, data = login_payload) print(login_req.status_code)``` 403 returns what is wrong -
Why can't I change primary key in postgresql?
When I migrate the Django project model, I get the error: `there is no unique constraint matching given keys for referenced table "accounts_account"` my models is: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='ایمیل', max_length=60, unique=True) username = models.CharField(verbose_name='نام کاربری', max_length=30, unique=True) phone_number = models.CharField(max_length=11, blank=True, null=True, default="") profile_image = models.ImageField(default="profile.jpg", upload_to='profile/images') # media/blog/images/img1.jpg ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True in pgAdmin the Primary Key is not changeable primary Key in pgadmin4 -
Aggregated query django manytomany field
I'm trying to make chat application where for the screen where list of messages of users are visible like the Home Screen of WhatsApp or Telegram. For which I might need Chatroom ID, Name of sender. (mainly)' I have my models set like this models.py class ChatRoom(models.Model): name = models.CharField(max_length=50) last_message = models.CharField(max_length=1024, null=True) last_sent_user = models.ForeignKey(User, on_delete=models.PROTECT, null=True) def __str__(self): return self.name class Messages(models.Model): room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) From where I'm querying in ChatRoomParticipants to see how many ChatRoom(s) is the user connected to. In ChatRoomParticipants user has relation with users who are connected to the that particular room. To show name and last message and the fetch ID of the ChatRoom on the mobile application I've written the following query. chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values('id','room__id', 'room__name', 'room__last_message', 'room__last_sent_user', 'user__chatroom_users__user__username')) But this gives me repeated an unexpected output which I'm not able to make any sense of Below I'm showing which 2 users are related to which room Database values room - f4253fbd-90d1-471f-b541-80813b51d610-99ea24b1-2b8c-4006-8970-2b4f25ea0f40 relations to - udaykhalsa9 and udaykhalsa7 room - f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de relations to - udaykhalsa9 and … -
Set values in summernote text editor using javascript
I want to set values in summer note text editor using JavaScript/jQuery. I have tried this both but nothing works. document.getElementById('summernote').innerHTML = data.message; $('#summernote').summernote('code', data.message); Can anyone help me how I can add values in summer note using JavaScript/jQuery. -
How to query and update Django model JsonField?
Im working on a project where using Django JSONField to store json data for the instance. When i try to query the object as per official documentation, its not working as expected. Im uanble to query the object to update the key value inside the jsonfield. Please find the below details for your reference and help to to achelve the desired result. Model class PosOrder(models.Model): store = models.ForeignKey('store.Store', on_delete=models.CASCADE, null=True) order_number = models.CharField(max_length=30, null=True) customer_phone = models.CharField(max_length=100, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) order_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_discount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_tax = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) coupon = models.ForeignKey('shoppingcoupon.ShoppingCoupon', on_delete=models.PROTECT, null=True, blank=True) order_grand_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) payment_method = models.CharField(max_length=100, null=True, blank=True, choices=( ('cash', 'Cash'), ('card', 'Card'), ('online', 'Online'))) order_status = models.CharField(max_length=100, null=True, blank=True, choices=order_status) payment_status = models.CharField(max_length=100, null=True, blank=True, choices=payment_status) payment_id = models.CharField(max_length=100, null=True, blank=True) complete = models.BooleanField(default=False) order_data = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('hrms.Employee', on_delete=models.CASCADE, null=True, blank=True) Jsonfield is like {"id": 408, "store": {"id": 1, "name": "Salt Lake"}, "order_number": "POS408", "customer_phone": "9877454577", "order_status": "processed", "payment_status": null , "payment_method": "cash", "created_at": "2022-08-09T11:38:37.207775+05:30", "created_by": {"id": 5, "code": "RMS003"}, "get_order_total": 39206, "get_order_tota l_discount_amount": 2232, "get_order_total_without_tax": 32730, "get_order_total_tax": 6476, "ordered_items": [{"id": 41, "item": {"id": 3, "product": {"id": 3, … -
How can translate the the whole screen language of application by only clicking single click on lang selection using python for flutter application
I have a Flutter app with 100 language choice on login page. I want when user choose one language suppose "Hindi" language the language of whole application screen should change. How can I change the language of whole application. -
How to add value in blank query set
I am running last 6 months of report which contains month, visits, fees and other fees as fields. When a month not having any visits its shows empty query set. how to pass a value to empty query set. I am getting result as below: <QuerySet [{'month': 7, 'visits': 19, 'fees1': Decimal('6380'), 'other_fees': Decimal('1730')}]> <QuerySet [{'month': 6, 'visits': 6, 'fees1': Decimal('3201'), 'other_fees': Decimal('851')}]> <QuerySet [{'month': 5, 'visits': 6, 'fees1': Decimal('900'), 'other_fees': Decimal('1685')}]> <QuerySet []> <QuerySet [{'month': 3, 'visits': 2, 'fees1': Decimal('455'), 'other_fees': Decimal('605')}]> <QuerySet [{'month': 2, 'visits': 2, 'fees1': Decimal('430'), 'other_fees': Decimal('504')}]> month 4 is not having any visit and fees since, the query set being empty. instead of empty. I want to set value of 0 for the fields.