Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a drawback to adding multiple indexes to a model in Django?
I'm working on a django dashboard to display data in a series of charts, and thusly need to set up different dataframes from my models. When I load the dashboard up in production, it takes about 15 seconds for the view to be rendered. Another dashboard takes 40. After analyzing my code, it turns out my queries are very time consuming. I thought they wouldn't be since my Order model has about 600k objects, while the order_date filters should get them down to some 30k at most. Below is my model: class Order(models.Model): order = models.IntegerField(db_index=True, default=0) region = models.CharField(max_length=3, default="") country = models.CharField(db_index=True, max_length=2, default="") order_date = models.DateTimeField(db_index=True, default=datetime.datetime.now) user_name = models.CharField(db_index=True, max_length=256, null=True) order_status = models.CharField(max_length=256, null=True) quote_status = models.CharField(max_length=256, null=True) purchase_status = models.CharField(max_length=256, null=True) q_to_r = models.FloatField(db_index=True, null=True) r_to_p = models.FloatField(db_index=True, null=True) And here is the snippet of code that takes 15 seconds to evaluate: month = [4, 2022] country = ["US", "CA", "UK"] user_list = ["Eric", "Jane", "Mark"] all_objects = Order.objects first_data = all_objects.filter(order_date__month=month[0], order_date__year=month[1], country__in=country, order_status__in=order_status, quote_status__in=quote_status, purchase_status__in=purchase_status, user_name__in=user_list) order_data = first_data.values_list("order", flat=True) country_data = first_data.values_list("country", flat=True) df = pd.DataFrame({"Order": order_data, "Country": country_data}) The df instance in particular is what takes the bulk of the … -
Docker compose creating import errors?
I am trying to run a simple django app on docker-compose I created a docker file and docker compose and when running I get the following. I had two venv folders which I deleted cause they were a mess in GitHub. I also have a submodule import which is some blockchain related stuff but it is just there and doing nothing at the moment within the django app ahmed@Ahmed-PY:~/ssa2$ sudo docker-compose up Recreating ssa2_web_1 ... done Attaching to ssa2_web_1 web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | May 17, 2022 - 14:39:40 web_1 | Django version 4.0.2, using settings 'ssfa.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 46, in get_internal_wsgi_application web_1 | return import_string(app_path) web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 30, in import_string web_1 | return cached_import(module_path, class_name) web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 15, in cached_import web_1 | import_module(module_path) web_1 | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "<frozen importlib._bootstrap>", … -
Inability to access Django Admin page on app deployed with Docker on Digital Ocean, and using Traefik as reverse proxy
I have deployed a Django app to a Digital Ocean Droplet with Docker. I am using Traefik for reverse-proxy. I have configured DO's DNS to point my Domain Name wbcdr.com to the Droplet's public IP. Although, I am able to access the site, I get a 404 Error for the Django admin page, i.e. https://www.wbcdr.com/admin. Do I have to add another A record separately for the admin url? Or is it due to Traefik's inability to resolve the Admin url? -
django forms, empty_label attribute for select widget is working for ForeignKey field but not for CharField
I'm trying to set up a form that allows a tattoo shop to book consultations. There are 2 select fields: select an artist and select a tattoo style. Instead of the default first option of the select field being '--------', I would like them to say 'Preferred Artist' and 'Tattoo Style', respectively. models.py: class ConsultationRequest(models.Model): tattoo_styles = [ ('water-color', 'Water Color'), ('blackwork', 'Blackwork'), ] preferred_artist = models.ForeignKey(Artist, on_delete=models.CASCADE) tattoo_style = models.CharField(max_length=50, choices = tattoo_styles ) forms.py: class ArtInformationForm(ModelForm): class Meta: model = ConsultationRequest fields = ['preferred_artist', 'tattoo_style'] def __init__(self, *args, **kwargs): super(ArtInformationForm, self).__init__(*args, **kwargs) self.fields['preferred_artist'].empty_label = 'Preferred Artist' # this works self.fields['tattoo_style'].empty_label = 'Tattoo Style' # this doesn't work When I display this form in a template, the first option for selecting an artist is 'Preferred Artist', but the first option for selecting a tattoo style is still the default dashes. Not sure why this is. I am thinking it has something to do with them being two different kinds of fields, one being a ForeignKey and one being a CharField. Thanks for any help with this. -
How to add multiple image by click "add an image" button in django?
In Django e-commerce project I want to add a few images, I have already added two images front_image and back_image, But I want to add more. When I click the "add an image" button, I want an image field to appear and save those images when form save. -
How to start a django project on one that is already created?
I already have a django project and all files created, but I am trying to deploy to a server. I moved files over to server using FileZilla and I am in putty now trying to django-admin startproject practice ~/practice but I get a command error stating that this already exists which obviously it does but then if I want to manage.py makemigrations I get a -bash: Permission denied and I am guessing that is because I have not started django project here on putty??? I hope there is enough info here to explain my issue. Any help is appreciated -
Customize django admin. Problem with no-model views
Im trying to create a extra view in django admin, on the left navbar. This view will be responsible for uploading a file, which will be parsed in some function (in future i would like to render result of this parsing in admin page). This file wont be saved in database, so there wont be a model. Is there any possibility to add a view to django admin (left navbar) which dont have a model? I was reading a lot, and could find a solution. What i have done for now: Created a class which inherits from AdminSite. I tried to implement get_app_list method, but variable self._build_app_dict(request) was empty array, and this means, method couldn't find a installed aps. I wanted to add new object to app_list variable, to render it on website. Tried to override a admin templates, but couldnt render it. I tried to override app_index.html which i put on folder: app_name/templates/admin/app_index.html Here is my code, which ofc doesnt work: class MyCustomAdmin(AdminSite): def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site. """ app_dict = self._build_app_dict(request) breakpoint() app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) for app in app_list: app['models'].sort(key=lambda … -
Using subdomains and CNAME records with Nuxt
I know that I can set up a single Nuxt project which can serve multiple subdomains, like this:- app1.example.com app2.example.com ... and have different content served on each subdomain based on the value of the subdomain. The way this would work is that the Nuxt server would detect the value of the subdomain (app1, app2 etc.) and fetch data from the API (I am using a django rest framework backend) using that as a filter. But is there a way of then mapping another domain to these subdomains so that the Nuxt server still knows how to fetch the right data from the API? Something like this:- myapp1.com -> app1.example.com myapp2.com -> app2.example.com I think that Heroku does something like this but it's hard to be certain - so it seems possible to me. But maybe there's another way to do this? -
Django input text not showing up on home page
I'm working on a todo app, that has a home page where all todos are listed. You can click on a link on the left that leads you to another page (newTodo.html) where you can add a new todo (text, due date and percentage of how much is done already). I want the todos to be saved in db.sqlite so when I refresh the page the todos are still there. My problem is, whenever I try adding a new todo it won't show up on the home page. I'm very new to Django/Python so please excuse my badly written code (still learning!), I was trying out a few things but nothing seemed to work. forms.py class ListForm (forms.Form): class Meta: model = List fields = ["taskText", "taskDate", "taskPerc"] models.py from django.db import models class List(models.Model): taskText = models.CharField(max_length=150) taskDate = models.CharField(max_length=50) taskPerc = models.IntegerField() newTodo.html (using Bootstrap) <form action="/newTodo" method="POST"> {% csrf_token %} <td scope="row"><input type="text" class="form-control" id="taskText" name="taskText"></td> <td scope="row"><input type="text" class="form-control" id="taskDate" name="taskDate"></td> <td scope="row"><input type="text" class="form-control" id="taskPerc" name="taskPerc"></td> <td><a href="{% url 'home' %}" class="btn btn-success" role="button"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check" viewBox="0 0 16 16"> <path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 … -
Django-celery can't work in another environment but work in localhost
I try to learn and pratice celery with django in the best way and it works in only localhost environment, But the problem is when i build to another environment it returns error like this web_1 | app.config_from_object('django.conf:settings', namespace='CELERY') web_1 | TypeError: config_from_object() got an unexpected keyword argument 'namespace I delete the namespace='CELERY' but it's return another error like AttributeError: 'Overview' object has no attribute '__qualname__' I use django-celery==3.3 Here is my code: celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OPTIMUM_HAIRUN.settings') app = Celery('OPTIMUM_HAIRUN') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(settings.INSTALLED_APPS) app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') in views.py : @shared_task def run_file_to_process(self, id): do_something ps: as i say this code work properly in localhost but not work when i build this in another environnment -
how to split one database into two with django
I have one big data table that I want to turn into two tables Accordingly, I need certain columns from the big table in the first table Аnd in the second table I need to transfer the remaining columns here my old model.py class HV(models.Model): from direction.models import Project id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) address = models.CharField(max_length=90) username = models.CharField(max_length=60) password = models.BinaryField() kind = models.CharField(max_length=60) enabled = models.BooleanField(default=True) availability = models.BooleanField(default=True) time_unavailable = models.DateTimeField(null=True) direction = models.ForeignKey(Department, on_delete=models.PROTECT, null=True, default=None) project = models.ForeignKey(Project, on_delete=models.PROTECT, null=True, default=None) class Meta: managed = True db_table = 'hv_list_service' def __str__(self): return self.name and my new models.py class ClusterName(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) kind = models.CharField(null=True, max_length=10) enabled = models.BooleanField(default=True) availability = models.BooleanField(default=True) time_availability = models.DateTimeField() direction_id = models.ForeignKey(Department, on_delete=models.PROTECT) project_id = models.ForeignKey(Project, on_delete=models.PROTECT) class Meta: managed = True db_table = 'vmlist_cluster_name' def __str__(self): return self.name class ClusterPooling(models.Model): id = models.AutoField(primary_key=True) address = models.CharField(null=True, max_length=120) username = models.CharField(null=True, max_length=50) password = models.BinaryField(null=True) cluster_name_id = models.ForeignKey(ClusterName, null=True, on_delete=models.PROTECT) active = models.BooleanField(null=True) class Meta: managed = True db_table = 'vmlist_cluster_polling' def __str__(self): return self.address I know you can transfer data from one table to another using Django, but I have no idea what … -
How can make foreignKey from the same table in django?
How can make foreign-key from the same table in Django admin? For example, I have data of persons with first name and last name: Joe Ni Joe Ri Bob Gh and I have a Person model: class Person(models.Model): name = models.CharField(max_length=25) lname = models.CharField(max_length=25, blank=False) def __str__(self): return str(self.name) class MyModel(models.Model): first_name = models.ForeignKey(Person, on_delete=models.CASCADE) last_name = models.ForeignKey(Person, on_delete=models.CASCADE) Now i wanna choose for example the value 'Joe' in "MyModel" and then it will show me all the other valid options for this first name: NI, RI How can i do it? TNX guys -
Cannot raise ParseError from Django ViewSet
I have a method in a ViewSet where I want to validate that request.data is a list. If it is not, I would like to raise a ParseError(). However, my code crashes when I actually raise said ParseError and I don't understand why. I can easily raise ValidationError()s and both are subclasses of APIException, which the documentation states to be handled automatically. # views.py class MyViewSet(viewsets.GenericViewSet): ... @action(methods=['post'], detail=False, url_path='bulk-create') def bulk_create(self, request, *args, **kwargs): # Assert that request.data is a list of objects if not isinstance(request.data, list): raise ParseError("Expected the data to be in list format.") # Actually process incoming data ... Calling the route with anything other than a list correctly triggers my if statement, but instead of returning a proper response with status.HTTP_400_BAD_REQUEST, the server crashes and I receive the following error: Traceback (most recent call last): 2022-05-17T12:23:45.366216553Z File "/opt/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2022-05-17T12:23:45.366221178Z response = get_response(request) 2022-05-17T12:23:45.366223345Z File "/opt/venv/lib/python3.9/site-packages/debug_toolbar/middleware.py", line 67, in __call__ 2022-05-17T12:23:45.366225470Z panel.generate_stats(request, response) 2022-05-17T12:23:45.366238220Z File "/opt/venv/lib/python3.9/site-packages/debug_toolbar/panels/request.py", line 30, in generate_stats 2022-05-17T12:23:45.366240470Z "post": get_sorted_request_variable(request.POST), 2022-05-17T12:23:45.366346803Z File "/opt/venv/lib/python3.9/site-packages/debug_toolbar/utils.py", line 227, in get_sorted_request_variable 2022-05-17T12:23:45.366352511Z return [(k, variable.getlist(k)) for k in sorted(variable)] 2022-05-17T12:23:45.366354803Z TypeError: '<' not supported between instances of 'dict' and 'dict' Because of the … -
Django admin import-export one model and two different csv files depending select options?
I am using django-import-export, and want to import to one model different CSV files. I mean for example I have a model Statement class Statement(models.Model): amount = MoneyField(max_digits=14, decimal_places=4, default_currency='EUR', currency_field_name='currency', default="0.0000", currency_max_length=5, null=True ) type = models.CharField(name='type', choices=Type.choices, max_length=50, default=Type.INCOME) But I want to import statement files from different bank accounts, and, of course, the structure of each file can be different. One bank has CSV like ref_code, amount, currency, direction 1569852, 10.00, EUR, Income The second bank has a structure Order number, Amount, Curr, Account No 569486, 10.99, EUR, BE658954412 But I want to import this data, parse and insert it into the same table. I created a Resource class, Custom Import Form, etc. class StatementResource(resources.ModelResource): amount = Field(attribute='amount', column_name='Amount') currency = Field(attribute='currency', column_name='Currency') class Meta: model = Statement ... class CustomImportForm(ImportForm): bank = forms.ModelChoiceField( to_field_name='pk', queryset=Bank.objects.all(), required=True) Then I rewrite get_import_data_kwargs @admin.register(Statement) class StatementAdmin(ImportExportModelAdmin): resource_class = StatementResource def get_import_form(self): return CustomImportForm def get_import_data_kwargs(self, request, *args, **kwargs): form = kwargs.get('form') if form: return {"bank": form.cleaned_data["bank"]} return dict() But how to parse CSV depending on which bank is selected? -
How to display KML layers on google maps JavaScript
What is the best practice to display KML layers on google maps js? I have an HTML page with google maps on it that takes some arguments and context from Django view and displays back a map with some info like KML Layers . Here is how I do this : Map HTML page <script> // Initialize and add the map let poly; let map; let bounds = []; let cords = []; let point_1_marker = []; let point_2_marker = []; let normaPointMarker = []; let flightPlanCoordinates = []; let pt1; let pt2; let kmlLayer; function initMap() { const lat = "{{lat}}"; const lng = "{{lng}}"; const myLocation = { lat: parseFloat(lat), lng: parseFloat(lng) }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 14, center: myLocation, zoomControl: false, streetViewControl: false, fullscreenControl: false, }); const marker = new google.maps.Marker({ position: myLocation, map: map, }); {% if go_to_my_location %} console.log("loc true"); map.setCenter(myLocation); {% endif %} //Breach Part {% if breach == 'true' %} var isClosed = false; var poly = new google.maps.Polyline({ map: map, path: [], strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2 }); var clickedPoints = [] google.maps.event.addListener(map, 'click', function (clickEvent) { if (isClosed) return; var markerIndex = poly.getPath().length; var isFirstMarker = markerIndex … -
How do you list blog posts from a specific category?
So the site is built similarly to a blog. Basically update=post and timeline=catagory I'm trying to make a page where the categories are listed and you can click on them and it will list all the posts under that category. Right now, it will list the categories and when you click on it, it does go to the specific one, but how do I list all the articles inside it? Right now all I can do is display the title of the category. I realize that's because I've created the queryset for the catagory but Is there a way to call upon the posts corresponding to that category in my HTML? Or do I have to switch to using the post in my queryset. If so how do I do that because I tried and boy did that create a lot of errors. models.py urls.py views.py timelineArticles.html timelines.html -
Django - modify login view using built in login mechanism
I have created login mechanism basing on build in functionality and using this tutorial: https://learndjango.com/tutorials/django-login-and-logout-tutorial Now I need to access what is entered in username field in build in view created by django.contrib.auth. Need to do this from login view because i need to log failed login attempt with IP adress. The problem is i do not have this view in my views.py because its somehow built-in urls.py: urlpatterns = [ [...] path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), [...] ] .../templates/registration/login.html [...] <form method="post"> {% csrf_token %} <h2><p class="font-weight-bold">{{ form.as_p }}</p></h2> <button type="submit" class="btn btn-dark">Login</button> </p> </form> [...] How to access or eventually overwrite this view without changing anything else within app. -
Django .save() method not saving
I'm trying to save a text imput from an HTML page, and then display it on a redirect. It seems that the .save() method isn't working. I'm quite new to Django and HTML in general. I've followed the official Django tutorial and trying to apply the concepts from that into this app. Basically, it is supposed to take a user input from an HTML page and then save it to a list of names. Then, I want to redirect to another page which displays a list of these names. Anyone have any ideas? Here's my code: In views.py: from django.shortcuts import render, HttpResponseRedirect, redirect from .models import Contact def addListing(request): if request.method == 'POST': new_contact = Contact( full_name=request.POST['fullname'], ) new_contact.save() return redirect('listings') return render(request, 'farmsearch/add_listing.html') def listings(request): farms = Contact.objects.all() return render(request, 'farmsearch/listings.html', {'farms': farms}) In models.py: from django.db import models class Contact(models.Model): full_name = models.CharField(max_length=250) def __str__(self): return self.full_name In add_listing.html: <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link … -
trying to use channels in Django caused these errors
I was trying to use channels in Django, To do that I followed a tutorial and made these changes in the asgi.py file from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter( { "http":get_asgi_application() }) and these in the settings.py file ASGI_APPLICATION = 'lostAndFound.wsgi.application' after that, i restarted the server and got an internal server error, and the error in the terminal `Exception inside application: WSGIHandler.__call__() takes 3 positional arguments but 4 were given Traceback (most recent call last): File "/home/alaa/.local/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in call return await self.application(scope, receive, send) TypeError: WSGIHandler.call() takes 3 positional arguments but 4 were given` can anyone plese help me with this -
Django many-to-many model generation
I am making an offer creation module in Django, I have a product and a variant object, the product variant is connected with a many-to-many relationship. What I want to do is to save the products by selecting them while creating the offer, but at the same time to offer the option to choose the variants under the products. The problem here is that the products and variants are not separate. model.py class offerProductVariant(models.Model): offerProduct = models.ManyToManyField(product) offerVariant = models.ManyToManyField(variant) class offer(models.Model): offerName = models.CharField(max_length=50) offerCustomer = models.ForeignKey(customer,on_delete=models.CASCADE,null=True,blank=True) offerCompany = models.ForeignKey(company,on_delete=models.CASCADE,blank=True) offerDate = models.CharField(max_length=40) offerProductVariantMany = models.ManyToManyField(offerProductVariant,blank=True) views.py def teklifsave(request): if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': form = offerCreate(request.POST) form2 = offerCreateProduct(request.POST) if form.is_valid(): m = offer( offerName = form.cleaned_data['offerName'], offerCompany = form.cleaned_data['offerCompany'], offerCustomer = form.cleaned_data['offerCustomer'], offerDate = form.cleaned_data['offerDate'] ) m.save() if form2.is_valid(): op = offerProductVariant() op.save() fproducts = form2.cleaned_data['offerProduct'] print(fproducts) fvariants = form2.cleaned_data['offerVariant'] print(fvariants) for fproduct in fproducts: print(fproduct) op.offerProduct.add(fproduct) op.save() for fvariant in fvariants: print(fvariant) op.offerVariant.add(fvariant) op.save() m.offerProductVariantMany.add(op) return redirect('offer') return redirect('offer') -
Problems with Django forms and Bootstrap
Im making a form in django, were I style it with Widgets: from django.forms import ModelForm, TextInput, EmailInput, NumberInput from .models import * class DateInput(forms.DateInput): input_type = 'date' class PatientForm(ModelForm): class Meta: model = Patient fields = ['fornavn', 'efternavn', 'email', 'birthday', 'id_nr'] widgets = { 'fornavn': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Fornavn' }), 'efternavn': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Efternavn' }), 'email': EmailInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Email' }), 'birthday': DateInput(attrs={ 'format':'DD/MM/YYYY', 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'dd/mm/yyyy', }), 'id_nr': NumberInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Ønsket patientnummer' }), } However when inserting the form in the template with a Bootstrap Card styling, the form isnt rendering, and I'm left with only the names of the input fields, no fields for input and even missing the submit button. Template as follows: {% load crispy_forms_tags %} {% block content %} <div class="container p-5"> <div class="row p-5"> <div class="card p-3" style="width: 40rem;"> <h3 class="p-2 m-1">Opret patient</h3> <hr> <form action="" method="post" class=""> {% csrf_token %} {{ form|crispy }} <input type="submit" name="Opret" class="float-end"> </form> </div> </div> </div> {% endblock %} Any suggestions? -
How to make model.ImageField as mandatory in django admin?
I need to make upload image in django admin panel as a mandatory field, is there any possibility? Here what i did. **Model.py** class ContentData(models.Model): title = models.CharField(max_length=100,null = True) description = models.TextField(null=True) image = models.ImageField(upload_to="uploads", blank=True) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
Django graphene: add field resolver with saving of the type inherited from the model
I have a node inherited from the model: class OrderModel(models.Model): FAILED = "failed" REQUIRES_PAYMENT_METHOD = "requires_payment_method" ORDER_STATUSES = ( (FAILED, FAILED), (REQUIRES_PAYMENT_METHOD, REQUIRES_PAYMENT_METHOD), ) STATUSES_MAP_FOR_NOT_ADMINS = { REQUIRES_PAYMENT_METHOD: FAILED, } status = models.CharField(_('status'), choices=ORDER_STATUSES, default=NEW_ORDER, max_length=255) class Meta(object): db_table = 'order' verbose_name = _('order') verbose_name_plural = _('orders') class OrderNode(PrimaryKeyMixin, DjangoObjectType): status = graphene.String def resolve_status(self, info): if info.context.user.is_admin: return self.status return self.STATUSES_MAP_FOR_NOT_ADMINS.get(self.status, self.status) class Meta: model = OrderModel filter_fields = GrantedOrderFilter.Meta.fields interfaces = (relay.Node, ) I want to add a custom status resolver to map statuses displayed for the users. But with the current implementation, I'm losing the typing for the status field. Is there any way I can save typing generated from the model and add the custom resolver? -
connection to server at "localhost" , port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
I am doing a project using django rest framework. It was working ok, but at the moment I am getting error connection to server at "localhost"(127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I knew that the problem with postgresql. Because I've tried to connect it with pgadmin, and also gives me this error. I am using Ubuntu OS, when I checked ubuntu not listening port 5432. postgresql.conf # - Connection Settings - listen_addresses = '*' # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for > # (change requires restart) port = 5432 # (change requires restart) max_connections = 100 # (change requires restart) #superuser_reserved_connections = 3 # (change requires restart) #unix_socket_directories = '/var/run/postgresql' # comma-separated list > # (change requires restart) When I run service postgresql status, it says following. ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor pr> Active: active (exited) since Tue 2022-05-17 09:22:03 +05; 1h 9min ago Process: 6270 ExecStart=/bin/true (code=exited, status=0/SUCCESS) Main PID: 6270 (code=exited, status=0/SUCCESS) May 17 09:22:03 mirodil-vivobook systemd[1]: Starting PostgreSQL RDBMS... May 17 09:22:03 mirodil-vivobook systemd[1]: Finished PostgreSQL RDBMS. Here is … -
How to get ETA when fetch data from postgres?
I have Django project and in some view users can select what data their want to fetch from DB. But when query is large and fetching take some time ~ 10min users dont know there is an error or just fetching time. How can i get aproximatelly execution time when fetching data from postgres? And how can i display that?