Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is necessary to learn SQLAlchemy when using Django?
I'm a intermidiate Django Developer. All the Database and Tables creations are done with Django Models. I was wondering when should a programmer used SQLAlchemy, which scenarios are the best to use this instead of the regular Django Models? -
My Delete modalForm always delete the first object in the dataModel?(Django)
I made a modal using bootstrap to delete user entries in a list view so i had to iterate with a for loop in the template so it always deletes the first object, also it never closes. How I can make the button of each entry unique that it deletes this object only. here's the modal : {% for obj in patients %} <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete" aria-hidden="true"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete patient!</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Are you sure you want to delete this patient?</p> </div> <div class="modal-footer"> <form method="POST" action="{% url 'patients:patient_delete' obj.pk %}"> {% csrf_token %} <input class="btn btn-danger" value="Yes" type="submit" > <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </form> </div> </div> </div> </div> {% endfor %} and here's my triggering button : <button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Delete</button> -
Create a Bootstrap accordian for items in a python for loop
I am trying to create a Bootstrap accordian for a list of items in a Django database. When rendered, currently my code will only collapse and expand on the first item in the for loop. For other items, when I click on these the first item expands/collapses, not the item being clicked on. Looking for a solution please. <div class="panel-group"> <div class="panel panel-default"> {% for issue in issues %} <div class="panel-heading"> <div class="panel-title"> <a data-toggle="collapse" data-target="#collapse1"><h3><i class="fas fa-chevron-down"></i> {{ issue.title }}</h3></a> </div> </div> <div id="collapse1" class="panel-collapse collapse"> <p><strong>Type: </strong>{{ issue.type }}</p> <p class="issue-description"><strong>Description: </strong>{{ issue.description }}</p> <p><strong>Requested By: </strong>{{ issue.requested_by }}</p> <p><strong>Date Created: </strong>{{ issue.date_created }}</p> <p><strong>Status: </strong>{{ issue.status }}</p> <p><strong>Date Completed: </strong>{{ issue.completed_date }}</p> <p><strong>Upvotes: </strong>{{ issue.upvotes }}</p> </div> {% endfor %} </div> </div> -
How do i filter a foreign key to get only specefic values in Django?
I have a model where I am creating a company. The model takes the name of a company, if the company has any parents ie: Quicktrip # 1345 parent company is Quicktrip Corp. How the parent is being made is that any company being created has the potential to be a parent. How do i filter through the list of companies so only certian ones are set as parent? I tried to check if the company has more than one location then its a parent but that did not work. parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) With the current code it sets all my companys i created to be a parent. -
How to pass user object into forms field
I am trying to pass a user object from my views.py into my forms.py to the user field and save a new object. The user field is a foreign key in the model. I can do a select dropdown widget like with the jobSite field but im trying to automatically pass the user object on submit instead of the current user having to select another user from the drop down. I've tried passing the user through as an initial key value from the views.py like so form = entryTime(request.POST, initial={'user': user}) I've tried a few different variations of that but so far haven't been able to successfully get the user object to save to the user field. forms.py class entryTime(ModelForm): class Meta: model = Entry fields = [ 'user', 'start_time', 'end_time', 'jobSite', ] widgets = { 'start_time': DateTimePicker( options={'useCurrent': True, 'collapse': False}, attrs={'append': 'fa fa-calendar', 'icon_toggle': True} ), 'end_time': DateTimePicker( options={'useCurrent': True, 'collapse': False}, attrs={'append': 'fa fa-calendar', 'icon_toggle': True} ), 'jobSite': Select() } def __init__(self, *args, **kwargs): super(entryTime, self).__init__(*args, **kwargs) self.fields['start_time'].widget.attrs['class'] = 'form-control' self.fields['end_time'].widget.attrs['class'] = 'form-control' self.fields['jobSite'].widget.attrs['class'] = 'form-control' views.py def addTimeEntry(request, userId): user = User.objects.get(pk=userId) form = entryTime() if request.POST: form = entryTime(request.POST) if form.is_valid(): print('form is valid') args={"form":form} … -
Annotate filtered queryset to another queryset
Okay, what I have. Tour — main model, TourTranslation — model for translated Tour information and TourArrival — tour arrivals (dates when each tour starts) In my view I get all TourTranslation's for current language. And then I need to annotate to each object in this queryset another filtered queryset like TourArrival.objects.filter(tour=<CURRENT_OBJECT_TOUR_FROM_TOURTRANSLATION>, date__gt=timezone.now) I know that I can just use setattr() method and iterate all over TourTranslation.objects.filter(language=<CURRENT_LANGUAGE>) and manually add all TourArrivals, but it does query each time, so summary it will be len(TourTranslation.objects.filter(language=<CURRENT_LANGUAGE>)) queries per user request and it is very much. How can I do it by doing one query? models.py (to undestand models' structure) class Tour(models.Model): class Meta: verbose_name = "тур" verbose_name_plural = "туры" REGION_CHOICE = ( ('e', 'Европа'), ('b', 'Беларусь') ) COLOR_CHOICE = ( ('y', 'Жёлтый'), ('g', 'Зелёный'), ('b', 'Голубой'), ('r', 'Красный') ) color = models.CharField(max_length=1, default='b', choices=COLOR_CHOICE, verbose_name="Цвет страницы") region = models.CharField(max_length=1, default='b', choices=REGION_CHOICE, verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Внутреннее название") image = models.ImageField(upload_to="tours/static/img/", verbose_name="Основное изображение") duration = models.PositiveIntegerField(verbose_name="Длительность (в днях)") seat = models.PositiveIntegerField(verbose_name="Количество мест") cost = models.PositiveIntegerField(verbose_name="Стоимость тура в BYN") images = models.ManyToManyField('TourImage', verbose_name="Фотографии с туров") def __str__(self): return self.name class TourArrival(models.Model): class Meta: verbose_name = "заезд" verbose_name_plural = "заезды" ordering = ['date'] tour = … -
how to create model instance with recursive foreign key that cannot be null
In my django app I have two Model in a one-to-many relationship: Term and TermName (Term has many TermName). I want to keep track in Term of a particular TermName instance, say TermName models are name alias or the related Term model, but one of them is the "reference" name alias. For this I have added a one-to-one relation between the two Models. Here is the code: class TermName(HpoStatus): name = models.CharField(max_length=255) term = models.ForeignKey( 'Term', on_delete=models.CASCADE ) class Term(models.Model): ref_termname = models.OneToOneField( TermName, on_delete=models.DO_NOTHING, related_name = 'reference_of_term', ) Problem is if I create a new Term instance, django complains that ref_termname cannot be null. However sames goes if I want to create the "reference" TermName beforehands; it now complains about term being null ... My workaround is to let ref_termname be null (i.e. use null=True field option). But for my model design I would like to make it not nullable. Can this be possible? thanks for your help! -
Filtering using multiple foreign keys in Django
So I already have an Exam stored, and able to filter out the questions that are from only from that exam, however, how would I only print out the answer choices to their designated question? When I try to print it out in my template all of the answer choices print under each of the questions instead of filtering out, would I need a for loop/if statement within the template to correctly do this or? I've tried a number of things and the Docs most likely have the answer but I just need help understanding from django.db import models class Exam(models.Model): name = models.CharField(max_length=64, verbose_name=u'Exam name', ) slug = models.SlugField() def __str__(self): return self.name class Question(models.Model): question_text = models.CharField(max_length=256, verbose_name=u'Question\'s text') is_published = models.BooleanField(default=False) exam = models.ForeignKey(Exam, related_name='questions') def __str__(self): return "{content} - {published}".format(content=self.question_text, published=self.is_published) class Answer(models.Model): text = models.CharField(max_length=128, verbose_name=u'Answer\'s text') is_valid = models.BooleanField(default=False) question = models.ForeignKey(Question, related_name='answers') def __str__(self): return self.text How would I be able to print the Exam on the template, and filter it in order to print questions, and the answers related to it from the foreign key -
(Django) Solve Lazy Reference pointing to deleted model
I accidentally deleted a model in an app before removing all the relationships pointing to it. Now I am getting a lazy reference error since the model is already deleted. I am using Django 2.2 with PostgreSQL. So I have a Core app with a model called Analysis inside it. I had another app named Projects, and inside I have a model named Project with m2m relationship pointing to Analysis of Core like below. core_analysis= models.ManyToManyField(core.Analysis,verbose_name="Core Analysis", blank=True). I deleted Analysis from Core, and removed m2m core_analysis from Project. Accordingly, django created DeleteModel migration in Core and RemoveField migration in Projects. However, I only ran migration in Core, and now when I tried to resume migration Project throws Lazy Reference Error. ValueError: The field projects.Project.core_analysis was declared with a lazy reference to 'core.analysis', but app 'core' doesn't provide model 'analysis'. Is there a way to fix this issue while not having to lose any data. -
Searching through Django admin spinner selector
Is it possible to search in Django admin spinners or selectors? When there is a lot of items it becames a nightmare: -
How to create robust composite primary key in Django?
I would like to create in Django model a composite primary key, which is a text prefix and then an index within that prefix. For example, I would like that the model upon save() generates this order: prefix - id ABC - 1 ABC - 2 ABC - 3 ABC - 4 XYZ - 1 ABC - 5 XYZ - 2 XYZ - 3 ABC - 6 XYZ - 4 XYZ - 5 etc. I have already tried to create a metadata with unique_together = [['Prefix', 'Id']] That works for uniqueness, but it does not compute the lowest id per prefix, the id is just always incremented: prefix - id ABC - 1 ABC - 2 ABC - 3 ABC - 4 XYZ - 5 ABC - 6 XYZ - 7 XYZ - 8 ABC - 9 XYZ - 10 XYZ - 11 etc. class Invoice(models.Model): prefix = models.CharField(max_length=12, default='') invoice_ref = models.CharField(max_length=40, default='') class Meta: unique_together = [['prefix', 'id']] I could compute the id in the overloaded save() method, however how much robust is that approach? There would be several non-atomic queries to database: def save(self): try: m = Invoice.objects.last(prefix=self.prefix) self.id = m.id + 1 except Exception as e: … -
Django - In the admin page, how do I widen the dropdown choices?
How do I increase the width of the django foreign key dropdown text? For example, I want to be able to see the full line of text: How many possum? - I have known for a long time that, while wealth is unlikely to decrease happiness, one can acquire happiness for almost no financial cost. Currently, the above text is abridged in the dropdown: !(https://i.imgur.com/BTVSko3.png) As background information, the dropdown shows foreign keys that are linked to other foreign keys. Code (truncated): admin.py @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): form = CustomQuestionAdminForm fieldsets = [ (None, {'fields': ['parent_option', 'question_bank', 'question_text', 'category', 'date_published']}), ] inlines = [OptionInline] list_display = ('question_text', 'category', 'date_published') search_fields = ['question_text'] class CustomQuestionAdminForm(forms.ModelForm): class Meta: model = Question fields = [ 'question_text', 'parent_option', 'question_bank', 'date_published', 'category' ] def __init__(self, *args, **kwargs): super(CustomQuestionAdminForm, self).__init__(*args, **kwargs) self.fields['parent_option'] = ModelChoiceFieldOptionsAndQuestionText( queryset=Option.objects.exclude(question=self.instance), required=False, ) Actual -> Dropdown display does not show all of the choice text (see screen shot above) Desired -> The dropdown display shows all of the choice text, preferably regardless of its length. -
How to show model field's in admin list view, but show only related models inside its detail / change form?
assume we have the following: Models.py class Father(models.Model): name = models.Charfield(...) ... class Child(models.Model): one = ForeignKey(Father, ...) ... class GrandChild(models.Model): one = ForeignKey(Child, ...) ... I registered all Father() objects in the admin, and it shows the father's name and other fields on the list page (works fine)... But when clicking it into the change form, I only want it to show all Child() and GrandChild() objects as if they were inline (according to each parent class), and to allow / disallow changing of those forms when hitting save... Keeping the Father() fields on this page as readonly is fine too, but not required. Normally, the easiest way is to use an inline, but I can't do that here. The problem is due to the @admin.register(Father) decorator, because when I change the ModelAdmin.form to the ChildForm(), it always gives an error saying the Father() fields are required: ERRORS: : (admin.E108) The value of 'list_display[0]' refers to 'a_field', which is not a callable, an attribute of 'FatherAdmin', or an attribute or method on 'app_name.Father'. Anyone know of any ways to do this?? I know I can do this by manually making my own views and templates, but I'm trying to … -
Django model reference to a postgres foreign table (clickhouse_fdw)
I have a Django project. I've connected a clickhouse table with a postgres table using clickhouse_fdw. It's working using psql commands, but now I want to access from django. I've added a new model for clickhouse table and ignored migrations and managment for it in django. Then in django shell I've tried: MyModel.objects.raw('SELECT * FROM mytable LIMIT 1')[0] and I get: ProgrammingError: permission denied for foreign table mytable Any suggestions? -
Country wise access restriction in Django project
When an user open any link of Django project, before open this link, I want to apply country wise restriction. Admin has right to add country in Database table, if country is available in table, then url will open otherwise it will show a message, restricted country -
Unable to display foreign key attribute on a django app
I have two models in my db. They are:- Modules Topics Topics is a foreign key of Modules. This is my models.py from django.db import models class Modules(models.Model): name = models.CharField(max_length=500,null=False) def __str__(self): return self.name class Topics(models.Model): modules = models.ForeignKey(Modules,on_delete=models.CASCADE) name = models.CharField(max_length=500) Here is my HTML code:- {% extends "algorithms/header.html" %} {% block content %} {% if all_topics %} <div class="row"> {% for topic in modules.topics_set.all %} <div class="col s12 m6"> <div class="card cyan lighten-4"> <div class="card-content black-text"> <span class="card-title"><b>{{ topic.name }}</b></span> <p>{{topic.algorithm_content|safe}}</p> </div> <div class="card-action"> <a href="/algorithms/{{ module_name }}/{{ topic.name }}/">View</a> </div> </div> </div> {% endfor %} </div> {% else %} <h3>The admin has not uploaded any courses yet</h3> {% endif %} {% endblock %} I am unable to see any data of 'Topics' model. -
wagtail error in postgres_search update_index
I'm migrating my site from wagtail 1.10/django 1.11/python 2.7 to wagtail 2.5.1/django 2.2.3/python 3.7. I've been using the wagtail postgres_search backend. All my tables migrated successfully except postgres_search. To get things to work on my development machine I had to drop the postgres_search table, re-run the postgres_search migrations, and then run update_index. On the server I did the same thing, but update_index throws an exception. The main difference between my machines is that I'm running Postgres 11 on my development machine, and stuck on 9.4 on the server. Whatever is causing this problem is also (I think) causing a TransactionManagementError whenever I try to save any changes to pages on the server. If I use the default database search backend on the server, everything works fine. I'm wondering if my problem could be related to this django ticket: https://code.djangoproject.com/ticket/30446 Any suggestions would be greatly appreciated. Here's my traceback: (venv) [aapa@web552 physanth2]$ python3.7 aapa/manage.py update_index Updating backend: default default: Rebuilding index physanth default: physanth.StandardIndexPage Traceback (most recent call last): File "aapa/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/base.py", line … -
How to take info from sub-object in request before validating in Django?
I'm writing an api in Django for which I use the django-rest-framework. I've got a simple model as follows: class PeopleCounter(models.Model): version = models.CharField(max_length=10) timestamp = models.DateTimeField(db_index=True) sensor = models.CharField(max_length=10) count = models.IntegerField() And I've got a serializer as follows: class PeopleCounterSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PeopleCounter fields = [ 'version', 'timestamp', 'sensor', 'count', ] When I post the following data to this endpoint it works great: { "version": "v1", "timestamp": "2019-04-01T20:00:00.312", "sensor": "sensorA", "count": 4 } but unfortunately I need to adjust the endpoint for the data to arrive as follows: { "version": "v1", "timestamp": "2019-04-01T20:00:00.312", "data": { "sensor": "sensorA", "count": 4 } } I thought I needed to add a create method to the serializer class. So I tried that, but when I post the json with the "data" object I get a message that the sensor field and the count field are required. Does anybody know where I can normalize this data so that I can insert it in the database correctly? Also, what if I want to serve the data through the same endpoint like this as well, where would I be able to define that? All tips are welcome! -
'NoneType' object has no attribute 'slug'
I got this error " 'NoneType' object has no attribute 'slug'" in create_path, line 48: return 'uploads/{0}/{1}'.format(instance.game.slug, filename) model.py def create_path(instance, filename): return 'uploads/{0}/{1}'.format(instance.game.slug, filename) class OnlineGame(models.Model): name=models.CharField(max_length=120) slug=models.CharField(max_length=25,unique=True) icon=models.ImageField(upload_to='uploads/onlinegame',blank=True,null=True) class Player(models.Model): slug=models.SlugField(unique=True,max_length=120) fullname=models.CharField(max_length=120,null=True,blank=True) game=models.ForeignKey(OnlineGame,null=True,blank=True,related_name='playergame',on_delete=models.PROTECT) -
Cant change Django debug language
my django settings is already in Portuguese and English, as you can see below: LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', 'English'), ] But when there is an error in the code, it comes in german. I am located in Germany, I have a German laptop, but my Windows is also configured in English. I don't know where this german is coming from. See an example here: https://ibb.co/cvhBcvd PLEASE, I don't need help with the error, I just would like to have all my errors in English. Thank you gurus. -
How to fix the issue "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet"?
I have deployed my django webapp to my heroku server and it was working fine until I added a websocket connection that shows the contents of a model object in a separate url as soon as that object is created. For this, I used Django channels with a redis server hosted on redislabs. To run asgi app, I tried to use daphne server but when I try to run the daphne server with the following command: $daphne smartResturant.asgi:channel_layer --port 8888 , it says "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" My asgi.py import os import django from smartResturant.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smartResturant.settings") django.setup() application = get_default_application() My settings.py ASGI_APPLICATION = 'smartResturant.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": ['redis://:xxxxxxxx@redis-13131.c85.us-east-1-2.ec2.cloud.redislabs.com:13131'] }, }, } It works fine when I run locally without using daphne server. But I found out that to run asgi based apps on a hosted server, you have to use daphne server and I am unable to run it. Any help will be appreciated! -
How to access object.pk in a function listview without having to iterate through the objects with a for loop?
I have a FBV using django-tables2 so the the template already call the objects but i need to add a button that triggers a modal so I need to call the pk of the objects inside the button here's the views.py def Patients_list(request): patients = Patient.objects.filter(user=request.user) table = PatientTable(patients) RequestConfig(request).configure(table) return render(request, 'patients/patients_list.html',{ 'table' : table, 'patients':patients, }) and the button is callable at the tables.py class PatientTable(tables.Table): FirstName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) LastName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) Telephone_no = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) delete = TemplateColumn('<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Deleta</button>',extra_context={'patient': 'Patient'}) class Meta: model = Patient attrs = {'class': 'table table-striped table-hover'} exclude = ("user", "Notes", "Adress") template_name = 'django_tables2/bootstrap4.html' and the template: {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} <div id="content"> {% if user.is_authenticated %} <h1> Patients list: </h1> <br> <a href="{%url 'patients:patient_create'%}" class="btn btn-info" role="button">Add Patient</a> <br> <br> {% render_table table %} {% else %} <h2>please login</h2> {% endif %} </div> <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete" aria-hidden="true"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete patient!</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Are you sure you want to delete this patient?</p> </div> … -
How can I grab the id of foreign key to use as a column for bulk file imports?
I'm working with the Django import / export library to bulk upload models using an XLSX/CSV file. I have two models - Company and Competitor. Competitor has a many-to-many relationship with Company. I want admin users to be able to upload a bunch of competitor names and be able to select which Company they all correspond to. I want the ID of the Company it corresponds to, to be marked in another column. How can I do this? I have followed the instructions on the library's Getting Started page but I just can't get the company ID to persist. These are my models: # app/models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=200) website = models.CharField(max_length=200) class Competitor(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name='The related company' ) competitor_name = models.CharField(max_length=200) competitor_website = models.CharField(max_length=200) In forms.py I've defined the custom forms allowing users to select from a list of already defined Company records. # app/forms.py from django import forms from import_export.admin import ImportForm, ConfirmImportForm from .models import Company, Competitor class CompetitorImportForm(ImportForm): company = forms.ModelChoiceField( queryset=Company.objects.all(), required=True ) class CompetitorConfirmImportForm(ConfirmImportForm): company = forms.ModelChoiceField( queryset=Company.objects.all(), required=True ) Set up my import-export resources in resources.py from import_export import resources from .models import Company, … -
angular-gettext does not pick the strings from .PO files
I have installed everything according to documentation. Some of the things are working as per the documentation. Is there something like Django translation which automatically replaces the translation for specific language if you select those lang Index.html <!DOCTYPE HTML> <html> {% load static %} <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script> <script src="{% static 'first.js'%}"></script> <script src="{% static '/angular-gettext/dist/angular-gettext.js'%}"></script> <script type="text/javascript" > angular.module('first').run(function (gettextCatalog) { gettextCatalog.setCurrentLanguage('fr'); gettextCatalog.debug = true; debugger; gettextCatalog.setStrings('fr', { "Hello!":"Bonjour !"}); }); </script> </head> <body> <div ng-app="first"> <translate>Hello!</translate> Sagar <h1 translate>Hello!</h1> </div> </body> </html> PO file msgid "" msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Project-Id-Version: \n" "POT-Creation-Date: \n" "PO-Revision-Date: \n" "Language-Team: \n" "MIME-Version: 1.0\n" "X-Generator: Poedit 2.2.3\n" "Last-Translator: \n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "Language: fr\n" #: ui/templates/admin/firsttranslate/index.html:24 #: ui/templates/admin/firsttranslate/index.html:26 msgid "Hello!" msgstr "Halo !" When I run my code It searches for Hello and Replaces with Bonjour But I want it to be replace automatically as Django does Thanks in advance. -
uwsgi_pass does not forward SCRIPT_NAME header
I'm trying to make my web app (Django/wsgi-based) available from some subfolder of the main domain. I'm using docker for my app, and static files, so I have main nginx on my server as reverse proxy, another nginx in "nginx" container which routes the stuff for my app and uWSGI in the second container which serves actual Django data And I want my app to be available externally as myserver.com/mytool, in the same time I do not want to hardcode mytool anywhere in my app. Usually SCRIPT_NAME header is used for this type of stuff, so here is nginx configuration on the host: server { listen 80; # Just for sake of simplicity, of course in production it's 443 with SSL location /mytool/ { proxy_pass http://127.0.0.1:8000/; include proxy_params; proxy_set_header SCRIPT_NAME /mytool; # <--- Here I define my header which backend should use } } Then in my docker-compose I expose 8000:80 for nginx and here is internal nginx configuration: server { listen 80; location / { include uwsgi_params; uwsgi_pass web:3031; } } With this configuration I would expect that my Django app receives SCRIPT_NAME header, but apparently it does not. In the same time if I define custom headers like …