Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to share memory using gunicorn+uvicorn workers or Daphne+supervisor
I have a Django web application that uses Daphne web server. I have a problem when running multiple instances of app using supervisor (that corresponds to running app with multiple uvicorn workers using gunicorn). I tried to solve it by sharing memory using Redis DB to save user instances so that every worker can access logged in users but then I came across the problem. There is threading inside of User class and I can't pickle _thread.lock object so I can't use Redis. If I separate threading from my User class, I don't profit from it at all because then worker has to do same job again, that is, make a thread, when I send request. Is there a workaround to this problem? I.e. using internal shared memory or something like that? -
Validating several objects at once, before saving
Is it possible to sum values in fields of several objects? class MyModel(model.Models): name = models.Charfield() amount = models.IntegerField() Model Object 1 Object 2 Object 3 Object 4 Object 5 Here i want the sum of "amount" in all the objects to use in my validation. If the total "amount" is correct, i want to save all objects. How do i do this? -
Persian URL in Cpanel Django
I have the url http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/ in my development project and it's is working fine till i upload it to cpanel which returns Page not found (404) here is my urls.py: from django.urls import path , re_path from . import views as v urlpatterns = [ path('', v.index.as_view(), name="ShopView"), path('seach/' , v.SearchResultsView.as_view() , name="search_results"), re_path(r'c/(?P<categoriese>[-\w]+)/' , v.categoryView , name="ProShopView2"), re_path(r'(?P<namecate>[-\w]+)/p/(?P<namepro>[-\w]+)/', v.ProductDetailsView , name="productview"), path('products/<str:proname>/comment/' , v.commentView , name="commentviewshop"), ] first re_path is for category which the url is http://127.0.0.1:8000/shop/c/جکوزی-آپارتمانی/ second re_path is for category and product http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/ here is my category model: class categories(models.Model): name = models.CharField(max_length=50, null=True,blank=True,unique=True) url_name = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True) image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path , null=True , blank=True) def __str__(self): return self.name **here is my productmodel: ** *deleted some of the unnecessary fields. class productmodel(models.Model): Seller = models.ForeignKey(User , on_delete=models.CASCADE , null=True , blank=True) category = models.ForeignKey(categories ,blank=True, null=True, on_delete=models.CASCADE , related_name="categories_main") ProductName = models.CharField(max_length=60) slug = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True) ProductBody = models.TextField(max_length=800) image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path , null=True , blank=True) def __str__(self): # return f'ProuctName:{self.ProductName} ProductAuthor:{self.author} ProductId:{self.id}' return self.ProductName def getsnippet(self): return self.ProductBody[0:30] **here is my category views: ** def categoryView(req , categoriese): if categories.objects.filter(url_name … -
Recursive "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext" development server log
I am working on a Django project and I implemented custom login and logout views for authentication. I am getting these weird development server logs below immediately after I open my site at 127.0.0.1:8000. [04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/favicon.ico HTTP/1.1" 302 0 [04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/favicon.ico HTTP/1.1" 302 0 [04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/login/%25252525252525253Fnext%25252525252525253D/favicon.ico HTTP/1.1" 302 0 Here are my two relevant url.py files from django.urls import path from .views import login_view, register_user, verify_user, verify_number from django.contrib.auth.views import LogoutView urlpatterns = [ path('accounts/login/', login_view, name="login"), path('accounts/<str:phone_number>/verify/', verify_user, name="verify_login"), path("accounts/logout/", LogoutView.as_view(), name="logout"), path('accounts/register/', register_user, name="register"), path('accounts/<str:phone_number>/verify/', verify_number, name="verify_user"), ] from django.urls import path, re_path from django.conf import settings from django.conf.urls.static import static from apps.home import views from apps.authentication import views as auth_views app_name = 'home' urlpatterns = [ # Main Application URLS path('', views.home, name='home'), ... ... ... ] I am thing setting in my settings.py ... LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home:index' LOGOUT_REDIRECT_URL = 'home:home' ... And finally, this is my home function (snippet of my views.py) ... def home(request): context = {} return render(request, "home.html", context) ... I have tried removing the LOGIN_URL setting but not luck. I am only getting these weird logs on my home page at 127.0.0.1:8001 Anyone … -
Django doesn't save ManyToManyField field. Why?
I have been searching for the answer everywhere but haven't managed to find it. Django doesn't save a ManyToManyField (Categories). Please let me know why if you know. So, it saves everything except the Category - ManyToManyField. Everything other works well. There is no any errors. Here is the code: Views.py: def adminpanel(request): categories = Category.objects.all() if request.method == "POST": if 'apost' in request.POST: form = PostForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.save() form.save_m2m() images = request.FILES.getlist('image') for image in images: picture = Image.objects.create( name = instance.name, post = instance, image = image, ) return render(request,'adminpanel.html',{'categories':categories}) Adminpanel.html: <form method = "POST" action = "{% url 'adminpanel' %}" enctype = "multipart/form-data"> {% csrf_token %} <label>Name:</label> <input id = "post_name" type = "text" class = "admin-field" placeholder = "Name" name = "name"><br><br> <label>Category:</label> {% for category in categories %} <input type="checkbox" id="{{category.name}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}">{{category.name}}</label><br> {% endfor %} <br><br> <label>Thumbnail:</label> <input id = "post_thumbnail" type = "file" id = "file" name = "thumbnail" accept = "image/png, image/jpeg"><br><br> <label>Images:</label> <input id = "post_images" type="file" name="image" accept = "image/png, image/jpeg" multiple><br><br> <label>Slug:</label> <input id = "post_slug" type = "text" class = "admin-field" placeholder = "Slug" name = "slug"><br><br> <label>Body:</label> <input id = … -
Django Rest Framework - What to return from a custom filter function for Django Rest Multiple Models
I am using the module DjangoRestMultipleModels so I can post multiple models on a page. I need to filter the objects by the user that created them but I need help as I'm struggling to figure this out. The URL contains the user's id path("posts/user/<int:user>/posts/", UserPostsList.as_view(), name="users posts"), This is the view to show the objects: def get_user(queryset, request, *args, **kwargs): id = kwargs['user'] return #Don't know what to return here class UserPostsList(ObjectMultipleModelAPIView): permission_classes = [IsAuthenticated] def get_querylist(self): querylist = [ {'queryset':Post.objects.all(), 'serializer_class': UserPostSerializer, 'filter_fn': get_user}, {'queryset':Question.objects.all(), 'serializer_class': QuestionSerializer, 'filter_fn': get_user}, ] return querylist I tried using def get_querylist(self): user = self.request.user querylist = [ {'queryset':Post.objects.all()filter(user=user), 'serializer_class': UserPostSerializer}, {'queryset':Question.objects.all(), 'serializer_class': QuestionSerializer, 'filter_fn': get_user}, ] return querylist but because I am logged in as two different users. Admin as 1 user and the front end sending the request as another user I get the wrong results. I must use the user id from the URL -
Django allauth facebook utf-8
I`m using django allauth for social login and i get this resulst in extra_data "first_name": "\u041a\u0438\u0440\u0438\u043b\u043b", "name": "\u041a\u0438\u0440\u0438\u043b\u043b \u0412\u0438\u043d\u044e\u043a\u043e\u0432", How can i get these field in normal view? -
I Need A Python Program To Find whether the photo was taken in front camera or back camera
I Have committed in a project . I'am Locked in a phase and i cant move further. i need a python program to find whether the photo is taken from front camera or back camera if so it should show the picture and say this photo is taken from front camera or back camera I Completed one phase of the program still need an exact program to find the image taken by specific camera -
How to pass pk in reverse() for generics.DestroyAPIView?
I'm writing test for my endpoint responsible for deleting objects. I'm struggling with passing proper pk of object. It is keeping me prompting with django.urls.exceptions.NoReverseMatch. My url: router = routers.DefaultRouter() router.register( prefix="questions-api/delete", viewset=views.QuestionDelete, basename="questions_delete" ) urlpatterns = router.urls The way I'm calling reverse: response = api_client.delete( reverse("questions_delete-list", kwargs={'pk':1}), ) Appreciate any hint :) -
the checking out doesnt work properly , the error is always != 0 but it cannot be so
the idea is that while checking out, if you dont fill in the info, you will get stuck there until you fill in all the info and then you can continue I suppose that the problem is that the error is constantly != 0. However, it cannot be. here is the code that I have problem with: var form = document.getElementById('form') form.addEventListener('submit', function(e) { e.preventDefault() }) document.getElementById('make-payment').addEventListener('click', function(e){ const form = document.getElementById('form') let error = formValidate(form); if (error != 0) { alert('smth typed in') }else { submitFormData() } }) function formValidate(form) { var error = 0; let formReq = document.querySelectorAll('._req'); for(let index = 0; index < formReq.length; index++) { const input = formReq[index] formRemoveError(input); if(input.classList.contains('_email')) { if(emailTest(input)){ formAddError(input); error++; } } else { if (input.value === '') { formAddError(input); error++; } } } } function formAddError(input) { input.parentElement.classList.add('_error') input.classList.add('_error'); } function formRemoveError(input) { input.parentElement.classList.remove('_error') input.classList.remove('_error'); } function emailTest(input) { return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(input.value); } -
Django docker doesn't hot reload for the updates in some folders somehow
I run Django docker and hot reload works normally in most folders. But it doesn't work in some folders. Here are my basic folder structure. whaleserver (Django project) api (app) migrations ... v1 v2 .. Any change inside v1 triggers hotreload but v2 change doesn't somehow. Need help to diagnose this. I already researched but couldn't find proper solution for this. Much appreciated if anyone can give me helpful suggestion on it. Thanks in advance. -
Trim_whitespace=True is not working in Django Serializer
I am trying to trim whitespace from API input before writing to DB. I am using >>> class A(object): ... def __init__(self, name, email, phone_number): ... self.name = name ... self.email = email ... self.phone_number = phone_number ... >>> class ASerializer(serializers.Serializer): ... name = serializers.CharField(max_length = 200, trim_whitespace=True) ... email = serializers.EmailField() ... phone_number = serializers.RegexField("[0-9]{10}") >>> obj = Geeks("Aditi ", "abc@gmail.com", "1234567890 ") >>> serializer = ASerializer(obj) >>> serializer.data {'name': 'Aditi ', 'email': 'abc@gmail.com', 'phone_number': '1234567890 '} why is it not removing space in name? Any idea? -
Safely remove a field from django model
I removed some fields from my database lately and they are still in the older migration files of my project. I don't want to delete all the migration files, since they are in the git and it's not my project. But when I remove a field, the migration has problem because old migration files still have a "connection" to the deleted field. Is there a way to delete a field without deleting migration files and without having any problems? Thank you -
Django additional fields in TabularInline
I have such structure: #admin.py class OrderProductInline(admin.TabularInline): model = OrderProduct extra = 0 template = "admin/edit_inline/tabular_order.html" @admin.register(Order) class OrderAdmin(admin.ModelAdmin): ... inlines = [ OrderProductInline ] #models.py class OrderProduct(models.Model): ... order_id = models.ForeignKey(Order, on_delete=models.CASCADE, blank=False, null=False) to_product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=False, null=True, verbose_name=_('Product')) On the attached image I show some custom inputs (red rectangles) for each product item in inline form. This inputs depends on additional queryset based on Foreign Key, but I cant`t find the correct way how to display this fields there. -
How to remove 'dist' from path while subfolder import from component library using rollup?
I have created a component library and trying to consume the library in my other project using the github repo url. I am able to import the complete library right now. import {component} from 'library'. But when i am trying to import subfolders like this import {component} from 'library/component'. I am not able to do so for that I have to do like this import {component} from 'library/dist/component'. Expected : import {component} from 'library/component'. Current: import {component} from 'library/dist/component' How to achieve this ? -
Calendar in (form) html template like in Django admin panel
I thought it might be useful to someone. How to make a calendar widget like in the Django admin panel. INSTALLED_APPS = [ 'django.forms', ] header.html <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'css/widgets.css' %}"> <script type="text/javascript" src="/admin/jsi18n/"></script> footer.html <script src="{% static 'js/calendar.js' %}"></script> <script src="{% static 'js/DateTimeShortcuts.js' %}"></script> <script src="{% static "js/core.js" %}"></script> forms.html {{ form.date_production }} {% if form.date_production.errors %} {% for error in form.date_production.errors %} {{ error|escape }} {% endfor %} forms.py from score.models import Score from django import forms from django.contrib.admin.widgets import AdminDateWidget class CreateScoreForm(forms.ModelForm): date_production = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Production'}), required=False) date_shipping = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Shipping'}), required=False) date_payment = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Payment'}), required=False) class Meta: model = Score fields = ['date_production', 'date_shipping', 'date_payment',] models.py from django.db import models from django.urls import reverse_lazy class Score(models.Model): date_production = models.DateField(blank=True, null=True, verbose_name='Production') date_shipping = models.DateField(blank=True, null=True, verbose_name='Shipping') date_payment = models.DateField(blank=True, null=True, verbose_name='Payment') def get_absolute_url(self): return reverse_lazy('delete_score', kwargs={'pk': self.pk}) def __str__(self): return self.number class Meta: ordering = ['-date_creation'] -
How to consume url parameters in Django views
Getting an error always The current path, <code>api/det/1</code>, didn’t match any of these. My urls.py url(r'^api/det/<int:id>',views.DetailsAPI.as_view(),name='DetailsAPI') My views.py class DetailsAPI(APIView): def get(self,id): filter_list=Details.objects.all() #filter_list = Details.objects.get(id=id) envid = self.kwargs['id'] df = read_frame(filter_list) df_det = df.loc[df['Id'] == int(id)] df_final=df_det.to_json(orient='records') return HttpResponse(df_final, content_type = 'application/json') I'm sure there is some simple stuff that i'm missing and i can't get it to work with whatever syntax i try.. Any suggestions? -
Why am I unable to add new field in Django model? I am using docker container
I am running the Django service in a docker container. Django has a Postgres database remote access from AWS RDS, and all this is working fine. But I am adding a new field (amount) in Model. class MyModel(models.Model): model_id = models.UUIDField(default=uuid.uuid4) model2 = models.ForeignKey(MyModel2, on_delete=models.CASCADE, related_name='mymodels') amount = models.FloatField(default=0) # this is new field updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) MyModel table already exists in the database. price is new field here. Whenever I start server and create migrations, new migrations are created 'accounts/migrations/0001_initial.py'. docker-compose build docker-compose up -d docker-compose exec djangoservice bash ~\ python manage.py makemigrations ~\ python manage.py migrate after this process, no changes in my database table. Can someone tell me what am I doing wrong? How can I add new fields in my exesting table? -
Django : HTML render from multiple tables linked many-to-one relations
I have multiple models which are defined like that : class Circuit(models.Model): nom = models.CharField(max_length=120) pays = models.CharField(max_length=120, choices=pays_choices) image = models.ImageField(blank=True) class Jeu(models.Model): nom = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField(blank=True) class Course(models.Model): jeu = models.ForeignKey(Jeu, verbose_name='Nom du jeu', on_delete=models.CASCADE) type_course = models.CharField(max_length=50, choices=type_course) ligue = models.ForeignKey(Ligue, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) date_evenement = models.DateTimeField("Date de la course") The Circuit and Jeu models are independent and are respectively gathering data of race tracks and racing games. The Course model is gathering all the races that will happen, and it is taking data from the Circuit and Jeu tables. In the HTML part, I want to display cards of the races that are coming, like that : The picture on top should come from the image of the circuit, in the Circuit model. The date and circuit are coming from the Course table. To achieve that, I already added in the Jeu model a reverse lookup to only take the races of each game : class Jeu(models.Model): nom = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField(blank=True) def courses(self): return self.course_set.all().order_by('date_evenement') But how do I get now the image of the circuit, from the Circuit model ? -
How to disable ANSI escape code output during a Rollup build?
When doing a runtime build with vite it uses rollupjs to do the code transformation, which prints some interesting information in the terminal. While this is fine on a local dev box, it becomes a nuisance in a CI build (here Jenkins): [36mvite v4.0.3 [32mbuilding for production...[36m[39m transforming... Missing export "createServer" has been shimmed in module "__vite-browser-external". Missing export "Socket" has been shimmed in module "__vite-browser-external". [32m✓[39m 3098 modules transformed. rendering chunks... computing gzip size... [2mbuild/[22m[2massets/[22m[32meditor-side-line-straight-3b1dfbb4.svg [39m[1m[2m 0.41 kB[22m[1m[22m [2mbuild/[22m[2massets/[22m[32msquiggle-cb9fe55e.svg [39m[1m[2m 0.47 kB[22m[1m[22m [2mbuild/[22m[2massets/[22m[32mmarkdown-8b37fca1.svg [39m[1m[2m 0.58 kB[22m[1m[22m [2mbuild/[22m[2massets/[22m[32mshell-40c17629.svg [39m[1m[2m 0.60 kB[22m[1m[22m [2mbuild/[22m[2massets/[22m[32mremove-899a6ae3.svg [39m[1m[2m 0.65 kB[22m[1m[22m Is it possible to disable the ANSI escape code in the output to get just the text? Ideally, this should be configurable (say, using an env variable, to know when doing a CI build). -
ImageField gets None value after overriding create method
I am trying to create a user, I need to override the create method, but after that, imagefield gets null value instead of given file here is my code views.py class VerifyEmail(CreateAPIView): serializer_class = UserSerializer queryset = User.objects.none() def create(self, request, *args, **kwargs): print(request.POST.get("profile_picture")) token = request.GET.get("token") invite_info = Invitation.objects.get(new_token=token) data = { 'email': invite_info.receiver, 'organization': invite_info.organization.pk, 'is_staff': request.GET.get('is_staff', False), 'is_superuser': request.GET.get('is_superuser', False), 'first_name': request.POST.get('first_name', ''), 'last_name': request.POST.get('last_name', ''), 'profile_picture': request.POST.get('profile_picture'), 'country': request.POST.get('country'), 'password': request.POST.get('password') } serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) serializer.save() headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=201, headers=headers) serilizers.py # class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( write_only=True, required=True, style={'input_type': 'password', 'placeholder': 'Password'} ) class Meta: model = User fields = ('id', 'email', 'organization', 'first_name', 'last_name', 'country', 'profile_picture', 'date_joined', 'modification_date', "is_active",'password') def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data) imagefield in models.py profile_picture = models.ImageField(upload_to="images",) It's work fine when I use default implementation of create method,but when I try to override it dictionary data gets all values except "profile_picture" which gets None. please help me. -
During a django model's object creation, how to pop out and save a value from a JSON array stored in JSONField of another model's object?
I am building a website in django where users can purchase lets say activation keys for a software. Now there are a limited number of these keys, all of whome are right now stored in a json array in a JSONField of a django model named Software. Whenever a user purchases a key, an object of PurchasedKey model is created. During this, an activation key from the list of available keys must be saved in the attribute named activation_key of this object. After saving the key it must also be deleted from the list of available keys. This is the part I am not sure how to do. I could just manipulate the JSON to retrieve one key from the list, remove it from the list and the update and save the Software object. But is there a better way to do this with probably also a better way to store the available keys instead of using JSONField. # models.py from django.db import models from django.contrib.auth.models import User class Software(models.Model): name=models.CharField(max_length=20) available_keys=models.JSONField() class PurchasedKey(models.Model): purchased_by=models.ForeignKey(User, on_delete=models.CASCADE) software=models.ForeignKey(Software, on_delete=models.CASCADE) activation_key= What to do here -
The view web_vulnerability_scan.views.pdf didn't return an HttpResponse object. It returned None instead
Yesterday,when I try this function,it still working fine but today it suddenly shows this error,what is the problem?I could not post the complete coding,but I searched online,they said should be the if part problem,I have no idea how to fix it,someone please help,thank you!!! def pdf(request, target_id): # to check is the report scan_id already exist for i in req.json().get("reports"): id_list = i['source']['id_list'] # if the report scan_id is in the report which mean already exist if str(id_list)[2:-2] == scan_id: # using fileresponse to let the user download the file file = open('report.pdf', 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="Web_vulnerability_scan_report.pdf"' return response # if the scan_id not found in the report else: req = requests.get(url=api_url, headers=HEADERS, verify=False) pdf_download = req.json().get("reports")[0].get("download")[1] print("report", pdf_download) pdf_url = TAR_URL+pdf_download r = requests.get(url=pdf_url, headers=HEADERS, verify=False) with open("report.pdf", "wb") as code: code.write(r.content) code.close file = open('report.pdf', 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="Web_vulnerability_scan_report.pdf"' return response -
how to create comments form in CBV?
I created a model comments and it was easy to display comments at the bot of post , but how am I suppose to make a form to add comment in same page as art_detail. I mean I have to use a CreateView but ArtDetailView() uses DetailView so i cant put both in one view, and when i put them i separated views only one of views send data to template model: class Comment(models.Model): writer = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) art = models.ForeignKey(Art,on_delete=models.CASCADE) text = models.TextField(max_length=500) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.writer.username views: class CommentView(CreateView): model = Comment template_name = 'art_detail.html' fields = ['text'] def form_valid(self, form): form.instance.art = Art.objects.get(id=self.id) form.instance.writer = self.request.user return super().form_valid(form) class ArtDetailView(DetailView): model = Art template_name = 'art_detail.html' to handle this comments idk even if i need a url or not ? can you please help with this problem -
Is there any default method in python to Format date [duplicate]
I will be getting date input as "2023-01-31" which I have to convert as 31st January 2023. Do we have any default python method for this ?