Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mypy with Django: type[MyModel] has no attribute "objects" [attr-defined]
After coding my Django model and adding a method which uses the "objects" manager, Mypy continues to show the error (command: "mypy ."): models.py:168: error: "type[MyModel]" has no attribute "objects" [attr-defined] How to solve that? -
Backend vs Frontend approach for upload of large files to remote storage
I am creating a software involving content delivery. It involves upload of large video files(100GB+). I understand that in general for file upload you can use the input element of html and upload it to the backend and from there you upload it to your storage. But this involves 2 uploads for 1 file and involves loading your large file into in-memory database in your backend. Im wondering if one could save some bandwidth and time, space and computation by somehow directly uploading from the frontend. What is the industry standard for dealing such a scenario? I've seen ways to upload large files from backend using multipart uploads using AWS sdk, but so far, I couldn't find a way to directly upload using HTML + JavaScript from the frontend itself(without loading the file into the in-memory database). I am using Django for backend, Angular for frontend and AWS s3 for storage. -
How to resolve a "DuplicateColumn" error when running Django migrations?
I'm encountering an issue while running migrations in my Django project. Here's the error message I'm receiving: psycopg2.errors.DuplicateColumn: column "order_address" of relation "orders_order" already exists This error seems to be related to the migrations process. I have checked my migration files and ensured that I'm not explicitly adding the "order_address" column multiple times. However, the error persists. What could be causing this error, and how can I resolve it? -
Not printing required data from json available data
[This is the source code. Here I iterate through a bunch of json entries and try to print only a few.] (https://i.stack.imgur.com/KUlfj.png) the last few empty columns are where I tried to print some specific data. It isn't printing it at all. The entries are supposed to be printed on a html page. I had tried to iterate through 'output' which had 2 json entries. I wish to print only a few specific values from each json entry but when i specified and ran the django webapp, it didn't print anything. -
csrf token is showing as text in the browser
enter image description herei am very new to django. i am trying to create a login form in django but when i write the csrf_token line after the tag it is showing in the browser view. everything is very confusing for me i don't know what to do. the tutorial that i watch on youtube only pass the csrf_token but don't say anything much. {% csrf_token %} Email Password Sign In Change Password this is a very simple form that i styled using tailwindcss and the csrf token is being shown. also my app has other errors. it does not run on the development server -
Error creating a closure table in Django: 'ForeignKey' object has no attribute 'column'
I have a Jobs model and need a closure table job_hierarchies schema looks like below Table job_hierarchies { account_id int [not null] ancestor int [not null, ref: > jobs.id] descendant int [not null, ref: > jobs.id] level int [not null] } I tried creating model & migration for JobHierarchy as below Model # api/models/job_hierarchy.py from django.db import models from .base import BaseModel from api.models import Job class JobHierarchy(BaseModel): account_id = models.IntegerField(null=False) ancestor = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id') descendant = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id') level = models.IntegerField(null=False) class Meta: db_table = 'job_hierarchies' Migration looks like below # Generated by Django 5.0.2 on 2024-03-08 04:28 from django.db import migrations, models def add_foreign_keys(apps, schema_editor): JobHierarchy = apps.get_model('api', 'JobHierarchy') Job = apps.get_model('api', 'Job') schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id'), ) schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id'), ) class Migration(migrations.Migration): dependencies = [ ('api', '0002_create_jobs'), ] operations = [ migrations.CreateModel( name='JobHierarchy', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account_id', models.IntegerField()), ('level', models.IntegerField()), ], options={ 'db_table': 'job_hierarchies', }, ), migrations.RunPython(add_foreign_keys), ] When I run make migrations, I get below error File "/app/api/migrations/0009_create_job_hierarchies.py", line 8, in add_foreign_keys schema_editor.add_field( File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 730, in add_field "name": self._fk_constraint_name(model, field, constraint_suffix), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 1708, in _fk_constraint_name [field.column], ^^^^^^^^^^^^ AttributeError: … -
stripe transfer method in django
i am working on project where i want to transfer amount to multiple stripe customers i have used the stripe transfer method but i am getting the following error Error: Request req_FlLAHrjOxkd4IO: You have insufficient available funds in your Stripe account. Try adding funds directly to your available balance by creating Charges using the 4000000000000077 test card. See: https://stripe.com/docs/testing#available-balance here is my code charge = stripe.Charge.create( amount=5000, currency="usd", source='tok_visa', description="Adding funds to test account" ) charge_id = charge.id # Assuming you have defined 'total_charges', 'user.id', 'seller_amount', and 'referral_amount' earlier in your code session = stripe.PaymentIntent.create( amount=total_charges, currency="usd", transfer_group=f"ORDER10_{user.id}", ) stripe.Transfer.create( amount=seller_amount, currency='usd', destination='acct_1OrzGLI3hFSHp0X5', transfer_group=f"ORDER10_{user.id}", ) stripe.Transfer.create( amount=referral_amount, currency='usd', destination="acct_1OrzPRI5g3KKKWKv", transfer_group=f"ORDER10_{user.id}", ) -
Django not sending rendered array to Angular
I'm trying to build an API with Django that recieves an image, applies a filter and returns the image with the filter to the frontEnd, that it's made with Angular. But when I call the API my model does recieve the image but doesn't apply the filter and doesn't return the modified image. And it whe using the method POST doesn't return anything, not even an error This is my models.py: def apply_filter(noisy_image, kernel): smoothed_image = np.zeros_like(noisy_image) for channel in range(noisy_image.shape[2]): for row in range(noisy_image.shape[0] - kernel.shape[0] + 1): for col in range(noisy_image.shape[1] - kernel.shape[1] + 1): sub_matrix = noisy_image[row:row + kernel.shape[0], col:col + kernel.shape[1], channel] smoothed_image[row + 1, col + 1, channel] = np.sum(sub_matrix * kernel) fig, ax = plt.subplots() ax.imshow(smoothed_image.astype(np.uint8)) ax.axis('off') return fig def default_image(image_array): # Load image fig, ax = plt.subplots() ax.imshow(image_array.astype(np.uint8)) ax.axis('off') # Hide axes return fig def suavizado1(image_array): kernel_size = 12 kernel = np.ones((kernel_size, kernel_size)) / (kernel_size ** 2) noise = np.random.normal(0, 10, size=image_array.shape) noisy_image = image_array + image_array * noise return apply_filter(noisy_image, kernel) This is my views.py: def processImage(request): if request.method == 'POST': uploaded_file = request.FILES['image'] filter_name = request.POST.get('filter') image_path = default_storage.save('uploaded_images/' + uploaded_file.name, ContentFile(uploaded_file.read())) print(image_path) #Load image imagen = Image.open(image_path) image_array = np.array(imagen) … -
Django email html format not
`html = """\ <html> <head></head> <body> <p>Hi Team,<br><br> Reminder:<br> Please check if Domain listed below need to be renewed.<br><br> {0} </p> </body> </html> """ www = get_data_from_db() week_old = 14 d = [] for domain in www: days = compute_days(domain) if int(days) <= int(week_old): d.append("{0} is expiring in {1} days.<br>".format(domain, days)) print(d) html = ('\n'.join(d)) print(html) part2 = MIMEText(html, 'html') msg.attach(part2)` Hi, just started learning python/django not long ago. This project is to add a reminder/notification to the company by sending out email. I came across this problem where I am unable to correctly display the html with value. If I change my code at html = html.format('\n'.join(d)) It will display the html with 1 value where the actual result is 2 value. Missing the another one. If I use code above, it will only display 2 value but missing the html. What am i missing here? -
Null field returning required
I set a referral field on my django model to null but everytime I try to register without passing in a parameter it says that the field is required for registration. I've tried different approaches to try to solve it but still no fix. I want users to be able to register without using a referral code #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, username, email, password, is_staff, is_superuser, address, **extra_fields): now = timezone.now() if not username: raise ValueError(('The given username must be set')) email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, address=address, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, False, False, True, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): user = self._create_user(username, email, password, True, True, **extra_fields) user.is_active = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=250, blank=True) last_name = models.CharField(max_length=250, blank=True) email = models.EmailField(('email address'), unique=True) username = models.CharField(max_length=50, unique=True, blank=False, default='username') profile_picture = models.ImageField(upload_to='Pictures', blank=True) created_at = models.DateField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) referral_code = models.CharField(max_length=10, unique=True, blank=True, null=True) referred_by = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) referred_users_count = models.IntegerField(default=0) #subscription_start_dates = … -
Django async nested model loading
I have models: class ObjectA(models.Model): alias = models.CharField(max_length=50) objectb = models.ForeignKey(ObjectB, on_delete=models.PROTECT) class Meta: db_table = "objecta" class ObjectB(models.Model): name = models.CharField(max_length=50) objectc = models.ForeignKey(ObjectC, on_delete=models.PROTECT) class Meta: db_table = "objectb" class ObjectC(models.Model): name = models.CharField(max_length=50) class Meta: db_table = "objectc" In my ViewSet function I want to get ObjectA and then get name from referenced ObjectC. In synchonious django I would do get_object_or_404(ObjectA, alias="My alias").objectb.objectc.name But this in async Django throws me an error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I found a solution which does not look very clean to me: from django.db.models.query import aprefetch_related_objects from django.shortcuts import get_object_or_404 get_objecta_model = sync_to_async(get_object_or_404, thread_sensitive=True) objecta = await get_objecta_model(ObjectA, name=alias) await aprefetch_related_objects([objecta], "objectb__objectc") objecta.objectb.objectc.name -
Pivot table with hierarchical indexes?
Using pandas 2.0.3. I know this may sound simple but i dont know how to make it work. I'm using pandas pivot table to rearrange a table to match a template. Here's the current code I'm using: x = pd.pivot_table(df, index=['locality', 'name', 'type', 'method'], columns='mineral', values='mineral_value', fill_value=0).reset_index() With this code I'm getting this data structure: However, I need to add a hierarchy with the columns mineral and method, so it looks something like this: I've been trying multiple ways but I just haven't been able to get it. I've tried to add x = pd.pivot_table(df, index=['locality', 'name', 'type', 'method'], columns=['mineral', 'method'], values='mineral_value', fill_value=0).reset_index() TypeError: keys must be str, int, float, bool or None, not tuple Any idea? thanks in advance -
Sending a custom error Through the API to appear in flutter
I have a functioning flutter front to register users that consumes a Django-rest-framework API. With 3 fields (Username,Email and Password). I'm trying to add a snack-bar that shows up when the user fills a field incorrectly according to my validations. this is what i tried : if (response.statusCode == 200) { // Request was successful print('Signup successful!'); // You can perform any other actions here, such as navigating to a new screen } else { // Request failed print('Failed to signup. Error: ${response.statusCode}'); final Map<String, dynamic> errors = jsonDecode(response.body); String? key = errors.keys.first; String value = errors[key][0]; print(value); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('$value'), backgroundColor: Colors.red, duration: const Duration(seconds: 2), ), ); } } catch (error) { // Handle any exceptions that occur during the API call print('Error while signing up: $error'); // You can display an error message to the user or perform other error handling actions } } For some reason when the password field or username field are Wrong i get a : Failed to signup. Error: 500 Error while signing up: FormatException: Unexpected character (at character 1). and when the email field is invalid i get the wrong error message (Enter a valid email address) . I'm still … -
How can I eliminate the segfaults that occur in working code only when debugging with ipdb?
I am using: Python: 3.11.0 Django: 4.2.8 djangorestframework 3.14.0 sqlite: 3.38.5 When I'm debugging and I use 'n' to go over a method, I sometimes get a segfault where there is no problem running the code normally. I can move my 'ipdb.set_trace()' to immediately after the call that caused the segfault, rerun the test and continue debugging but this is tedious. One cause I've tracked, is under the django reverse function. Here, the <URLResolver <module 'rest_framework.urls' from '/home/paul/wk/cliosoft/sosmgrweb/venv/lib/python3.11/site-packages/rest_framework/urls.py'> (rest_framework:rest_framework) 'api-auth/'> causes the segfault when its _populate method is invoked. I could start upgrading everything but this is a large application with many dependencies and I'd like to be confident that this problem will be eliminated if I go down that road. Does anyone know what the cause of this is and how I can resolve it? -
create choices dynamically in django
I'm trying to populate choices in django form dynamically, the choices cames from an external API. My model so far: from django.db import models class MyModel(models.Model): choice_field = models.CharField(max_length=100, choices=()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) api_url = 'http://api.com' response = requests.get(api_url) if response.status_code == 200: data = response.json() options = [(option['value'], option['label']) for option in data] self._meta.get_field('choice_field').choices = options however, it is not working, can someone help me? -
Why is my stopwatch adding fixed amount of time when I refresh?
I have a Vue.js Script is Adding time to my stopwatch once I refresh the page - Always adds an additional 6 hours. The script is simply a button that tracks time when clicked, and post the time to a django model once stopped. I am able to track time fine, but when I refresh the page, I come back to seeing 6 hours added to my stopwatch: Vue.js Script: var NavbarApp = { data() { return { seconds: {{ active_entry_seconds }}, trackingTime: false, showTrackingModal: false, timer: null, entryID: 0, startTime: '{{ start_time }}' } }, delimiters: ['[[', ']]'], methods: { startTimer() { fetch('/apps/api/start_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) => { return response.json() }) .then((result) => { this.startTime = new Date() this.trackingTime = true this.timer = setInterval(() => { this.seconds = (new Date() - this.startTime) / 1000 }, 1000) }) }, stopTimer() { fetch('/apps/api/stop_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) => { return response.json() }) .then((result) => { this.entryID = result.entryID this.showTrackingModal = true this.trackingTime = false window.clearTimeout(this.timer) }) }, discardTimer() { fetch('/apps/api/discard_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token … -
How to Efficiently Create and Maintain SQL Indexes in Django with PostGIS?
I'm working on a Django project that utilizes PostGIS for spatial data. Currently, I'm considering creating a SQL index for the created_at field to improve query performance. The created_at field is configured with auto_now_add=True, meaning it automatically captures the timestamp when an object is created. However, I'm unsure about the best practices for creating and maintaining SQL indexes in Django with PostGIS. Here are my specific questions: What is the recommended approach for creating SQL indexes in Django with PostGIS? Does creating an index for the created_at field significantly improve querying performance in Django? What are the potential maintenance tasks associated with managing SQL indexes in Django with PostGIS? I would appreciate any insights, advice, or best practices from experienced Django developers or those familiar with working with PostGIS. Thank you! -
Django: Mocking an external api call in the save method of a model
I want to test a modelform using pytest in two modes: without the need to call the external API used in the save method by generating an error when the API is offline so I can test the validation I created Here's my code: trips/models.py class Place(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name="places") day = models.ForeignKey( Day, on_delete=models.SET_NULL, null=True, related_name="places" ) name = models.CharField(max_length=100) url = models.URLField(null=True, blank=True) address = models.CharField(max_length=200) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) objects = models.Manager() na_objects = NotAssignedManager() def save(self, *args, **kwargs): old = type(self).objects.get(pk=self.pk) if self.pk else None # if address is not changed, don't update coordinates if old and old.address == self.address: return super().save(*args, **kwargs) g = geocoder.mapbox(self.address, access_token=settings.MAPBOX_ACCESS_TOKEN) self.latitude, self.longitude = g.latlng return super().save(*args, **kwargs) def __str__(self) -> str: return self.name trips/forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = ["name", "url", "address", "day"] formfield_callback = urlfields_assume_https widgets = { "name": forms.TextInput(attrs={"placeholder": "name"}), "url": forms.URLInput(attrs={"placeholder": "URL"}), "address": forms.TextInput(attrs={"placeholder": "address"}), "day": forms.Select(attrs={"class": "form-select"}), } labels = { "name": "Name", "url": "URL", "address": "Address", "day": "Day", } def __init__(self, *args, parent=False, **kwargs): super().__init__(*args, **kwargs) if parent: trip = parent else: trip = self.instance.trip self.fields["day"].choices = ( Day.objects.filter(trip=trip) .annotate( formatted_choice=Concat( "date", Value(" (Day … -
Cant get Django Date Widget to show in form
I am attempting to get a date field in a form to display as a date with date picker. For some reason, the field will not display as a date type. The model field: registration_date = models.DateField(null=True, blank=True) The form: class VehicleQuickAdd(forms.ModelForm): class Meta: model = Vehicle fields = ['license_plate', 'internal_id', 'affiliated_company', 'registration_date', 'active_since', 'registration_certificate',] widgets = { 'registration_date': forms.DateInput(attrs={'type': 'date'}) } The HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Add Vehicle{% endblock title %} {% block content %} <div class="section-container container-fluid"> <div class="general-form pl-md-5 pr-md-5"> <h2>Add Vehicle</h2> <form action="" method="post"> {% csrf_token %} {% crispy form %} </br> <input class="btn btn-success" type="submit" value="save"> </form> </div> </div> {% endblock content %} When I look at the element in the page it says type="text" <input type="text" name="registration_date" class="dateinput form-control" id="id_registration_date"> Any ideas about why this isn't working? -
Annotations returning pure PK value instead of Django HashID
In my application the user can assume one of 3 different roles. These users can be assigned to programs, and they can be assigned to 3 different fields, each of those exclusevely to a role. In my API I'm trying to query all my users and annotate the programs they are in: def get_queryset(self): queryset = ( User.objects .select_related('profile') .prefetch_related('managed_programs', 'supervised_programs', 'case_managed_programs') .annotate( programs=Case( When( role=RoleChoices.PROGRAM_MANAGER, then=ArraySubquery( Program.objects.filter(program_managers=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), When( role=RoleChoices.SUPERVISOR, then=ArraySubquery( Program.objects.filter(supervisors=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), When( role=RoleChoices.CASE_MANAGER, then=ArraySubquery( Program.objects.filter(case_managers=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), default=Value(list()), output_field=ArrayField(base_field=JSONField()), ) ) .order_by('id') ) return queryset This works (almost) flawlessly and gives me only 5 DB hits, perfect, or not... The problem is that I'm using Django HashID fields for the Program PK, and this query returns the pure integer value for each Program. I've tried a more "normal" approach, by getting the data using a SerializerMethodField: @staticmethod def get_programs(obj): role_attr = … -
Django: changing contents on a field on every save-like action
Before committing a record to the database, I want to do a sanity check on a certain field. More precisely, it is an ArrayField and I want to remove any NaN/None values and replace them by zero. However, there are many ways to create said record. A user might MyObject().save(), or MyObject.objects.create(), or MyObject.objects.bulk_create(), and even MyObject.objects.bulk_update(field=my_field). I believe there are also ways in that Django Rest Framework might use. How can I be sure that NaN/None is always replaced by zero before committing to the database? Should I overwrite all the above methods? Should I create a custom field that inherits from ArrayField but does all the data munging? What is the best practice? -
How to disable Socket io?
I am making a project involving django, react with websockets. First I tried to use socket.io, completed its setup , then decided not to use it. I deleted the files related to that but this error is popping every few seconds when i run my backend server, How to stop this? I tried to remove the server.js file , still it is persistent enter image description here -
In add to cart Span is not working properly
I Created a add to cart function for my website but in the website span is not working properly . My problem is that: You can see in the marked portion of the image if i clicked on add to cart button it is changing "0-1" but when I am clicking on add to cart button of an another product it is not changing from "1-2" So, In product-detail.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In js file: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In Views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) So please help me out with this problem and I think that the probelm is in views because js file is working properly... -
Changing ImageField URL
I'm attempting to correct my image URLs by invoking the correct_image_url method of the Page model. However, for some reason, the result is not being saved. Thus, while it operates correctly, at the step where I execute: print(f"New URL of the page: {new_image_url}") it returns the old URL. class Page(models.Model): image = models.ImageField( max_length=400, storage=S3Boto3Storage(), validators=[FileSizeValidator(limit_value=8)]) number = models.PositiveIntegerField(default=0, blank=True, null=True) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) objects = PageManager() def correct_image_url(self): url = self.image.url corrected_url = url.replace( "https%3A/dist.cloudfront.net", "https://dist.cloudfront.net") domain = "https://dist.cloudfront.net" first_occurrence = corrected_url.find(domain) second_occurrence = corrected_url.find( domain, first_occurrence + len(domain)) if second_occurrence != -1: corrected_url = corrected_url[:second_occurrence] if corrected_url != url: if self.image: original_url = self.image.url print( f"Correcting URL from: {original_url} to {corrected_url}") self.image = corrected_url try: self.save() self.refresh_from_db() new_image_url = self.image.url print(f"New URL of the page: {new_image_url}") except DataError: print( f"Skipped saving due to DataError for URL: {corrected_url}") except ValidationError as e: print( f"Validation error: {e.messages} for URL: {corrected_url}") I run it in the Django shell like this: from app.models import Page for page in Page.objects.all()[:1]: page.correct_image_url() Also, when i try to run self.image.url = corrected_url It returns AttributeError: can't set attribute -
Best practice for tenant isolation with django-tenant-users in Django?
I'm building a multi-tenant application using Django with django-tenant and django-tenant-users for handling tenants and user authentication. However, I'm struggling to find the best approach to prevent users from one tenant accessing data or functionality of another tenant. I've explored custom middleware, Django's permission system, and user profile models, but haven't found clear guidance on enforcing tenant isolation within the Django framework. For those familiar with django-tenant and django-tenant-users, how do you ensure that users from one tenant cannot access data or features belonging to another tenant? Any insights, best practices, or references to relevant documentation would be greatly appreciated. Thank you!