Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while integrating google OAuth with superset
To integrate Google authentication into my Superset application, which is running on a specific IP address, I followed these steps: Created an OAuth client ID on the Google Cloud Platform. To create it, a JavaScript Authorized Origin is required, which is basically the application's URL. Since my Superset application does not have a domain, I masked the <superset-IP> with a random domain (http://localtesting.com) in my local etc/hosts file. I used this masked domain in the Google Console for creating the client ID. Updated the superset_config.py file with the client ID, client secret, and app domain. Here is the file for your reference: from flask_appbuilder.security.manager import AUTH_OAUTH ENABLE_PROXY_FIX = True AUTH_TYPE = AUTH_OAUTH OAUTH_PROVIDERS = [ { "name": "google", "icon": "fa-google", "token_key": "access_token", "remote_app": { "client_id": "<ClientId", "client_secret": "<ClientSecretKey>", "api_base_url": "https://www.googleapis.com/oauth2/v2/", "client_kwargs": {"scope": "email profile"}, "request_token_url": None, "access_token_url": "https://accounts.google.com/o/oauth2/token", "authorize_url": "https://accounts.google.com/o/oauth2/auth", "authorize_params": {"hd": "http://locatesting.com"} }, } ] AUTH_ROLE_ADMIN = 'Admin' AUTH_ROLE_PUBLIC = 'Public' Restarted the VM where superset is hosted. After completing these steps, I encountered a 502 Bad Gateway error. My Superset application is using an Nginx server. Is this issue somehow associated to nginx or anything wrong in masking of IP in my local machine -
fcm-django add badge to Aps for ios platform
I use fcm-django library def get(self, request, *args, **kwargs): user = request.user devices = FCMDevice.objects.filter(user=user) body_data = { "title": "Title text", "body": "Click to explore more", } extra_data = {"type": "some information", "link": "https://google.com", "badge": str(10)} for device in devices: try: if device.type == "ios": device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data)) else: device.send_message(Message(data={**body_data, **extra_data})) except Exception as e: return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK) I need add badge value to Aps for ios. I've tried apns = { "badge": 10, } device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data, apns=Aps(apns))) But got error and no PN. How can I do it correctly? -
Django- getting the value of 'models.DateField(default=datetime.datetime.today)' in view
I have this model: models.py: class myModel(models.Model): a = models.ForeignKey(P,on_delete=models.CASCADE) ... **date = models.DateField(default=datetime.datetime.today)** In the views.py, I get the data of "date" field: views.py from appX.models import myModel from datetime import datetime ... def my_items(request): ... got_date = myModel.objects.get(id = 1).date got_date_2 = datetime.strptime(got_date, "%YYYY-%MM-%d") But python throws the following error: time data '"2024-02-14"' does not match format '%YYYY-%MM-%d' What "format" should I use ? Thanks. -
Different outputs between Django Server and PyCharm
I am facing an issue that I get different outputs running the same code throw PyCharm and throw the Django Server. PyCharm gives the output expected and needed, so it is an issue to fix. Because I only use PyCharm for testing. The input string: # HTML HTML is a markup language that can be used to define the structure of a web page. HTML elements include * headings * paragraphs * lists * links * and more! The most recent major version of HTML is HTML5. The Code is: # A list of simple markdown and there html aquvalents. # First element is the inner html/markdown second is the whole markdown, third is the starting html tag and fourth the closing html tag regex_hugging_html = [ [r"(?<=^#{1})[^#][^\n]*$", r"^#{1}[\s]*[^#][^\n]*$", "<h1>", "</h1>"], # heading first level (#) [r"(?<=^#{2})[^#][^\n]*$", r"^#{2}[\s]*[^#][^\n]*$", "<h2>", "</h2>"], # heading second level (##) [r"(?<=^#{3})[^#][^\n]*$", r"^#{3}[\s]*[^#][^\n]*$", "<h3>", "</h3>"], # heading third level (###) [r"(?s)\*\*(.*?)\*\*", r"(?s)\*\*.+?\*\*", "<b>", "</b>"], # boldface (** **) [r"(?s)__(.*?)__", r"(?s)__.+?__", "<b>", "</b>"], # boldface (__ __) [r"(?s)\n{2}(.+?)(?=\n{2}|\Z)", r"(?s)(\n{2}.+?)(?=\n{2}|\Z)", "<p>", "</p>"], # paragraphs (blank line) ] def markdown_to_html(markdown): html = markdown for replacer in regex_hugging_html: # Find all occurances of the markdown expression for substr in re.compile(replacer[0], … -
How to save data from CKEditor via Django Rest Framework using javascript (vanilla)
Im writing an application that has a function for adding a document. For this reason i needed some rich text editor for formatting the documents. so here is my views.py for rendering my html: def add_document_view(request): if request.user.is_authenticated: categories = Category.objects.all() languages = get_language_choices() context = {"allCategories":categories, "form":PostForm, "languages":languages} return render(request, "documents/add-document.html", context) return JsonResponse({"status":"500 Auth Error"}) add-document.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add Document</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> <h1>Add Document</h1> <hr> <form method="POST" action="#"> {% csrf_token %} <div class="form-group"> <label for="title">Header:</label> <input type="text" class="form-control" id="header" name="header" placeholder="Enter document header" required> </div> <div class="form-group"> <label for="category">Category:</label> <select class="form-control" id="category" name="category" required> <option value="" disabled selected>Select category</option> {% for category in allCategories %} <option value="{{ category.id }}">{{ category.title }}</option> {% endfor %} </select> </div> <div class="form-group"> {{form.media}} {{form.as_p}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script src="https://cdn.ckeditor.com/ckeditor5/38.0.0/classic/ckeditor.js" defer></script> </body> </html> models.py from django.db import models from ckeditor.fields import RichTextField from simple_history.models import HistoricalRecords from .utils import get_language_choices class Category(models.Model): title = models.CharField(max_length = 64, unique = True) def __str__(self): return self.title class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' … -
Unexpected Behavior with Concurrent ModelViewset Requests
I'm experiencing an issue with a Django Rest Framework ModelViewSet endpoint named projects/. I have a set of requests (PATCH, DELETE, then GET) that are causing unexpected behavior. The timeline of requests and responses is as follows: PATCH request at 14:45:09.420 DELETE request at 14:45:12.724 3.DELETE 204 response at 14:45:12.852 PATCH 200 response at 14:45:13.263 GET request at 14:45:13.279 GET 200 response at 14:45:13.714 All responses indicate success. However, the GET response, which follows a DELETE, includes the supposedly deleted model. If I call the GET endpoint a bit later, the deleted model is no longer listed. This behavior suggests a potential race condition or a caching issue, where the PATCH operation completes after the DELETE, or the GET request returns a cached list not reflecting the deletion. The view, serializer and model code are all pretty vanilla: class ProjectViewSet(ModelViewSet): parser_classes = (MultiPartParser, FormParser, JSONParser) queryset = Project.objects.all() serializer_class = ProjectSerializer pagination_class = ProjectPagination class ProjectSerializer(serializers.ModelSerializer): creator = UserUUIDField(default=serializers.CurrentUserDefault()) image = serializers.ImageField(required=False) class Meta: model = Project fields = "__all__" class Project(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) creator = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) image = models.ForeignKey( wand_image, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="projects" ) One model has a … -
Django project setup using django-configurations
I'm very new to Django and I'm trying to set up a new project, using django-configurations to manage the config of Development, Staging and Production environments. https://pypi.org/project/django-configurations/ I followed the quickstart guide, but after setting things up I keep getting this error when running manage.py startserver: File "[path_redacted]/django_test/.venv/lib/python3.11/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. This is a brand new blank project, no apps and no changes whatsoever from the default project setup. I only set up django-configurations as per the quickstart guide. I have manage.py set up as per the guide: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_test.settings') os.environ.setdefault('DJANGO_CONFIGURATION', 'Development') try: from configurations.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Then do the same with settings.py, by adding the below class just after the default definition of BASE_DIR: class Development(Configuration): DEBUG = True The default installed apps are there and untouched, including the admin app: INSTALLED_APPS … -
why the django filter query not accepting the passed values?
I have below program that is suppose to execute objects.filter query on two columns and based that fetch the data of 3rd column. class API(GenericAPIView, ListModelMixin, CreateModelMixin): serializer_class = [DummySerializer, ATSerializers] def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.org = None self.ent = None def post(self, request, *args, **kwargs): org = request.data.get("org") ent = request.data.get("ent") self.org = org self.ent = ent if self.org is None or self.ent is None: return Response("Both fields are required to fetch token..", status=status.HTTP_400_BAD_REQUEST) queryset = self.get_queryset() print("[QUERY SET] :", queryset) if not queryset: return Response("No matching records found.", status=status.HTTP_404_NOT_FOUND) lnk_token = list(queryset.values_list('link_token', flat=True)) return Response({"lnk_tkn": lnk_token}, status=status.HTTP_200_OK) def get_queryset(self): org = self.org ent = self.ent print("this is get_queryset bloc") if org is None or ent is None: return tbl.objects.none() else: print(self.org, self.ent) filter_token = tbl.objects.filter(org=org, ent=ent) print(filter_token) lnk_token = filter_token.values_list('tkn', flat=True) return lnk_token def list(self, request, *args, **kwargs): queryset = self.get_queryset() if not queryset: return Response(f"Both IDs are the required fields.....") return Response( { "token": queryset } ) I am receiving the values of org and ent from request body in my post method and passed onto the get_queryset() GET method. Then the values are supposed to be passed to filter_token = tbl.objects.filter(org=org, ent=ent) That is when … -
Django redirect() returns 302
So, i'm trying to make a calculator with user log in and sign up funcionalities. The calculator is in an app called "calc" and the log in/sign up is in another app called "cadastro". When the user log in, the view should redirect to the calc index view, but i get a 302 code in the terminal instead. This is my log in view: def login(request): form = formularioLogin() if request.method == "POST": user = authenticate(username = request.POST.get("username"), password = request.POST.get("password")) if user: login_django(request, user) return redirect("calc:index") return JsonResponse({"erro": "Usuário ou senha incorretos."}) return render(request, "cadastro/login.html", {"form": form}) This is my calc:index view: @login_required(login_url="cadastro:login") def index(request): historico = calculos.objects.order_by("-pk") if request.method == "GET": if "apagar" in request.GET: apagar = request.GET.get("apagar") apagar = calculos.objects.filter(pk=apagar) apagar.delete() return render(request, "calc/index.html", {"historico": historico}) elif "conta" in request.GET: conta = request.GET.get("conta") if re.search("^[0-9.+*\-]+$", conta): res = str(eval(conta)) if conta != res: # create = calculos.objects.create(calculo=conta, resultado=res) return render(request, "calc/index.html", {"conta": res, "historico": historico}) return render(request, "calc/index.html", {"conta": res, "historico": historico}) return render(request, "calc/index.html", {"erro": "erro", "historico": historico}) return render(request, "calc/index.html", {"historico": historico}) This is my calc.urls: app_name = "calc" urlpatterns = [ url(r"^$", views.index, name="index"), ] And this is my cmd: CMD I'm using Django … -
Django Cron Jobs
quiero saber que es lo mejor para hacer cronjobs en django a dia de hoy 2024, ya que me encuentro con librerias que satisfacen esta necesidad pero que no estan actualizadas con ultimas versiones del 2011 o 2006 Saludos esperaba una cronjob que tuviera un disparador en django -
Django Async Add to many-to-many field
I am trying to use this piece of code to update a many-to-many field within an async function: async def get_last_message_id() -> int: last_message = await Message.objects.all().alast() if last_message: await last_message.read_by.aadd(request.user) return last_message.id if last_message else 0 However, I get the following error: TypeError: 'async_generator' object is not iterable What am I doing wrong here? Thanks! -
Django TestCase assert query returns object
Not sure why I can't find documentation on this but: def test_invalid_trip_location_field_value(self): trip_location_field = TripLocationField.objects.filter( name='Fiji' ).first() self.assertEqual(len(trip_location_field), 1) This gives me TypeError: object of type 'TripLocationField' has no len(). How can I assert that the object exists? -
Django group by substring on a field
I have a Django, PostgreSQL project. I want to perform a group by on substring from a field. Ex I have a model as Model1 and its column as name. The value in the column can be: ABC-w-JAIPUR-123 XYZ-x-JAIPUR-236 MNO-y-SURAT-23 DEF-q-SURAT-23 From the above values in name field, I want to group by second occurrence of - and ending with - in our case it would be: "JAIPUR", "SURAT" Please let me know how to achieve this in Django. -
Rename drf_spectacular API end points
I'm using drf_spectacular with Django Rest Framework to generate API documentation. However, I need to customize the names of the endpoints displayed in the Spectacular API documentation. Could someone please advise on how to achieve this? Thank you! enter image description here I try see SPECTACULAR_SETTINGS but didn't find something usefull -
How to create a advanced search bar using Django?
Good day, Currently i m working on a project, it is my first time doing such. I'm on the back end and do some stuff on the front end to make it more intuitive. I chose django because its straightforward, but i'm having some difficulty creating an advanced search. Here is the problem: First i made 2 scrips to import full texts to a table on postgresql. Lets call this table trt_text(in this this table there are 2 texts each It has the title and content. Then i did another script to put another .txt on postgresql. Lets call this table trt_keyconcepts. This table has 3 "columns" the first one contains a word/sentence from the trt_text, the second one contains what type of word/sentence it is, and the third column is integer, it contains the number that said word appears on the text. Using ChatGPT these views were made: views.py: def advanced_search(request): return render(request, 'app/advanced_search.html') def advanced_search_results(request): if request.method == 'GET': entity_name = request.GET.get('entity_name', '') entity_type = request.GET.get('entity_type', '') frequency = request.GET.get('frequency', '') search_results = Text.objects.all() if entity_name: search_results = search_results.filter(content__icontains=entity_name) if entity_type: search_results = search_results.filter(textfile__name=entity_name) if frequency: search_results = search_results.filter(textfile__frequency=int(frequency)) return render(request, 'app/advanced_search_results.html', {'search_results': search_results}) return redirect('advanced_search') At this … -
Performing subqueries in Django ORM from two different databases
I have two models Model1 and Model2 where table for Model1 is defined in db1 and for Model2 it is defined in db2. I have router set up for read operations from both the databases which is working fine for simple read operations, but for complex annotations and Subqueries I am unable to figure out how to make the ORM understand which DB to search the tables in. This is what I am trying to do right now: from django.db.models import OuterRef, Subquery from app1.models import Model1 from app2.models import Model2 model1_qs = Model1.objects.using('db1').filter(id=OuterRef('context_id')) model2_qs = Model2.objects.using('db2').all() res = model2_qs.objects.using('db1').annotate( model1_value=Subquery(model1_qs.values('value')[:1]) ) I am expecting res to be an annotated queryset with model1_value fetched from db1. But instead getting a table not found error. Django is trying to look for Model1 in db2... P.S. I need to perform such queries in existing views of a large project, so using raw SQL queries is not really a feasible option for me. -
Default going to homepage in django
Hello to all the friends, I am a Django developer and I want to go to a specific url with slug, but when I try that, automatically the server goes to homepage, I don't know that what should I do. views.py def ChangeQuizInfol(request,slugp): print("changequizinfo is running.") if request.method == 'POST': print("is post.") form = NewAzmoonForms() # else: # form = NewAzmoonForms(request.POST, instance=quiz) # if form.is_valid(): # form.save() else: quiz = QuizStudent.objects.get(slug=slugp) print(quiz) questions = Questions.objects.filter(quiz_id=quiz.id) print(questions) try: try: co = { "quiz":quiz, "form":form, "questions":questions } except: co = { "form":form, } except: co = { } return render(request, "komaki/per.html", co) def ListsTeacherQuizes(request): print("list is running.") user = request.user quizes = QuizStudent.objects.filter(author_id = user.id) return render(request, "komaki/lists.html",{"quizes":quizes}) urls.py from django.urls import path from . import views app_name = 'komaki' urlpatterns = [ path('',views.avaL,name='avaL'), path('create/',views.create_question,name='create_question'), path('start/',views.startazmoon,name='startazmoon'), path('azm/',views.azmoonpage,name='azmoonpage'), path('Sokht/',views.NeveshtanAzmoon,name='NeveshtanAzmoon'), path("NeveshtanQuestion/",views.NeveshtanQuestion,name='NeveshtanQuestion'), path('ShowQuizStudents/',views.ShowQuizes,name='ShowQuizes'), path('<slug>',views.EachQuiz,name='EachQuiz'), path("equation/", views.Equation, name='Equation'), path("geo/",views.Geo, name='Geo'), path("Chang/", views.Chang, name='Chang'), path("AskAndAnswer/",views.AskAndAnswer, name="AskAndAnswer"), path("Pish/",views.Pishrafteh, name="Pishrafteh"), path("UploadVideo/",views.Videoupload,name="Videoupload"), path("Lists/",views.ListsTeacherQuizes, name="ListsTeacherQuizes"), path("<slugp>", views.ChangeQuizInfol, name="ChangeQuizInfol"), ] lists.html {% extends 'base.html' %} {% block head %} {% endblock %} {% block body %} {% for quiz in quizes %} <div class="quiz{{ quiz.id }}" style="margin-top: 100px;"> <a href="{% url "komaki:ChangeQuizInfol" slugp=quiz.correct_slug %}">{{quiz.name}}</a> </div> {% endfor %} {% endblock %} per.html … -
When creating a html table in django, the layout of the data is incorrect
I wanna make a table like this image but i have a few problem. Problem 1: When you look at white background you will see 1,2,3,4 numbers. 1 and 2 same and 3 and 4 same. I don't want twice of each symptom. I want unique symptoms in the first column. Problem 2: Same problem like problem 1. Remedy names must be unique. And i made red arrows near the points. I want only one remedy_name and all points must be under the remedy_name. And here is my codes... from django.db import models from django.utils import timezone from django.contrib.auth.models import User class UserSymptom(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) symptom = models.ForeignKey(Symptom, on_delete=models.CASCADE) date = models.DateField(default=timezone.now) time = models.TimeField(default=timezone.now) def __str__(self): return f"{self.user} - {self.symptom.name} - {self.date} {self.time}" class RemedyRubrics(models.Model): remedy_name = models.ForeignKey(RemedyName, on_delete=models.CASCADE) rubric = models.TextField() point = models.IntegerField() def __str__(self): return f"{self.remedy_name.remedi_adi} - {self.rubric} - {self.point} " class Meta: verbose_name_plural = 'Remedy Rubrics' views code def homeopati4(request): user_symptoms = UserSymptom.objects.filter(user=request.user) matching_remedies = [] for symptom in user_symptoms: # Semptom adındaki ilk harfi kontrol et first_letter = symptom.symptom.name[0] if first_letter.lower() in ['ö', 'ü', 'ş', 'ı']: # Semptom adı Türkçe karakterle başlıyorsa, ilk harfi atla ve kalan kısmı içeren rubrikleri bul symptom_name_without_first_letter … -
How can I check payment status automatically?
I’m sending post requests to create a payment, then after a little time I send get request to check payment status. I don’t it’s correct or no. I’m finding a decision to automatize it. Is any ways to solve it? -
How can I display "Recent actions" in my project [duplicate]
How can I display "Recent actions" in my project for a specific application like the one in Django Panel For example, when adding a new product, deleting a product, or modifying a product Is there a library to add this feature? -
problem with gunicorn [ERROR] Exception in worker process
A month ago I rented a Shared line cloud server on Selectel and uploaded a project there, but literally a couple of days later this error appeared (see file). Since I was unable to resolve the error, I had to reset the server and start the site again. And again, not even a day had passed before the same error appeared. Feb 14 09:19:21 it-want systemd[1]: Started gunicorn daemon. Feb 14 09:19:21 it-want gunicorn[565]: [2024-02-14 09:19:21 +0000] [565] [INFO] Starting gunicorn 21.2.0 Feb 14 09:19:21 it-want gunicorn[565]: [2024-02-14 09:19:21 +0000] [565] [INFO] Listening at: unix:/run/gunicorn.sock (565) Feb 14 09:19:21 it-want gunicorn[565]: [2024-02-14 09:19:21 +0000] [565] [INFO] Using worker: sync Feb 14 09:19:21 it-want gunicorn[566]: [2024-02-14 09:19:21 +0000] [566] [INFO] Booting worker with pid: 566 Feb 14 09:19:21 it-want gunicorn[567]: [2024-02-14 09:19:21 +0000] [567] [INFO] Booting worker with pid: 567 Feb 14 09:19:21 it-want gunicorn[568]: [2024-02-14 09:19:21 +0000] [568] [INFO] Booting worker with pid: 568 Feb 14 09:19:22 it-want gunicorn[568]: [2024-02-14 09:19:22 +0000] [568] [ERROR] Exception in worker process Feb 14 09:19:22 it-want gunicorn[568]: Traceback (most recent call last): Feb 14 09:19:22 it-want gunicorn[568]: File "/home/itwant/itwant/venv/lib/python3.9/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker Feb 14 09:19:22 it-want gunicorn[568]: worker.init_process() Feb 14 09:19:22 it-want gunicorn[568]: … -
django reports invalid form with request method POST
I render the html when login url is hit and then invoke another url to handle submitted form. Following is the method that processes the form - def process_loginform(request): print(request.method) form = LoginForm(request.POST) if form.is_valid(): print("Valid form") else: print("Invalid form") return HttpResponseRedirect("/login/welcome/") The Login form html - {% extends 'base.html' %} {% block content %} Hello <form action="/login/process_loginform/" method="post"> {% csrf_token %} <label for="username">Username</label> <input id="username-val" type="text" name="username-name" /> <label for="password">Password</label> <input id="password-val" type="password" name="password-name" /> <input type="submit" value="Login" /> </form> {% endblock %} forms.py - from django import forms class LoginForm(forms.Form): username = forms.CharField(label="username", max_length=64) password = forms.CharField(label="username", max_length=64) Console output - (ubuntu-7Wf190Ea) ubuntu@ip-172-31-4-242:~/ka$ ./manage.py runserver 0.0.0.0:1890 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). February 14, 2024 - 10:28:18 Django version 4.2.10, using settings 'ibs.settings' Starting development server at http://0.0.0.0:1890/ Quit the server with CONTROL-C. [14/Feb/2024 10:28:23] "GET /login/ HTTP/1.1" 200 729 request: <WSGIRequest: POST '/login/process_loginform/'> POST **Invalid form** I'm following this documentation - https://docs.djangoproject.com/en/5.0/topics/forms/ Why is the form invalid ? I tried to google the error, no luck. I was expecting to understand why is my login handler reporting an invalid form. Thanks -
Language translator [closed]
I need to create a website in django I wanted to add a settings in that, like language translation I needed only the content has to be changed the name remains same (eg: the OnePlus node blue tide this will remains same )and this change will only effect the headers,nav etc ,I use i18 n But it doesn't give proper output I need a language translation settings only the headers footers change -
Overriding ordering of related object in queryset
I have two related models, Customer and Config. Customer is set to automatically order by order. Now I want to select the latest Config entry for each distinct set of customer and report_type. That's usually accomplished by an order_by on all the distinct fields as well as a descending ordering on the date, followed by a distinct on the distinct fields. However, since Django sneaks in another ORDER BY on Customer.order in the eventual query, DISTINCT says its arguments don't match those of ORDER BY. I'd like to override the ordering on Customer in this case. class Customer(models.Model): name = models.TextField() order = models.IntegerField() class Meta: ordering = ["order"] class Config: customer = models.ForeignKeyField(Customer) created = models.DatetimeField() report_type = models.TextField() cfgs = ( Report.objects .filter() .order_by("customer", "report_type", "-created") .distinct("customer", "report_type") ) There is a solution, albeit one I feel is a little bit hacky. By doing the order_by and distinct calls on the customer_id field, it won't try to LEFT JOIN Customer and also forego its ordering. The problem here is that that means I'll have to make another database call to fetch the Customer objects. It's not a big deal, but if I could override the ordering on Customer, … -
External trigger (PostgreSQL) for Django application
I have a difficulty with my Django application: I have two databases, and I would like that when an instance is added to PostgreSQL, a Django function is triggered to work on the default database. Could you list the steps to follow? Thank you. I have created a trigger in the external database, but I can't get Django to react despite implementing pgtrigger.