Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create "profile" urls without explicit passing arguments in django?
I am kinda new at django. For example let's say I'd like to create a BrAnD nEw social network as a pet project. I want my urls to look something like example.com/my-profile but not as example.com/profile/slug_or_pk. I have a user and profile models in different apps for now. Is it actually possible somehow to hide the slug? Models.py class Profile(models.Model): user = models.OneToOneField(User, verbose_name='User', on_delete=models.CASCADE) slug = models.SlugField(null=True) about = models.TextField('About', null=True, blank=True) avatar = models.ImageField("Avatar", upload_to=f"profile/", blank=True, null=True) cover = models.ImageField("Cover", upload_to="profile/", blank=True, null=True) def __str__(self): return self.user def get_absolute_url(self): return reverse('profile_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user.username) return super().save(*args, **kwargs) class Meta: verbose_name = "Profile" verbose_name_plural = "Profiles" views.py class ProfileDetail(DetailView): model = Profile context_object_name = 'profile' template_name = 'user_detail.html' urls.py urlpatterns = [ path('<slug:slug>/', ProfileDetail.as_view(), name='profile_detail'), ] And the root URLconf: urlpatterns = [ path('', IndexView.as_view(), name='index'), path('register/', RegisterUserView.as_view(), name='register'), path('login/', LoginUserView.as_view(), name='login'), path('logout/', LogoutUserView.as_view(), name='logout'), path('users/', include('users.urls')), path('profile/', include('profiles.urls')), path('posts/', include('posts.urls')), ] I've looked over tutorials, articles and etc.but I didn't manage to find something really useful. Maybe I am wrong somewhere at the fundamentals. Please help! -
AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb'
I created two models in my Django db. Now, I want to make migrations, but it shows error like this: AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb' . I tried to google the answer and found that this signal was deprecated in new Django version. It is not my project and I can't change the current version, so my colleagues recommended me to find the solution. What am I supposed to do if I can't change the version of Django and working on dev branch in project? How do I make migrations? What packages I can update? -
Docker redis sync fell into error loop on remote server
I am running Django dev server in docker with celery and redis on my remote host machine. Everything works fine like 30 mins, and then redis starts falling into infinite loop while MASTER <-> REPLICA sync started Here's the console output: redis_1 | 1:S 16 Feb 2023 17:42:37.119 * Non blocking connect for SYNC fired the event. redis_1 | 1:S 16 Feb 2023 17:42:37.805 # Failed to read response from the server: No error information redis_1 | 1:S 16 Feb 2023 17:42:37.805 # Master did not respond to command during SYNC handshake redis_1 | 1:S 16 Feb 2023 17:42:38.057 * Connecting to MASTER 194.40.243.205:8886 redis_1 | 1:S 16 Feb 2023 17:42:38.058 * MASTER <-> REPLICA sync started redis_1 | 1:S 16 Feb 2023 17:42:38.111 * Non blocking connect for SYNC fired the event. redis_1 | 1:S 16 Feb 2023 17:42:39.194 * Master replied to PING, replication can continue... redis_1 | 1:S 16 Feb 2023 17:42:39.367 * Partial resynchronization not possible (no cached master) redis_1 | 1:S 16 Feb 2023 17:42:39.449 * Full resync from master: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ:1 redis_1 | 1:S 16 Feb 2023 17:42:39.449 * MASTER <-> REPLICA sync: receiving 54992 bytes from master to disk redis_1 | 1:S 16 Feb … -
How to return a standard Django Rest Framework JSON from an enum?
I'm not very familiar with DRF and I haven't found a solution on google for this problem (most answers are about a model with a field as enum, my problem is different) You see, we have an Enum in a Django application. Let's call it SomeValuesEnum. class SomeValuesEnum(Enum): ONE_VALUE = "One value" ANOTHER_VALUE = "Another value" What I need to do is to create a GET endpoint that returns the following { "count": 2, "page_count": 1, "next": null, "previous": null, "results": [ { "value": "One value", "name": "ONE_VALUE" }, { "value": "Another value", "name": "ANOTHER_VALUE" } ] } I know I need to create a serializer, but I haven't been able to create one and "feed it". For example, I started with something like this: class SomeValueSerializer(serializers.Serializer): Meta: model = SomeValuesEnum, fields = '__all__' and on the view: class SomeValueListView(APIView): serializer_class = SomeValueSerializer def get(self, request): choices = [{"value": target.value, "name": target.value.capitalize()} for target in SomeValuesEnum] serializer = SomeValueSerializer(data=choices) return Response(status=status.HTTP_200_OK, data=serializer.data) I also tried this class IncidentSerializer(serializers.Serializer): name = serializers.CharField(required=False, allow_blank=True, max_length=100) value = serializers.CharField(required=False, allow_blank=True, max_length=100) I'm not sure if I'm failing on the creation of the serializer, or in how I invoke him on the view (or … -
Protect views from anonymus users in simpleJWT
so I'm getting this weird issue. I have my simpleJWT auth working on the server but for some reason, I can't get permission_classes=[permissions.IsAuthenticated] to block the view from an anonymous user. There are many similar posts but I can't figure out where the issue is. from rest_framework import permissions class UsersListView(ListView): http_method_names = ['get'] permission_classes=[permissions.IsAuthenticated] def get_queryset(self): return UserModel.objects.all().exclude(id=self.request.user.id) def render_to_response(self, context, **response_kwargs): users: List[AbstractBaseUser] = context['object_list'] data = [{ "username": user.user_name, "pk": str(user.pk) } for user in users] return JsonResponse(data, safe=False, **response_kwargs) I've tried the dumbest approach first and removed allow any from here but no luck REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } Can you spot the issue? -
Django Rest: User validation: Is it safe to access self.request in ViewSet for validation in methods like perform_destroy
I want to validate that the user owns the model (is specified in the special field in the model referenced by this model) when user tries to update or destroy a model. In perform_update and perform_create I can access request to get user (with serializer.context["request"]) and referenced model instance with (serializer.validated_data["another_model"]) But in perform_destroy request is not passed. Is it safe to access self.request (will it always return the same request as request passed to destroy)? Even if django rest becomes async once? Or should I validate user in some other way? -
(Django) Why would my code not execute in an .html template?
this is my first post. I'll try get things right first time. I am having a play around with django and slowly creating a dummy store website. I'm following along a Corey Schafer YouTube tutorial and I didn't have this issue on my first run, so scratching my head now! My problem is that my .html template is not displaying the listing item when I run the page. I still see the <h1>DaftPrices Store Homepage</h1>, but not the listings. This is my template (store_home.html): <!DOCTYPE html> <html lang="en"> <head> <title>DaftPrices - Home</title> </head> <body> <h1>DaftPrices Store Homepage</h1> {% for listing in listings %} <p>{{ listing.item }}</p> {% endfor %} </body> </html> This is saved in a store dir, inside a templates dir, inside the store app. Image of directories This is my app views.py: from django.shortcuts import render listings = [ { 'seller': 'Chazsharpe', 'title': 'Something to sell', 'date_posted': '28th August 3030' } ] def store_home(request): context = {'listing': listings} return render(request, 'store/store_home.html', context) def store_about(request): return render(request, 'store/store_about.html') To clarify, the page pulls the template, but the "code" isn't working I have tried re-writing the dummy listings and changing the variables. I wasn't expecting this to do anything (and … -
Django serializer data
I need to get value of basket in 'title' not in 'id'. How can I do this? How can I get a value of 'title' from 'Position' model in another 'Client' model using ManyToManyField. It automatically transmits ID and the 'title' is required I have tried many ways but... It must be easy, but i search info 2 days class Position(models.Model): title = models.CharField(max_length=150, verbose_name='Title') slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name='URL') description = models.CharField(max_length=500, verbose_name='Describe') photo = models.ImageField(upload_to="photos/%Y/%m/", verbose_name='Photo', null=True) price = models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Price') date_create = models.DateTimeField(auto_now_add=True, verbose_name='Date create') date_update = models.DateTimeField(auto_now=True, verbose_name='Date update') is_published = models.BooleanField(default=True, verbose_name='Is published') in_stock = models.BooleanField(default=True, verbose_name='In stock') class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) basket = models.ManyToManyField('Position', default=None, blank=True, related_name='basket') def __str__(self): return f'{self.user.username}, id-{self.user.id}' class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer permission_classes = (IsOwnerOrReadOnly,) def get_queryset(self): pk = self.kwargs.get('pk') # need a list of objects, not an one return Client.objects.filter(pk=pk) result: { "id": 1, "user": 1, "basket": [ 1 ] } need something like this - "basket":['monitor','keyboard'] -
Why would js function not trigger on button click?
I'm trying to follow this guide and I'm having a bit of an issue I can't figure out how to fix. Basically in PassKeys.html you have these 2 following bits of code: <button class="btn btn-success" onclick='start()'>Add Key</button> function start(){ $("#modal-title").html("Enter a token name") $("#modal-body").html(`<p>Please enter a name for your new token</p> <input type="text" placeholder="e.g Laptop, PC" id="key_name" class="form-control"/><br/> <div id="res"></div> `) $("#actionBtn").remove(); $("#modal-footer").prepend(`<button id='actionBtn' class='btn btn-success' onclick="begin_reg()">Start</button>`) $("#popUpModal").modal('show') } Now I'm no JavaScript expert but I would wager that when I click that button (which I can see in my webpage) a function should run that activates a modal. In the example provided by the guide things do work exactly that way, but in my application it doesn't seem to, and the code itself is exactly the same. What could be the cause of that? -
Correct use of pytest fixtures of ojects with Django
I am relatively new to pytest, so I understand the simple use of fixtures that looks like that: @pytest.fixture def example_data(): return "abc" and then using it in a way like this: def test_data(self, example_data): assert example_data == "abc" I am working on a django app and where it gets confusing is when I try to use fixtures to create django objects that will be used for the tests. The closest solution that I've found online looks like that: @pytest.fixture def test_data(self): users = get_user_model() client = users.objects.get_or_create(username="test_user", password="password") and then I am expecting to be able to access this user object in a test function: @pytest.mark.django_db @pytest.mark.usefixtures("test_data") async def test_get_users(self): # the user object should be included in this queryset all_users = await sync_to_async(User.objects.all)() .... (doing assertions) ... The issue is that when I try to list all the users I can't find the one that was created as part of the test_data fixture and therefore can't use it for testing. I noticed that if I create the objects inside the function then there is no problem, but this approach won't work for me because I need to parametrize the function and depending on the input add different groups … -
simpleJWT confirm password field
I'm creating a small app that uses simpleJWT. I want the user to retype their password when registering. Currently, I'm sending data like this { "email":"test", "user_name":"test3", "password":"b12@wsqp" } But what I want to validate is { "email":"test", "user_name":"test3", "password":"b12@wsqp", "password2":"b12@wsqp" } What i have now is class CustomUserCreate(APIView): permission_classes = (AllowAny,) def post(self, request): reg_serializer = RegisterUserSerializer(data=request.data) if reg_serializer.is_valid(): new_user = reg_serializer.save() if new_user: return Response(status=status.HTTP_201_CREATED) return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST) class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance So my guess is to do class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2') extra_kwargs = {'password': {'write_only': True}, 'password2':{'write_only': True}} def create(self, validated_data): password1 = validated_data.pop('password1', None) password2 = validated_data.pop('password2', None) instance = self.Meta.model(**validated_data) if password1 is not None and password2 is not None: if password1 == password2: instance.set_password(password) else: #return some error instance.save() return instance How can I validate if the password are matching? -
Chrome Extension Requesting django server
I am creating a chrome extension that requires a back end server for processing. I would like it to send data to the server, the server will process this data and send some other data back to the user. Preferably this back end server should be in python as there are libraries I would like to use. Any idea how to go about this? I was thinking to use a django server with rest API but I'm not sure what would be best. If anyone could provide a tutorial link or briefly explain the code behind this idea it would be brilliant. -
permission for show media folder in django, python
I want set permission for show media folder images. for example, I want show my images to users who are staff. When user in not staff, show 404 Error Thanks -
Django filter objects and do not select objects if there are objects that were created before them with same field value
I'm trying to do a get_queryset for ModelList view, but I only want to select those records that don't have other records with the same event_id in front of them. For example, we have two records. The second record is a child of the first one, and therefore, I don't want to select this second record from the database because it will already be in the children field of the first record. The children field is generated in the serializer, and does not exist in the database. Dataset [ { "event_id": "63395", "operation_id": "25180328", "time_created": "2023-01-12T09:16:11.873700+01:00", "children": [ { "event_id": "63395", "time_created": "2023-01-12T09:16:41.285390+01:00", "operation_id": "25180329", "children": [] } ] }, { "event_id": "63395", "time_created": "2023-01-12T09:16:41.285390+01:00", "operation_id": "25180329", "children": [] } ] View class ModelList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] queryset = Model.objects.all() serializer_class = ModelSerializer def get_queryset(self): return Model.objects.filter( ~Q( Q(event_id=F('event_id')) & Q(operation_id__gt=F('operation_id')) ) ) -
How can I update specific field after retrieved in django rest framework
How can I update specific field after retrieved in django rest framework # Models.py class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() view = models.IntegerField(default=0) def __str__(self): return self.title I want to update view after read a specific data. # Views.py class ArticleDetail(generics.RetrieveUpdateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer # Update view + 1 # serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = "__all__" Please help me -
How to display not id but another value in ForeignKey
This is my code for the hotel website models.py class Rooms(models.Model): room = models.BigIntegerField(verbose_name='Комната', unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория', related_name='wer') room_bool = models.BooleanField(verbose_name='Статус', default=True) price = models.BigIntegerField(verbose_name='Цена', null=True,blank=True) class Registrations(models.Model): room_num = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', related_name='ertgdb', limit_choices_to={'room_bool': True}) first_name = models.CharField(max_length=250, verbose_name='Имя') last_name = models.CharField(max_length=250, verbose_name='Фамилия') tel_num = models.BigIntegerField(verbose_name='Номер телефона') img = models.FileField(verbose_name='Паспорт', null=True, blank=True) visit_date = models.DateField(default=now, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, help_text='Дата отбытия') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_relevant = models.BooleanField(default=False, verbose_name='Статус') price = models.BigIntegerField(verbose_name='Цена', default=100) serializers.py class RegistrationSer(serializers.ModelSerializer): class Meta: model = Registrations fields = ('id', 'room_num', 'first_name', 'last_name', 'tel_num', 'img', 'visit_date', 'guest_count', 'room_relevant') I need the room_num field (in the picture) to have not Id but room_num as in the Input form SlugRelatedField doesn't work because I can't make POST PUT requests later -
Django - ValueError: could not convert string to float: ''
Learning Django with tutorial and have error. File "F:\Python\COTSW\teashop\main\views.py", line 98, in cart_list total_amt+=int(item['qty'])*float(item['price']) ValueError: could not convert string to float: '' Views.py def cart_list(request): total_amt = 0 for p_id, item in request.session['cartdata'].items(): total_amt+=int(item['qty'])*float(item['price']) return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt}) Custom.js $(document).on('click', ".add-to-cart", function(){ var _vm=$(this); var _index=_vm.attr('data-index'); var _qty = $(".product-qty-"+_index).val(); var _productId = $(".product-id-"+_index).val(); var _productTitle = $(".product-title-"+_index).val(); var _productImage = $(".product-image-"+_index).val(); var _productPrice = $(".product-price-"+_index).text(); var _productSlug = $(".product-slug-"+_index).val(); console.log(_productPrice) // Ajax $.ajax({ url:'/add-to-cart', data:{ 'qty':_qty, 'id':_productId, 'title':_productTitle, 'image':_productImage, 'price':_productPrice, 'slug':_productSlug, }, dataType:'json', beforeSend:function(){ _vm.attr('disabled', true); }, success:function(res){ $(".cart-list").text(res.totalitems); _vm.attr('disabled',false); } }); Before changes var _productPrice = $(".product-price").text(); was var _productPrice = $(".product-price").text(); and worked. Console.log showing correct price 500.00, but total_amt+=int(item['qty'])*float(item['price']) taking an empty string. Everything works correctly in the tutorial and I don't understand what could be wrong. -
Django: how to filter the inbox messages that belong to a user?
I am trying to get the messages that belongs to a user, something that look like this I am finding it difficult to write the filter query, according to this Answer, i wrote a query that looks like this class MyInbox(generics.ListCreateAPIView): serializer_class = MessageSerializer def get_queryset(self): user_id = self.kwargs['user_id'] messages = ChatMessage.objects.filter(Q(sender__in=user_id) | Q(reciever__in=user_id)).order_by("-date") return messages This is my response what i am trying to do is this, get the latest message that i had with sam, also the latest message that i had with moz and not all the messages. I am trying to get this messages because i want to loop through the message just like in the screenshot above. This is my model class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="user") sender = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="sender") reciever = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="reciever") message = models.CharField(max_length=10000000000) is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) mid = ShortUUIDField(length=10, max_length=25, alphabet="abcdefghijklmnopqrstuvxyz") Please how do i go about this? -
Add method imports to shell_plus with alias
I have a model naming collision in my django models, with 2 models called Tag in separate modules. That looks something like this: . ├── conversations/ │ └──models.py <- contains a model called Tag └── dogs/ └──models.py <- contains a model called Tag In shell_plus I want to import each module with an alias in SHELL_PLUS_POST_IMPORTS so that it's available when I start the shell. How can I do this? As an example, if i were doing this manually in shell_plus I'd write: # These are the imports I want to happen automatically: from conversation import models as conversation_models from dogs import models as dog_models # Then I can write: conversation_models.Tag() dog_models.Tag() -
How to add faker data in django in place of foreign key field
All i need is that user field of Product com from the foreign key of User model How can i add daker data here it gives me this error Product.objects.create( Product_name=fake.name(), Product_desc = fake.text(), Price=fake.random_int(3000, 10000), user=1 ) class User(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=300, null=True, blank=True) password = models.IntegerField() def __str__(self): return self.name class Product(models.Model): Product_name = models.CharField(max_length=30) Product_desc = models.CharField(max_length=300, null=True, blank=True) Price = models.IntegerField() user=models.ForeignKey(User, on_delete=models.CASCADE,related_name='set_user') def __str__(self): return self.Product_name Here is the error -
python request para aplicativo da minha empresa
Tenho três tabelas em uma aplicação python que precisam ser relacionadas para criar uma lista com nomes advindos de um resultado de uma querie, porém em uma das tabelas só há um argumento que conecta todas. Tenho tentado reproduzir essa querie sql no python porém sem mt sucesso "select * from sicei.lotamento as lotamento, sicei.estagiario as estagiario where estagiario.status='1' and lotamento.status='1' and lotamento.lotacao_id='1'; " e utilizado uma função com get_object_or_404, semelhante a este exemplo abaixo: def det_vagas(request, ): est = get_object_or_404(Lotamento, ) lotamento=Lotamento.objects.filter() estagiario = Estagiario.objects.filter() context={'lotamento': lotamento, 'estagiario':estagiario} return render(request, 'mapas_de_vagas/detalhes.html', context) mas não to conseguindo fechar a querie, por dificuldade em entender a lógica relacional mesmo, sendo que a terceira tabela, só cria uma lista aonde eu deveria capturar o valor de uma coluna (lotacao_id) para obter o resultado que preciso. Será que conseguem me ajudar? Meio desesperado pq não to conseguindo. '-' Tentei utilizar uma função baseada em classe, mas o filtro deu ruim, e tentei trocar os argumentos porém sem resultados. -
In Django, passenger_wsgi.py is calling itself creating infinite processes
We are using Angular JS for frontend and Django framework at backend. Whenever a request comes from the front-end, passenger_wsgi file receives the request. It processes the request and returns the expected response. However, passenger_wsgi calls itself, which calls itself. This happens recursively, in an loop causing infinite processes and server to overload. Appreciate your comments and a fix. Below is the current passenger_wsgi. import os import sys import django.core.handlers.wsgi from django.core.wsgi import get_wsgi_application # Set up paths and environment variables sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # Set script name for the PATH_INFO fix below SCRIPT_NAME = os.getcwd() class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) # Set the application application = get_wsgi_application() application = PassengerPathInfoFix(application) I have tried changing the last 2 lines. In this scenario, passenger_wsgi is not able to serve the request and frontend received 500 Server Error. -
Is there a form field in Django that allows you to enter multiple values one at a time?
I could also use a TextField, but that's not ideal from UX point of view. I would like to know if there's a field that allows the user to enter multiple custom strings (not from a pre-defined list of options), one at a time, where, to enter a string, one needs to press enter, these values are then passed as a list of strings (or other types) to the model, which defines an ArrayField. I've searched for some time, but I couldn't find it. I'm not really an expert in Django, but I suppose such a field must exist. If not, I suppose I could create a custom form field that does that. Here's what I mean. In the example, 1 was written, then the user pressed ENTER, and the option was added; then the same thing happened to add 2; the important thing to note is that 1 and 2 do not come from a predefined set of values, but were custom strings entered by the user, which can also be removed after having been entered. -
After executing an api in django rest, the RAM remains high
After executing an api in django rest in production mode, the following method is called and executed. After each execution of this method, the amount of RAM usage goes up and up and does not go down, and I don't understand where the problem is. def download(self): try: if self.adjust: path = Path(UPLOAD_DIR / 'yf_history' / self.market / 'adjusted') else: path = Path(UPLOAD_DIR / 'yf_history' / self.market) path.mkdir(parents=True, exist_ok=True) data = yfinance.download( progress=False, tickers=self.ticker_list, period=self.period, interval=self.interval_period, group_by='ticker', auto_adjust=self.adjust, prepost=False, threads=True, proxy=None ).T for ticker in self.ticker_list: try: data.loc[(ticker,),].T.dropna().to_csv(path / f'{ticker}{self.suffix}.csv') except: pass del data except Exception as error: return False, error else: return True, 'Saved successfully' I don't have this problem with any other function Python==3.9 Django==3.2.9 djangorestframework==3.13.1 yfinance==0.2.10 Thank you for your advice on the problem and solution. -
How can we sync different databases and application in django
How can we access other database tables into django application database. Here 'default' database is main application and 'cl_db' is other application which is developed in asp.net but using same database server here how can we sync 'cl_db' database into 'default' database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fail_over', 'USER': 'SomeUser', 'PASSWORD': 'SomePassword', 'HOST': '127.0.0.1', 'PORT': '', }, 'cl_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cl_dev', 'USER': 'SomeUser', 'PASSWORD': 'SomePassword', 'HOST': '127.0.0.1', 'PORT': '', }, }