Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Missing 1 required positional argument: 'on_delete'?
So: I'm trying to implement Django CMS to my Django website and I'm facing the "OneToOneField.init() missing 1 required positional argument: 'on_delete'" in my models.py from Django. from django.db import models class Word(models.Model): word_name = models.CharField(max_length=50) word_about = models.TextField() word_resources = models.URLField() def __str__(self): return self.word_name class Meta: db_table = 'words' class Principle(models.Model): word = models.ForeignKey(Word, on_delete=models.CASCADE) principle_name = models.CharField(max_length=100) principle_description = models.TextField() class Meta: db_table = 'principles' class CodeSnippet(models.Model): raw_code = models.TextField() What I've tried: this, this + chatgpt so basically: word = models.OneToOneField(Word, on_delete=models.CASCADE), word = models.OneToOneField(Word, on_delete=models.CASCADE/PROTECT/DO_NOTHING/SET_DEFAULT) -
Django smart select doesn't work with Django CSP
I admit that I am truly a beginner in this area. I made a database driven website with django. Models.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Company(models.Model): ID = models.AutoField(primary_key=True, unique=True) soc_name = models.CharField(max_length=100) phone = models.CharField(max_length=100, blank=True) class Meta: ordering = ('soc_name',) def __str__(self): return self.soc_name class Plant(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=100) company_id = models.ForeignKey(company, on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() company_id = models.ForeignKey(company, on_delete=models.CASCADE) plant_id = ChainedForeignKey( Installations, chained_field="Company_ID", chained_model_field="Company_ID", show_all=False, auto_choose=True, sort=True) def __str__(self): return str(f"{self.start_date}, {self.plant_ID}") I used Django-Smart-Selects so that in Interventions Form, when a Company is selected, the Combo Box of the Plants (which belong to the respective Companies) is automatically filtered. Here an image to make it easier to understand: Up to here everything works perfectly. So I tried adding Content Security Policies (CSP) to my site. To do this, I added these lines of code to the Settings.py file: MIDDLEWARE = [ [...] 'csp.middleware.CSPMiddleware', ] CSP_DEFAULT_SRC = ("'none'",) CSP_STYLE_SRC = ("'unsafe-inline'", "https:") CSP_SCRIPT_SRC = ("'self'",) CSP_FONT_SRC = ("'self'",) CSP_IMG_SRC = ("'self'",) The problem is that when I … -
Django template bracket notation with variable key does not work
I am trying to dynamically render a table based on a table model and it's columns. In the template, I loop over each item in the qeuryset and then over each column from a list of hard coded column names, but Django returns a Could not parse the remainder: '[column]' from 'table[column]' error. table.id renders the correct id value but table[column[0]] returns an error. Does Django not allow bracket notation fro variables? In this example table is a dict of a model class and columns is a list of the model's column names. <tbody> {% for table in query_set %} <tr> {% for column in columns %} <td>{{table[column]}}</td> {% endfor %} </tr> {% endfor %} </tbody> I have also tried using the .items method on the table dict: <tbody> {% for table in query_set %} <tr> {% for key, value in table.items %} <td>{{value}}</td> {% endfor %} </tr> {% endfor %} </tbody> but this renders nothing. table.items seems to be undefined -
{ "detail": "You do not have permission to perform this action." }
I am stuck for a few days with this, and nothing is working for me. So, my db is in Neo4j, and I am making API with Django DRF. These are the relevant files: # models.py class NeoUser(StructuredNode): uid = UniqueIdProperty() emp_id = StringProperty(unique_index=True) username = StringProperty() email = EmailProperty(unique_index=True) password = StringProperty() designation = StringProperty() department = StringProperty() pp = StringProperty(unique_index=True) dob = DateTimeProperty() phone = StringProperty(unique_index=True) ** settings.py ** REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { # 'JWT_SECRET_KEY': 'your-secret-key', 'JWT_ALGORITHM': 'HS256', 'JWT_ALLOW_REFRESH': True, 'ACCESS_TOKEN_LIFETIME': timedelta(days=30), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'JWT_AUTH_HEADER_PREFIX': 'Bearer ', "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, # "VERIFYING_KEY": SECRET_KEY, "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, 'JWT_ALLOW_REFRESH': True, # 'AUTH_HEADER_TYPES': ('Bearer',), "AUTH_HEADER_NAME": "Authorization", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", # "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", # "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), # "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } serializer.py from rest_framework import serializers from .models import NeoUser from rest_framework.validators import UniqueValidator class Neo4jUserSerializer(serializers.Serializer): username = serializers.CharField() emp_id = serializers.CharField() email = serializers.CharField() phone = serializers.CharField() password = serializers.CharField() def validate(self, data): id … -
Which Django.forms.Form method should be overridden to use variables created in __init__() when creating form fields?
I need to get data access to variables in (init: dictionary), which Django method should be overridden for this? The dictionary variable is used as a label when creating form fields. Form code: class TrainingForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(TrainingForm, self).__init__(*args, **kwargs) self.dictionary = self.user.userdictionaries.dictionary word0 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word1 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word2 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word3 = forms.CharField(label=dictionary widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word4 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) View code: class Training(MixinDataParams, TemplateView): template_name = 'training.html' def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) form_training = TrainingForm(self.request.POST, user=self.request.user) c_def = self.get_user_context(title='Training', form=form_training) return dict(list(context.items()) + list(c_def.items())) I tried to change the required fields in the body of the view function (get_context_data), but this does not work reliably. -
Django MySQL ORM commented out 'use_index'. w
my command : qs = model.objects.force_index('idx_sensorid_id_accelerator').filter(sensor_id=dev['id']).order_by('-id').values(*cols) and my index (mysql) : STATISTICS Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment Index_comment Ignored sensor_accelerator 0 PRIMARY 1 id A 131673992 \N \N BTREE NO sensor_accelerator 1 sensor_accelerator_sensor_id_b0bf304a 1 sensor_id A 19720 \N \N BTREE NO sensor_accelerator 1 sensor_accelerator_added_c16fd96c 1 added A 131673992 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_id_accelerator 1 sensor_id A 19714 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_id_accelerator 2 id D 131673992 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_added_accelerator 1 sensor_id A 15368 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_added_accelerator 2 added D 131673992 \N \N BTREE NO but the query result is : SELECT `sensor_accelerator`.`sensor_id`, `sensor_accelerator`.`id`, `sensor_accelerator`.`x`, `sensor_accelerator`.`y`, `sensor_accelerator`.`z`, `sensor_accelerator`.`temp`, `sensor_accelerator`.`time`, `sensor_accelerator`.`added` FROM `sensor_accelerator` WHERE ((/*QueryRewrite':index=`sensor_accelerator` USE `sensor_accelerator_sensor_id_b0bf304a`*/1) AND `sensor_accelerator`.`sensor_id` = 'A0011') ORDER BY `sensor_accelerator`.`id` DESC LIMIT 1 what i expected is : SELECT `sensor_accelerator`.`sensor_id`, `sensor_accelerator`.`id`, `sensor_accelerator`.`x`, `sensor_accelerator`.`y`, `sensor_accelerator`.`z`, `sensor_accelerator`.`temp`, `sensor_accelerator`.`time`, `sensor_accelerator`.`added` FROM `sensor_accelerator` USE INDEX (idx_sensorid_id_accelerator) WHERE `sensor_accelerator`.`sensor_id` = 'A0011' ORDER BY `sensor_accelerator`.`id` DESC LIMIT 1 Why django orm commented out use_index phrase? -
How to change a value of the element without reloading after a button element is clicked
I am trying to implement a “Like” button for each post. I want to change the class of the button element based on whether the user has liked the post or not, and I want the change to be reflected in real-time without a full page reload. So far, the button can send data that is like or not to a function of Django using fetch however the change of the data isn’t reflected without reloading. To achieve this, what does it need to modify? Button element in html file <div id="{{ post.id }}"> {% if post.id in whoyouliked %} <button class="btn btn-secondary fa fa-thumbs-down" onclick="likeHandler(`{{ post.id }}`, `{{ whoyouliked }}`)"></button> {% else %} <button class="btn btn-info fa fa-thumbs-up" onclick="likeHandler(`{{ post.id }}`, `{{ whoyouliked }}`)"></button> {% endif %} </div> likeHandler function in script tag in the same html file function likeHandler(id, whoyouliked){ let btn = document.getElementById(`${id}`); btn.classList.remove('fa-thumbs-up') btn.classList.remove('fa-thumbs-down') if(whoyouliked.indexOf(id) >= 0){ var liked = true; } else{ var liked = false; } if(liked === true){ fetch(`remove_like/${id}`) .then(response => response.json) .then(result => { btn.classList.add('fa-thumbs-up') }) } else{ fetch(`add_like/${id}`) .then(response => response.json) .then(result => { btn.classList.add('fa-thumbs-down') }) } } I'm new to Javascript, so I'd appreciate any comment. -
Best Practice to Insert single text passages in Django (not from database)
I'm not a developer but do little Django projects for my business for several years now. I am wondering how to best implement longer text passages like e.g. directions, data protection/privacy rules or opening hours to my website. I don't like to hard code this in the template. In the last projects I've been using the database with a model "Information" and query for the "name" "directions", "privacy rules" or "opening hours". Then I can pipe it through markdown and insert it into the template. Is this the proper way or should I put the information in a file? The content of this is kind of static (at least for years). Thanks for ideas and help, Dirk -
Third test in Django with Pytest is failed because "django.template.exceptions.TemplateDoesNotExist"
I got 3 tests in django using pytest, the first two tests are alright untill third one which cannot find Template. Last 2 of 3 are working with same template but second one cannot find the template. FAILED app_wallet/accounts/tests/test_pytest.py::test_login_failed - django.template.exceptions.TemplateDoesNotExist: main_layout.html #test_pytest.py import pytest from django.urls import reverse from django.contrib.auth.models import User pytestmark = pytest.mark.django_db def test_create_account_success(client): client_url = reverse('accounts:create') data = { 'username': 'test', 'email': 'test@domain.pl', 'password1': 'myPassword123', 'password2': 'myPassword123', } response = client.post(path=client_url, data=data) user = User.objects.all().first() assert response.status_code == 302 # redirected to another page - valid data assert User.objects.all().count() == 1 assert user.username == data.get('username') assert user.email == data.get('email') def test_login_success(client): client_url = reverse('accounts:login') user = User.objects.create_user(username='test123', password='Password123', email='test@domain.pl') data = { 'username': 'test123', 'password': 'Password123' } response = client.post(path=client_url, data=data) assert response.status_code == 302 # redirected to another page - valid data assert User.objects.all().first().username == data.get('username') assert User.objects.all().first().email == 'test@domain.pl' def test_login_failed(client): client_url = reverse('accounts:login') user = User.objects.create_user(username='test123', password='Password123', email='test@domain.pl') data = { 'username': 'test123', 'password': 'Password12' } response = client.post(path=client_url, data=data) assert response.status_code == 200 assert User.objects.all().count() == 1 assert User.objects.all().first().username != data.get('username') #login.html {% extends 'main_layout.html' %} {% block head %} <title> Test 123 </title> {% endblock %} {% block main %} … -
Django application visible in the home network only if run by root
I have a web app on Django that I'm running with the internal server to make it see on my home network. If I run with my user with python manage.py runserver 0.0.0.0:8080 I can see it work but only within my host. If I try to reach on another PC on the same network I have connection refused. If I run the same command but with root user, so using sudo su, everything works and I can reach the server from any PC on the network. I'm using Python 3.10.12 and Ubuntu 22.04.3 LTS 6.2.0-26-GENERIC -
AttributeError: module 'django.db.models' has no attribute 'JSONField' in django 3.0.5
I am trying add a model in my app like this: class WarehouseTablePreferences(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) column_preferences = models.JSONField(default=dict) and in the app I have: Django==3.0.5 django-cors-headers==3.2.1 djangorestframework==3.11.0 but its still giving me the following error: File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/users/models.py", line 407, in <module> class WarehouseTablePreferences(models.Model): File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/users/models.py", line 409, in WarehouseTablePreferences column_preferences = models.JSONField(default=dict) AttributeError: module 'django.db.models' has no attribute 'JSONField' -
why view inheritance in django does not work
django(i am new) view inheritance dont work <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>coding Django</title> </head> <body> <h1>Welcome to this shit show</h1> {% block content %} {% endblock content %} </body> </html> this is sub component and does not show inside base view i tried to include it in the base.html does not work either {% extends "base.html" %} {% block content %} <h1> this is from sub component <h1> {% endblock content %} -
How can i integrate salesforce to my Django Application
Previously I worked with ROR where I used Restforce Gem. I am new to this Django can someone suggest what are the best ways to be followed to integrate salesforce to my e-commerce application I am new to this Django is there any rest api calls that i need to make. What is the project structure i need to keep in my mind while implementing this in Django -
How to access the fields from other models in Django
I am trying to make a application where the data incoming is in this format { "author name": "J. K. Rowling", "books" : ["Harry potter 1" , "Harry potter 2"] } Now i made the models for author and books in the following format class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.ForeignKey(Author,on_delete=models.CASCADE) title = models.CharField(max_length=200) The seralizers are :- class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(many=True, required=False) # Use the BookSerializer here class Meta: model = Author fields = '__all__' Views are: class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer Custom View:- class ImportDataViewSet(ViewSet): @action(methods=["POST"],detail=False) def import_data(self,request): data = request.data print(data) # deseralize the data and check book_seralizer = [BookSerializer(data = book_data) for book_data in data.get("books",[])] author_seralizer = AuthorSerializer(data = data.get("author")) if(author_seralizer.is_valid() and all(seralizer.is_valid() for seralizer in book_seralizer)): author_instance = author_seralizer.save() for book_instance in book_seralizer: book_instance.validated_data['author'] = author_instance print("hello ",book_instance.data) book_instance.save() return Response({"message","Data imported successfully"},status=200) else: author_errors = author_seralizer.errors if (author_seralizer.is_valid() == False) else {} book_errors = [serializer.errors for serializer in book_seralizer if(serializer.is_valid() == False)] errors = { "author_errors": author_errors, "book_errors": book_errors } return Response(errors,status=400) URLS:- router = DefaultRouter() router.register(r"authors",AuthorViewSet) router.register(r"books",BookViewSet) import_data_view … -
How to update an instance with fields of related model
I have a Store model and store's types models class Store(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=128, blank=True, default="", verbose_name="name") class AmazonStore(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Amazon store") amazon_api_key = models.CharField(max_length=255, blank=True, default="", verbose_name="amazon token") class AliStore(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Ali store") ali_api_key = models.CharField(max_length=255, blank=True, default="", verbose_name="ali token") I have a view (GenericViewSet, CreateModelMixin, ListModelMixin) to create and list stores and now I want to add an update method to update Store (and fields of its related model) I want to be able to update store's name and store's api key in one update() method and one serializer. Depending on the type of store, different data may be sent in the request.data. Examples: 1. AmazonConnectOptions: { name: 'New store name', ApiKey: 'new api key' } AliConnectOptions: { name: 'New store name', ApiKey: 'new api key' } I want to use UpdateModelMixin and add an update() method: def update(self, request, *args, **kwargs): partial = kwargs.pop("partial", False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) return Response(status=200) But I don't know how to update store and its keys in one serializer. -
Interactive Table Tree Structure (Datatable) in Django Bootstrap4 & Ajax
I have a project model that can have WBS and activities, WBS can also have activities. I want to load it in a tree table style so the user can edit any one record from one screen. Is it possible in Django? I have tried using datatable examples which are great but what to do if I wish to load a tree like structure and use Ajax to Add/Update? -
Errors with Deploying a Django and React App to Railway
I'm struggling to deploy my django app to railway. The app continues to successfully deploy to Railway, however when visiting the URL of my railway app, I continue to get the error: TemplateDoesNotExist at /index.html. Since I'm using react with Django, I understand the process of serving the static files from react after they are built, and when running this project locally, everything has been working fine, the issue only started once I began to deploy to Railway. For reference, the folder where I've stored my reactapp is called 'reactapp'. Here are the key components of my manage.py file: ALLOWED_HOSTS = ["myprojecturl.railway.app", "127.0.0.1"] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000/home/", "myprojecturl.railway.app" ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'api/templates/api'), BASE_DIR / 'reactapp/build', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'reactapp/build/static', ] My main urls.py file: path('', TemplateView.as_view(template_name='index.html')) I'm confused because this project works fully well locally, but the problems keep arising when deploying to Railway. Any help is appreciated, Thanks! -
how to get current user data from forms.py file in Django application?
Can't figure out how to get user data when getting form data. The idea is that the label and date-attribute('data-word-translate') should store the data obtained from the user's tables. It seems to me that it should be something like this: enter image description here I tried to change the values of the required fields at the view.py level, but this does not work reliably.enter image description here -
Disable perfomance measures for some transactions in Sentry
Our application written on stack Django\Postgres\Redis\Celery + Vue. As one of the monitoring tool we are using Sentry. Sentry measures performance for transactions. It's possible to control how many transaction will be covered by Sentry with set up sample rate. Also we can control which transaction could be covered with filtering them by (for example) path. How can i exclude transactions from performance monitoring (but still watch them for issues)? -
How to create *working* data migration using relation ot custom User in Django?
I've just started a new project and I'm using custom User model (from django-authtools). Everything works perfect until I got tired of constantly creating example data after wiping the db and decided to add a data migration for development purposes. Mind you, I specifically don't want to use fixtures for this. I have a ContactPerson model that references settings.AUTH_USER_MODEL and I'm using apps.get_model() calls in the migration. Everything by the books (or so it seems): # clients/models.py ... class Client(models.Model): name = models.CharField(max_length=128) class ContactPerson(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="as_contact_person", ) # migration from django.contrib.auth import get_user_model from django.db import migrations def create_example_data(apps, schema_editor): Client = apps.get_model("clients", "Client") ContactPerson = apps.get_model("clients", "ContactPerson") User = get_user_model() jim_user = User.objects.create_user( email="j.halpert@dundermifflin.com", password="*", name="Jim Halpert" ) dunder_mifflin = Client.objects.create( name="Dunder Mifflin, Inc.", ) ContactPerson.objects.create( client=dunder_mifflin, user=jim_user, ) class Migration(migrations.Migration): dependencies = [ ("clients", "0001_initial"), ] operations = [ migrations.RunPython(create_example_data) ] But trying to run the migration I get this error: ValueError: Cannot assign "<User: Jim Halpert j.halpert@dundermifflin.com>": "ContactPerson.user" must be a "User" instance. Other migrations are fresh and the built-in User model had never been used. I've also checked that the User model in the migration is of … -
how to connect service to django admin panel actions
I have the model Machine, that is inherited from models.Model: class Machine(models.Model): ... The model is registered in django admin panel using: admin.site.register(Machine) When I create new model using Add... button, I need to proceed some service code, along with creating new Machine. How can I connect my service code to default django admin panel? I've tried to connect code using re-defining methods in model class, based on information I found in Internet, but that didn't work. -
Full path is not saved to media when I implement django-tenants in my django project
I am implementing multitenant in a django project with PostgreSQL for this I implemented a library called django-tenants but I have a small problem what I wanted was to save the media files for each scheme in a folder with the same name of the scheme for it in the official documentation It told me that I had to put this configuration in my settings.py. DEFAULT_FILE_STORAGE = 'django_tenants.files.storage.TenantFileSystemStorage MULTITENANT_RELATIVE_MEDIA_ROOT = "" To be able to save a folder of the media of my models for each scheme, when I test my model class Product(models.Model): name = models.CharField(max_length=150, verbose_name='Name') image = models.ImageField(upload_to='product/%Y/%m/%d', null=True, blank=True, verbose_name='Image') Actually saving in the correct folder is called schema/product/2023/08/30/imagen.png but when I consult the path in the database it only saves me product/2023/08/30/imagen.png how do I get it to be save the schematic also in the path? I tried to find a solution by all means but none worked. -
I get some error when create new model in Django
I created 2 model for one to one in Django model So model codes is very simple enter image description here I executed CMD after put the above code python manage.py migrate But I get this error message enter image description here` -
Django-admin on react page
I'm trying to put the django-admin page in a react component so that it appears to the user on the frontend. it's a project just for programmers so everyone is authorized. However, I'm having difficulties using the iframe to display the page, how can I do this without harming the application's security? I'm currently trying to use the iframe for this, but some security problems are appearing, mainly those related to crsf. -
Can't serve files located in static root with whitenoise
I am trying to serve my static files in my testing environment that's suppose to mirror my production environment that uses Whitenoise. In setting.py, I believe these are the relevant parts of the issue: DEBUG = True INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', # the rest of the apps ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' if not DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' else: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") # STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')] WHITENOISE_USE_FINDERS = False I set WHITENOISE_USE_FINDERS = False to ensure that my development environment is serving files the way Whitenoise would. Regardless, none of the static assets are being served. The only time things seem to work is when I uncomment STATICFILES_DIRS and set STATIC_ROOT = 'static/, but I can't have that for my production environment. This problem has been troubling me for a long while now and if anyone can offer some insight, I'd appreciate it a lot.