Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a simple version of youtube? [closed]
Plan to build a simple version of YouTube with basic features such as: User signup / login / logout User upload videos Videos shared across users, etc. Any suggestions on frameworks to choose: Django, Flask, XAMPP, others? Also if there any open sources ready for this? Thanks. -
How to Query a ForeignKey field pointing to another ForeignKey field in Django
I have a model (Letter) with a foreign key, pointing to another model (Company) with a foreign key. Below is a simple schema from models.py from django.contrib.auth.models import User class Company (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) date_created = models.DateField(default=timezone.now, null=True) company_name = models.CharField(max_length=100, null=True) class Letter(models.Model): company = models.ForeignKey(Company, related_name = "company_letter", on_delete=models.CASCADE, null=True) subject = models.CharField(max_length=5000, null=True) body = models.TextField() I have created a form where users can create Letters with the model through ModelForm. Currently, when the user is presented with a form to create a Letter, on the Company field, all the companies from all the users appear. See the pic below: Front end Form I would like only the companies that the User has created to appear in the drop-down, not all companies from all users. Or to be able to select the first company that the User has created. -
cannot connect Django app to Azure Database for MySQL with SSL certificate
I want Enforce SSL connection with my Azure Database for MySQL. I followed all steps that are in Microsoft docs I connected public certificate in Workbench and everything seems to be ok: I also checked status in mysql CLI and in SSL I see Cipher in use is TLS_AES_256_GCM_SHA384. but when I am trying to runserver I get error: django.db.utils.OperationalError: (9002, 'SSL connection is required. Please specify SSL options and retry.') settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': 'SET character_set_connection=utf8mb4;' 'SET collation_connection=utf8mb4_unicode_ci;' "SET NAMES 'utf8mb4';" "SET CHARACTER SET utf8mb4;"}, 'ssl': { 'ca': '/var/www/html/BaltimoreCyberTrustRoot.crt.pem' } } } I am guessing that something is wrong with ca path but I am not sure how should I change it. I tried to connect to MySQL db with certificate using this command in mysql CLI (as suggested here) but it when I put server and username it gives me syntax error (I put exactly what is below). mysql -h mydemoserver.mysql.database.azure.com -u Username@mydemoserver -p --ssl-ca=/opt/ssl/BaltimoreCyberTrustRoot.crt.pem -
How to best determine and compare two model fields that share a common foreign key relationship?
I'm having trouble to check and compare foreign key relationships. class Investment(models.Model): investor = models.ForeignKey(User, on_delete=models.CASCADE) target = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='target') .. class Club(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30) .. class Match(models.Model): home = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='home_team') away = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='away_team') goals_home = models.IntegerField() goals_away = models.IntegerField() .. Now I'm struggling in identifying in which team of the match (home or away) he basically invested to make some further calculations (note it can also be both teams of a match in which the user invested). In my view I have a qs that returns all matches that include at least one team in which the authenticated user invested and I tried to compare this to his investments. def render_dashboard_overview(request): # Get qs of all investments of the user qs_investments = Investment.objects.filter( investor=request.user ) # Get qs of all matches of clubs where the user invested qs_matches = Match.objects.filter( Q(home__target__investor=request.user) | Q(away__target__investor=request.user) ) for match in qs_matches: if match.home in qs_investments: print('test') # Create context context = { 'dashboard_site': dashboard_site, 'qs_matches': qs_matches } return render(request, 'dashboard/dashboard_overview.html', context) Also should s.th. like that be implemented as a method to the model or is this common view stuff? -
Django admin: datetime is displayed in UTC despite settings
I have this in the DB: 25.0|120|CashApp|0.0|0|1|2022-03-03 22:05:17.025000 This in the settings.py: TIME_ZONE = 'US/Eastern' # = EST USE_I18N = True USE_L10N = True USE_TZ = True And this in the admin.py: def timestamp_(self, obj): return obj.timestamp.strftime("%d %b, %I:%M %p") # :%S timestamp_.admin_order_field = 'timestamp' And on the page it's displayed like this: 03 Mar, 10:05 PM From what I understand it stores the timestamp in UTC in the DB, which is perfect, but why it displays it in UTC on the page? I've read that if I don't do activate(), the current timezone will be the same as default timezone, which should be EST in my case. What am I missing? -
Need help setting up django with react properly
I have been trying to set this up for a couple days now and I cant seem to find a good tutorial. Plus, everyone seems to set it up differently and makes it difficult to learn what is the correct way of doing it. Right now I have gotten it set up to the point where when I run server on django it will load the react page but nothing updates when I make changes in app.js, but when I npm start on the react side it works just fine. Can someone please help me or point me to a good tutorial please. -
Why does Django not see migrations?
I am trying to change some field names of Django models, but for some reasons Django does not want to see my migrations. I made sure the following things are properly set up: myApp.apps.MyAppConfig is added to INSTALLED_APPS in settings.py A migration folder with an empty __init__.py is present in my app folder In myApp folder, I also have an empty __init__.py The whole procedure works just fine locally with a SQLite database and I can change field names and run python manage.py makemigrations and python manage.py migrate to migrate the database. However in production where I use Docker Compose for orchestration and Postgres as database only the first migration works fine. Afterwards when I change any model field name and try to run docker-compose exec projectname django-admin makemigrations or docker-compose exec projectname python manage.py makemigrations or add the app name behind these commands nothing helps. Then Postgres can't handle the request, because it doesn't know the new field name: 2022-03-11 14:40:22.136 UTC [81] ERROR: column model_name.new_field_name does not exist at character 357 What am I missing here? How can I get Django to migrate? -
Different datetime in Postman and dbeaver
I have build a chatroom in Django and I record the datetime when a chatroom is created. But now that I'm testing on Postman to see if the datetime is correct, I get a datetime like 2022-03-11T14:35:55.812069Z trough Postman and on my dbeaver I have a datetime like 2022-03-11 11:35:55.812 -0300 The db that i'm using is PostgreSQL How can I check if the two datetime are equal? -
The simple django model for selectbox
Django model with models.Choices class Special(models.Choices): SPECIAL = (("welcome","My Welcome!"), ("privacy","my Privacy list"), ("happy","How happy you are"), ('',"-------------")) and I have this code in form class key_selector = forms.fields.ChoiceField( choices = Special.SPECIAL required=False, widget=forms.widgets.Select ) This error comes here TypeError: 'Special' object is not iterable How can I make the selectbox with django??? -
update JavaScript without refreshing page. Django framework
I don't know how AJAX works so coming for help guys. Simply want to update my javascript file without refreshing home page. Usually when refreshing home page then django views.py is refreshed and that's how I'm receiving data. I'm sure this is possible with AJAX as seen somewhere but not sure how that works. My javascript: <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script> <script type="text/javascript"> /*extend leadlet - you should include the polli*/ L.RotatedMarker = L.Marker.extend({ options: { angle: 0 }, _setPos: function (pos) { L.Marker.prototype._setPos.call(this, pos); if (L.DomUtil.TRANSFORM) { // use the CSS transform rule if available console.log(this.options.angle); this._icon.style[L.DomUtil.TRANSFORM] += ' rotate(' + this.options.angle + 'deg)'; } else if(L.Browser.ie) { // fallback for IE6, IE7, IE8 var rad = this.options.angle * (Math.PI / 180), costheta = Math.cos(rad), sintheta = Math.sin(rad); this._icon.style.filter += ' progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\', M11=' + costheta + ', M12=' + (-sintheta) + ', M21=' + sintheta + ', M22=' + costheta + ')'; } } }); L.rotatedMarker = function (pos, options) { return new L.RotatedMarker(pos, options); }; var locations = {{ data|safe }}; var PlaneIcon = L.Icon.extend({ options: { iconUrl: '{% static "media/plane.png" %}', iconSize: [25, 25], // size of the icon popupAnchor: [-3, -76] // point from which … -
Can I sort querydict in templates?
In my template I've got: {% for user in users %} <tr> <td> <div class="info"> <h4>{{ user.name }}</h4> <h5>{{ user.age }}</h5> </div> </td> </tr> {% endfor %} Usual {% for user in users|dictsort:"user.name" %} doesn't work as users is a queryset. Is there a way to display that in sorted order in the template without touching the backend? -
Send value from __init__.py to consumer.py websocket Django channels
I want to send data from the firebase stream(pyrebase) via django channels websocket. Web scoket is working fine, But I can't imagine how I can use consumer.py file send message function in init_.py. Here my django channel web socket Consumer.py file. import json from random import randint from asyncio import sleep from channels.generic.websocket import AsyncWebsocketConsumer from django.conf import settings class WSConsumer(AsyncWebsocketConsumer): group_name = settings.STREAM_SOCKET_GROUP_NAME async def connect(self): # Joining group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave group await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def receive(self, text_data): print(text_data) # Send data to group await self.channel_layer.group_send( self.group_name, { 'type': 'system_load', 'data': text_data } ) async def system_load(self, event): # Receive data from group print('sending message to client') await self.send(text_data=json.dumps(event['data'])) This file works fine. This is my inti.py file. In this file, I want to send data to the WebSocket in this stream_handler function. import pyrebase from configFiles.config import config firebase = pyrebase.initialize_app(config) authe = firebase.auth() database = firebase.database() safe_temperature = 20 safe_humidity = 40 def stream_handler(message): if "Humidity" in message["path"]: if message["data"] > safe_humidity: database.child("Controller").child("Light").set(1) else: database.child("Controller").child("Light").set(0) if "Temperature" in message["path"]: if message["data"] > safe_humidity: database.child("Controller").child("Fan").set(1) else: database.child("Controller").child("Fan").set(0) # Here place I want to send … -
Problem in migrating my Django db from sqlite to mysql
I need to migrate my db from sqlite to mysql , I refered to following article which seems to be good https://www.shubhamdipt.com/blog/django-transfer-data-from-sqlite-to-another-database/ problem is data is not migrated to mysql db( but tables are created ) Can you recommend a solution -
Django selenium - StaticLiveServerTestCase - data initialized setUpClass: data available in first method called but not in the second method called
I have issue when initializing data in setUpClass with StaticLiveServerTestCase. I have define a method create_test_data() where I create all my objects (user, etc...). Then I have defined a class method with setUpClass (where create_test_data() is called) and 2 methods for 2 differents tests. My first test pass but not the second test. It seems that whereas data initialized are available for the first method/test1 there are no more available for the second/test2 method. Test pass if there run separatly. I tried using setUp method and SetUpTestData class method but neither works better. test.py def create_test_data(): # objects created class L_access_menu_creation_patient_TestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(1) cls.selenium.maximize_window() cls.date_saisie = timezone.now() cls.selenium.get(cls.live_server_url) create_test_data() # test1 def test_menu_create_available_admin(self): username_input = self.selenium.find_element_by_name("username") username_input.send_keys('admin') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('admin') # click sur le bouton 'connexion' pour valider login/mdp self.selenium.find_element_by_xpath('/html/body/form/button').click() # vérifier que le menu est affiché self.assertTrue(self.selenium.find_element_by_id('createmenu').is_enabled()) # click sur le bouton 'deconnexion' self.selenium.find_element_by_id('dropdownMenuButton').click() self.selenium.find_element_by_xpath('/html/body/nav/div/div/a[3]').click() # test2 def test_menu_create_available_test1(self): # add permission to user test1 self.test1 = User.objects.get(username='test1') content_type = ContentType.objects.get_for_model(Patient) permission = Permission.objects.get( codename='add_patient', content_type=content_type, ) self.test1.user_permissions.add(permission) # same test as above for admin user error raised: django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. -
Send initial arguments from a Django view to Dash and read it outside layout
I have an scatter plot on Dash. This scatterplot takes the values from SQL depending on the input parameter id. After querying the database with id, in case it is the first time it is accessed the given id element, it saves the x,y values in a csv. Then, Dash reads the given csv and plots it. Until here, everything works except that I am not able to read the value sent from the Django view. My approach is the following one: views.py: @api_view(['GET']) def chart(request): id = request.GET.get('ID', None) if not os.path.isfile(f"{processed_path}/{id}.csv"): # Query SQL with id in case the output_variable for the given id does not exist and write the csv file context['dash_context'] = {'target_id': {'value': id}} return render(request, 'plots/chart.html', context) chart.html: {% load plotly_dash %} {%plotly_app name="Genome" ratio=1% initial_arguments=dash_context} Dash application app = DjangoDash('Genome', id='target_id') ### Get id value passed to template <---- #Layout code Therefore, my question is: how can I read in the DjangoDash app the parameter that the user introduces in the url before displaying the layouts, which will be used to determine the input csv to read the x,y values in the layouts? -
Create chart with Apexchart in a for loop - Django
I have a list in a loop and I want to graph it in a loop. But it looks like below. Overlapping graphics. But I want it to be seen one by one. The reason for this is that the sent data is constantly added to index 0. I leave my codes below. enter image description here views.py for i in devices: query = client.query("select * from table where x='"+ str(i) +"' and time > now() -7d") series = query._get_series() values = series[0]['values'] for x in values: dto = datetime.strptime(x[0], "%Y-%m-%dT%H:%M:%SZ") dto += timedelta(hours=3) trdateTime = dto.strftime("%d/%m/%Y-%H:%M:%S") milisec = dto.timestamp() * 1000 + 10800000 tempVal = int(x[5][2:5])/10 humVal = int(x[5][5:8])/10 tempList.append(tempVal) humList.append(humVal) timeList.append(trdateTime) dataTemp = [milisec, tempVal] dataHum = [milisec, humVal] tempChartDatas.append(dataTemp) humChartDatas.append(dataHum) tempChartDatas2.append(tempChartDatas[:]) tempChartDatas2.append(",") humChartDatas2.append(humChartDatas[:]) tempList2.append(tempList[::-1]) humList2.append(humList[::-1]) timeList2.append(timeList[::-1]) context['logListT'] = zip_longest(timeList2, tempList2) context['logListH'] = zip_longest(timeList2, humList2) context["all"] = zip_longest(tempList2, humList2, tempChartDatas2, humChartDatas2) return render(request, 'index.html', context ) index.html --> this is chart {% for d,v in logListT %} <div class="row" style="border-bottom: 2px #293450 solid; padding-bottom: 25px; margin-top:2em;"> <div class="col-6"> <div id="chart-area{{ forloop.counter }}"></div> </div> <div class="col-6"> <div class="row" style="justify-content:space-evenly;"> <div id="chart3{{ forloop.counter }}"></div> <div id="chart4{{ forloop.counter }}"></div> </div> <div class="row" style="justify-content:center;"> <div class="tableScroll"> <table class="table"> <thead style="background-color:#0b1827; color:#4f5d82;"> <tr> … -
django user specific authentication method
i am planning a django web application with multiple tenants (or i call it companies). This means that my web application is used by multiple companies. Every company could shall set their own authentication method. For example company 1 and company 2 would like to use active directory and company 3 and 4 use the default django authentication system. But the users can associated with more than one company. I have build a little diagram: And at this point i'm stuck. Only existing users with the specific permission can create new user accounts. The primary key of a user is the email adress. I think the companies should "register" their domain if they would like to use another authentication method. For example company 1 have the domain xyz.de and all users in my web app with the domain in their email adress must authenticate them over the active directory from company 1. I think the user could type only their email adress in the login form and django can check if a specific authentication method is configured for the domain. And in the next step the user can type the password or he is redirect to the other authentication system. … -
Python Django Format Localization
I created my formats files for my project. And I have format file for all languages to be used in my project. According to the user's language, the relevant format file is automatically called by django. Can I call the definitions here based on the user's language? If I can call my definitions, my automatic transform methods will be ready. Your opinion is very valuable to me, thank you. formats/tr/formats.py: DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' STR_DATE_FORMAT = "%d.%m.%Y" STR_DATE_SQL_FORMAT = "%Y-%m-%d" STR_DATETIME_FORMAT = "%d.%m.%Y %H:%M:%S" STR_TIME_FORMAT = "%H:%M:%S" DATE_INPUT_FORMATS = ( '%d.%m.%Y', # '25.10.2022', '25.10.06' '%d/%m/%Y', # '25/10/2022' # '%d %B %Y', '%d %b. %Y', # '25 Ekim 2022', '25 Eki. 2022' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2022 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2022 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2022 14:30' '%d.%m.%Y', # '25.10.2022' ) converts/datetime.py: class DateTime: from formats.tr import formats as ff def __init__(self): from formats.en import formats as ff if a == "tr": from formats.tr import formats as ff else: from formats.en import formats as ff @classmethod def to_string(cls, tarih, date_format=ff.STR_DATE_FORMAT, time_format=ff.STR_TIME_FORMAT): """ :param tarih: :return: """ if isinstance(tarih, datetime.datetime): return tarih.strftime("%s %s" % (date_format, time_format)) elif isinstance(tarih, datetime.date): return tarih.strftime(date_format) elif isinstance(tarih, datetime.time): … -
Arduino to Django server (l127.0.0.1) not connect
My Arduino Code is not connected with my Django server which run on webbrowser 127.0.0.1 what change are in my arduino code so I run locally tested My Arduino program is #include <ESP8266WiFi.h> const char* ssid = "Pravesh"; const char* password = "123456789"; const char* host = "localhost"; void setup() { Serial.begin(115200); delay(10); Serial.println(); Serial.print("Connection to"); Serial.println(ssid); WiFi.begin(ssid,password); while(WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFI connected"); Serial.println("Ip address:"); Serial.println(WiFi.localIP()); // put your setup code here, to run once: pinMode(LED_BUILTIN,OUTPUT); digitalWrite(LED_BUILTIN, LOW); } void loop() { // put your main code here, to run repeatedly: Serial.print("Connecting to host"); Serial.println(host); WiFiClient client; const int httpPort = 80; delay(3000); if (!client.connect(host,httpPort)){ Serial.println("Connection failed"); return; } Serial.println("***"); } In the Serial monitor is shows connection failed -
Reload all django url's files without restarting server
I need to change my urls in site without reloading server. Using: Django 4.0.2 if type == 'Name': urlpatterns.append(path('<slug:slug>/', details)) if type == 'Id': urlpatterns.append(path('<int:pk>/', details)) So if param type change, django don't see that, cause urls.py runs only on server reload Probably we can make server reload, but for sure not manualy -
ModuleNotFoundError: No module named 'django_filter'
I'm trying to use django-filter on my application but I get the error 'ModuleNotFoundError: No module named 'django_filter' Below is my code base settings.py ''' ... 'django_filter' ... ''' I have also installed django_filter in my application. -
Filter a QuerySet based on matching field in another QuerySet but restricted to an associated field in the other QuerySet
I am trying to create a filter based off two query sets of two related models (both already previously filtered). The first returns a list of IDs and concepts (names) with associated values (definitions). dqs: ID + concept + definitions + associated language (any one of four) For example: <QuerySet [<Definition: Definition (en) for #39: CBD, central business district: definition text>, <Definition: Definition (en) for #184: migration: definition text...> The second also has IDs and concepts which may or may not have matching values in the first list. tqs: ID1 + concept1 + terms (lang 1); ID1 + concept1 + terms (lang 2)...ID2 + concept1 + terms (lang 1) etc. For example: <QuerySet [<Translation: “other language term entry” (fr) for #1: abiotic component>, <Translation: “abiotic component” (en) for #1: abiotic component>, <Translation: “yet another language term entry” (es) for #1: abiotic component>...> IDs and concepts (expressed in English, the source language) are not language specific. Terms and definitions are language specific. So each concept+ID is associated with term entries and definitions in four different languages. I need to filter tqs so that it only displays entries that have matching IDs in dqs, and only in the language in which the … -
Django Form ChoiceField how to show more field name
i have a "little" problem. I want get ALL ModelChoiced field and don't know how to do that. My code parts models.py class Materials(models.Model): material = models.CharField(max_length=20,unique=True) density = models.PositiveSmallIntegerField() price = models.PositiveSmallIntegerField() def __str__(self): return self.material class Items(models.Model): article_number = models.CharField(max_length=20,blank=True,null=True) quantity = models.PositiveSmallIntegerField(blank=True,null=True) material = models.ForeignKey('Materials',on_delete=models.PROTECT,blank=True,null=True) surface =models.CharField(max_length=20,blank=True,null=True) . . . forms.py class ItemsForm(forms.ModelForm): class Meta: model = models.Items fields = "__all__" views.py def new(request): items_form = forms.ItemsForm() context = { 'items_form':items_form, } return render(request,"new.html",context) new.html {{ items_form.article_number }} {{ items_form.quantity }} {{ items_form.material }} {{ items_form.surface}} . . . So now, when open link, the generated html material code is <select name="material" id="id_material"> <option value selected>---------</option> <option value="id_1">"material_1"</option> <option value="id_2">"material_2"</option> <option value="id_3">"material_3"</option> </select> I want represent all Materials field value on each input, like this: <select name="material" id="id_material"> <option value selected>---------</option> <option value="id_1">"material_1"</option> <option value="id_2">"material_2"</option> <option value="id_3">"material_3"</option> </select> <select name="density" id="id_density"> <option value selected>---------</option> <option value="id_1">"density_1"</option> <option value="id_2">"density_2"</option> <option value="id_3">"density_3"</option> </select> <select name="price" id="id_price"> <option value selected>---------</option> <option value="id_1">"price_1"</option> <option value="id_2">"price_2"</option> <option value="id_3">"price_3"</option> </select> I tryed adding these line in ItemsForm but this method not get 'id', only just values: def __init__(self, *args, **kwargs): super(ItemsForm, self).__init__(*args, **kwargs) self.fields['density'] = forms.ModelChoiceField(queryset=models.Materials.objects.values_list('density',flat=True)) -
Displaying MySQL data on HTML page in Django - data not displaying
I am totally new to Django and I'm having a problem displaying data from a MariaDB MySQL database on a HTML page. I have a legacy database called Vision which has a table within it called SensorResult. I have added this database to the settings.py file and made a routings folder with a router_db.py file to tell the app when to use the Vision database. From this, I ran the following command: python manage.py inspectdb --database=Vision This returned a printout of each table within the database and all columns. I then used this to create a standard models.py file using this information as shown below: from django.db import models class Sensorresult(models.Model): sensorresult = models.AutoField(db_column='SensorResult', primary_key=True) # Field name made lowercase. sensorid = models.IntegerField(db_column='SensorID') # Field name made lowercase. visionid = models.IntegerField(db_column='VisionID') # Field name made lowercase. userinputid = models.IntegerField(db_column='UserInputID', blank=True, null=True) # Field name made lowercase. value = models.FloatField(db_column='Value') # Field name made lowercase. timestamp = models.DateTimeField(db_column='TimeStamp') # Field name made lowercase. class Meta: db_table = 'SensorResult' From this, I used makemigrations and migrate commands to submit this model. Now I can open the Django Shell and query the database and get a response, which makes me think that the … -
Uploading file by filefield returns Bad Request SuspiciousFileOperation
views.py if request.method == 'POST': form = MeasuringCodesForm(request.POST, request.FILES) files = request.FILES.getlist("file_field") if form.is_valid(): with transaction.atomic(): for each_file in files: new_code = MeasuringCodes(file_field=each_file) new_code.mediaplan = Mediaplan.objects.get(campaign=campaign_id) new_code.added_by = request.user new_code.save() models.py MEASURING_CODES_PARENT_PATH = 'measuring_codes/' def upload_measuring_codes_direction(instance, filename): return os.path.join(settings.MEDIA_ROOT, MEASURING_CODES_PARENT_PATH, str(instance.mediaplan.mediaplan_octi_id), filename) class MeasuringCodes(models.Model): updated = models.DateTimeField(auto_now_add=True) mediaplan = models.ForeignKey('Mediaplan', on_delete=models.CASCADE) added_by = models.ForeignKey('User', on_delete=models.PROTECT) file_field = models.FileField(upload_to=upload_measuring_codes_direction) settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/files/' MEDIA_ROOT = os.path.join(BASE_DIR, 'files') And while uploading it i get bad request Detected path traversal attempt in '/x/y/files/measuring_codes/6RvVqvgp_L9cS/20220311124341089314_0' nginx.conf And on my local database everything works ok, even on wb.save(filename=os.path.join(MEDIA_ROOT, mp_file_path)) uploading works perfectly with actually same link (x/y/files/...) What should i change, something with upload_to attribute is executing badly and takes at beginning another storing route?