Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HTMX forms passing id of the foreign key chosen
This is my models.py class Services(models.Model): name = models.CharField(max_length=50) price = models.FloatField() description = models.CharField(max_length=500, null=True) # employees = def __str__(self): return self.name class Venue(models.Model): name = models.CharField(max_length=50) services = models.ManyToManyField(Services) description = models.CharField(max_length=500, null=True) capacity = models.FloatField() venue_price = models.FloatField(null=True) # available = def __str__(self): return self.name class Order(models.Model): venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, null=True, default=1) services = models.ManyToManyField(Services, null=True) total_price = models.FloatField(null=True) # date = In my html i made a set of radio buttons with the venue foreign keys from order. When the user chooses the venue they want i want the services to change based on what services are available in that venue. I don't understand how i can send a htmx request to views that passes a pk for what venue has been chosen. This is my html <div class="container"> <div hx-post="{% url "planner:create"%}" hx-swap="beforeend" hx-trigger="click" hx-target="#services" class="container form-check-inline"> {{ form.venue }} </div> </div> <div id="services"></div> This is views.py class EventCreateView(CreateView): model = Order form_class = OrderForm context_object_name = "venue" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) venue = Venue.objects.get(pk=???) context["services"] = venue.services.all() return context def get_template_names(self, *args, **kwargs): if self.request.htmx: return "planner/order_form_partial.html" else: return "planner/order_form.html" This is urls.py urlpatterns = [ path("create/", EventCreateView.as_view(), name="create"), ] -
ModuleNotFoundError: No module named 'PIL' , A problem came when I run my Django Project
When I try to run my Django project, it came an error:'ModuleNotFoundError: No module named 'PIL''. I try install Pillow in my virtual environment, but it still can't work. enter image description here -
Django AttributeError: 'bytes' object has no attribute '_committed'
Hi I have API in REST Framework. I send on mobile phone POST request with multiple images. My views.py: images = request.FILES.get('images') ad=models.Ad.objects.create(title=request.data['title'], content=request.data['content'],category=cat_id) for image in images: img = models.Images.objects.create(ad=ad,image=image) img.save() and i get error on POST request: AttributeError: 'bytes' object has no attribute '_committed' request.FILES : <MultiValueDict: {'images': [<InMemoryUploadedFile: scaled_image_picker5837141763302518082.jpg (image/png)>, <InMemoryUploadedFile: scaled_image_picker9163246472297616682.jpg (image/png)>]}> -
How to check if a ManyToManyField is subset of a queryset while filtering a queryset of a model in Django
class OrganizationUser(models.Model): pass class Feedback(models.Model): teams_shared_with = models.ManyToManyField('team.Team', related_name="feedback") class Team(models.Model): leads = models.ManyToManyField('organizations.OrganizationUser', related_name='teams_lead_at') members = models.ManyToManyField('organizations.OrganizationUser', related_name='teams_member_at', blank=True) I have the above models, all the fields were not shown. I want to filter those feedback which are shared in any team where I am a member or an admin. I would like to do something like: Feedback.objects.filter(teams_shared_with is a subset of organization_user.teams_lead_at.all()|organization_user.teams_member_at.all()) How would I do that? -
Django Polymorphic - Migrating a model that extends from a model that extends from PolymorphicModel
I have this kind of situation right now : Suppose I have 2 models that extends django Models, name it Post and Question It looks like this class Post(models.Model): ... class Question(models.Model): ... These two models has already have its own table in database and perhaps some other Model relates through a Foreign Key. Now suppose that I want to make another model that extends a PolymorphicModel from django-polymorphic, name it Commentable So it looks like this class Commentable(PolymorphicModel): ... And the two existing model wants to extend these new class like class Question(Commentable): ... class Post(Commentable): ... Now my question is how can migrate all the existing data including their related models from the existing Question and Post so they can be migrated and maintaining their Integrity? I know that one of the possible solution is to create a temporary model for Question and move all the existing data there deleting all the old data But this solution is kinda "poor" to maintaining the data integrity and it means that all the related model must be maintained in such a way so that their Foreign Key points to the updated primary key after migrating Is there any better approach … -
Invalid model identifier while migrating my data from sqlite3 to PostgreSQL
I'm trying to migrate my Wagtail application from sqlite3 to PostgreSQL but I'm getting an error saying Invalid model identifier: 'wagtailsearch.sqliteftsindexentry' This is while I type in the command: python manage.py loaddata data.json I get this error: Traceback (most recent call last): File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\apps\config.py", line 235, in get_model return self.models[model_name.lower()] KeyError: 'sqliteftsindexentry' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\python.py", line 181, in _get_model return apps.get_model(model_identifier) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\apps\config.py", line 237, in get_model raise LookupError( LookupError: App 'wagtailsearch' doesn't have a 'sqliteftsindexentry' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\Desktop\Mdrift_Wagtail\mdrift\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 102, in handle self.loaddata(fixture_labels) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 163, in loaddata self.load_label(fixture_label) oad_label for obj in objects: File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\python.py", line 103, in Deserializer Model = _get_model(d["model"]) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\python.py", line 183, in _get_model raise base.DeserializationError( django.core.serializers.base.DeserializationError: Problem … -
I want to create a report of all update history of my lead model in django
I have a Training_Lead model, in my team i have 5-6 members who can edit this lead from there id's. I want to create a report of Update history that who is update lead and when, fro that i have create a two coloum names last_modification and last_modification_time which is automaticaly update when someone update lead. class Training_Lead(models.Model): handel_by = models.ForeignKey(UserInstance, on_delete=models.PROTECT) learning_partner = models.ForeignKey( Learning_Partner, on_delete=models.PROTECT, blank=False, null=False) assign_to_trainer = models.ForeignKey( Trainer, on_delete=models.PROTECT, null=True, blank=True) course_name = models.CharField(max_length=2000) lead_type = models.CharField(max_length=2000) time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), ( 'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False) getting_lead_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), ( 'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False) lead_description = models.CharField(max_length=9000, blank=True, null=True) last_modification = models.CharField(null=False, blank=False, max_length=500) last_modification_time = models.DateTimeField(auto_now_add='True') def __str__(self): return str(self.assign_to_trainer) class Meta: ordering = ['start_date'] -
Django UserPassesTestMixin causes duplicate sql query
So, in my Django project, I have a Class-Based View that uses UserPassesTestMixin. Within it, I use test_func to check whether the object belongs to the user (or admin). But I see duplicate SQL queries happen. I suspect test_func which has self.get_object causes that. Pls, advise how to avoid that duplicating. Here is my view: class PostUpdateView(UserPassesTestMixin, UpdateView): permission_denied_message = "Access for staff or profile owner!" def test_func(self): return ( self.request.user.is_staff or self.request.user.pk == self.get_object().author_id ) model = Post queryset = Post.objects.all().select_related("author") form_class = UpdatePostForm template_name = "diary/post-update.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Raise KeyError(key)
Key error is raised but config.ini file has the same key and I can read that using configparser. But while executing it throws the key error. What can be the solution? Tried commenting out the those keys. But it throws a different error. -
Issue with Django CSRF and Basic Authentication
I am having a lot of trouble authenticating Basic Auth Http requests in Django from my Heroku web server. I have tried a lot of different solutions to fix this issue. First I was seeing Forbidden (Referer checking failed - no Referer.) so I had to add extra Origin and Referer headers to the incoming requests. Now I am stuck on Forbidden (CSRF cookie not set.). No matter what I try, I cannot seem to get ride of the error. The odd thing is that this works when I try to test this locally and hit the endpoint from a curl originating from my local machine, yet it fails from the external site (which I have less control over). This curl works: curl -X POST -u 'USERNAME:PASSWORD' -d '["test"]' https://test.mysite.com/api I have taken bits from this solution: https://stackoverflow.com/a/30875830/2698266 My relevant code looks like the following: in settings.py MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ... ] ... REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", ), "EXCEPTION_HANDLER": "rollbar.contrib.django_rest_framework.post_exception_handler", } ... ALLOWED_HOSTS = ["*.mysite.com", "mysite.herokuapp.com", "127.0.0.1", "external.com"] ... CORS_ORIGIN_WHITELIST = ["https://external.com"] CSRF_TRUSTED_ORIGINS = ["https://external.com"] CORS_REPLACE_HTTPS_REFERER = True My API endpoint (a webhook): from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view, authentication_classes, renderer_classes from rest_framework.authentication … -
How to pass and return a queue to and from a celery task in Django?
I'm trying to pass and return the queue q to and from the task test() in Django as shown below: # "views.py" import queue from .tasks import test from django.http import HttpResponse def call_test(request): q = queue.Queue() q.put(0) test.delay(q) # Here return HttpResponse("Call_test") # "tasks.py" from celery import shared_task @shared_task def test(q): q.queue[0] += 1 return q # Here But, I got the error below: Object of type Queue is not JSON serializable So, I used __dict__ with the queue q as shown below: # "views.py" import queue from .tasks import test from django.http import HttpResponse def call_test(request): q = queue.Queue() q.put(0) test.delay(q.__dict__) # Here return HttpResponse("Call_test") # "tasks.py" from celery import shared_task @shared_task def test(q): q.queue[0] += 1 return q.__dict__ # Here But, I got the error below: Object of type deque is not JSON serializable So, how can I pass and return the queue q to and from the task test()? -
Django search bar isn't giving correct results
views.py from django.shortcuts import render from ecommerceapp.models import Product from django.db.models import Q def searchResult(request): products=None query=None if 'q' in request.GET: query = request.GET.get('q') products=Product.objects.all().filter(Q(name__contains=query) | Q(desc__contains=query)) return render(request,'search.html',{'query':query,'products':products}) In views.py I have imported a model named 'Product' of another application. search.html {% extends 'base.html' %} {% load static %} {% block metadescription %} Welcome to FASHION STORE-Your Beauty {% endblock %} {% block title %} Search-FASHION STORE {% endblock %} {% block content %} <div> <p class="text-center my_search_text">You have searched for :<b>"{{query}}"</b></p> </div> <div class="container"> <div class="row mx_auto"> {% for product in products %} <div class="my_bottom_margin col-9 col-sm-12 col-md-6 col-lg-4" > <div class="card text-center" style="min-width:18rem;"> <a href="{{product.get_url1}}"><img class="card-img-top my_image" src="{{product.image.url}}" alt="{{product.name}}" style="height:400px; width:100%;"></a> <div class="card_body"> <h4>{{product.name}}</h4> <p>₹{{product.price}}</p> </div> </div> </div> {% empty %} <div class="row mx_auto"> <p class="text-center my_search_text">0 results found.</p> </div> {% endfor %} </div> </div> {% endblock %} navbar.html <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item dropdown {% if 'ecommerceapp' in request.path %} active {% endif %} "> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Shop </a> <ul class="dropdown-menu"> … -
Django 'NoneType' object has no attribute 'socialaccount_set'
models.py class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) def get_avatar_url(self): if self.author.socialaccount_set.exists(): return self.author.socialaccount_set.first().get_avatar_url() else: return 'https://dummyimage.com/50x50/ced4da/6c757d.jpg' part of landing.html <div class="col"> <h2>Recent Posts</h2> {% for post in recent_posts %} <div class="card"> <div class="card-body"> <h6> <a href="{{post.get_absolute_url}}" class="text-decoration-none text-dark"> {{post.title}} </a> </h6> <span class="badge"> <img class="rounded-circle" width="20px" src="{{post.get_avatar_url}}"> {{post.author.username}} {{post.created_at}} </span> </div> </div> {% endfor %} </div> Error message 'NoneType' object has no attribute 'socialaccount_set' Error during template rendering In template /.../landing.html, error at line 34(which includes '{{post.get_avatar_url}}' source url.) It works okay when I logged in but it shows the error when it's not logged in instead of showing the dummyimage. What am I missing? Html and Post model are in the different apps. views.py for the secondApp app! from firstApp.models import Post def landing(request): recent_posts = Post.objects.order_by('-pk')[:3] return render(request, 'secondApp/landing.html', { 'recent_posts': recent_posts, }) -
Access file from user system while running code from live server django
I want to access and execute .bat file from end-user system while my code running on server. Indirectly I want to access local system file of user system. Python / Django solution. -
Django - pass the value for detail to template
There is a view for detail: def get_viewNum(request, numNom): md = Nomenclature.objects.get(pk=numNom) all_changes_for_md = Changes.objects.filter(numNomenclature_id=md.numNom) return render(request,'Sklad/viewNum.html',context = {'nomenclature':md, 'changes':all_changes_for_md}) There is also a view to display the table: class TableView(ListView): model = Nomenclature context_object_name = 'nm' template_name = 'Sklad/viewTable.html' In template, I output a table and I want that when the button is clicked, there is a transition to the detail of the desired nomenclature. My template: /// {% for item in nm %} <tr> <td>{{item.numNom}}</td> <td>{{item.nameNom}}</td> <td>{{item.quantity}}</td> <td>{{item.numPolk}}</td> <td><a href="{% url 'prosmotr' %}">Просмотр</a></td> <td><button>Печать</button></td> </tr> {% endfor %} /// How do I pass the desired numNom to the url detail string? If you use this: ... <td><a href="{% url 'prosmotr' item.numNom %}">Просмотр</a></td> ... Returns an error: NoReverseMatch at /table/ Reverse for 'prosmotr' with arguments '('',)' not found. 1 pattern(s) tried: ['news/(?P[^/]+)/\Z'] My urls.py: urlpatterns = [ path('', home, name='rashod'), path('add_changes/',CreateChanges.as_view(), name = 'add_changes'), path('save', save), path('inventriz/', inventriz, name='invent'), path('inventriz/inventr', inventr, name='add_invent'), path('news/<str:numNom>/',get_viewNum, name='prosmotr'), path('table/', TableView.as_view(), name = 'viewTable') ] -
Image cannot be displayed after saving the data in Django. The code for it is given below
Problem Statement: In shown image, default profile pic is visible but i need uploaded photo to be displayed here when i upload and saved in the database.I am using django framework. What have I Tried here? In setting.html file,The below is the HTML code for what is have tried to display image, bio, location. The problem may be at first div image tag. Though the default profile picture is visible but which i have uploaded is not displaying in the page nor able to save in database. <div class="col-span-2"> <label for="">Profile Image</label> <img width = "100" height = "100" src="{{user_profile.profileimg.url}}"/> <input type="file" name='image' value = "" placeholder="No file chosen" class="shadow-none bg-gray-100"> </div> <div class="col-span-2"> <label for="about">Bio</label> <textarea id="about" name="bio" rows="3" class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea> </div> <div class="col-span-2"> <label for=""> Location</label> <input type="text" name = "location" value = "{{user_profile.location}}" placeholder="" class="shadow-none bg-gray-100"> </div> In views.py file,the below function is the views file settings page logic for displaying the image, bio, location. If the image is not uploaded, it will be default profile picture. If image is not none then the uploaded image is displayed. But I am not getting what is the mistake here in my code. @login_required(login_url='signin') def settings(request): user_profile = Profile.objects.get(user … -
how can i do "removeEmptyTag:False" in django-ckeditor in settings.py
source output django-ckeditor automatic remove empty tag :{ source output -
django + angular project. sometimes break my uibmodel
django view prep_data = service.PreparationsData('preparation/get_order_comp_details/',{"order_number": order_num}) response = prep_data.get_data() result = json.loads(response.text) rem = result["remark"].replace("\n",'\\n') context = { "order_number": order_num, "re" : rem } return render(request, "sendion.html",context) uibmodel var showsourcingverificationModal = $uibModal.open({ templateUrl: templateUrl, controller: 'sendtooModalCtrl', scope: $scope, size: 'lg', backdrop: false, resolve: { dataModal: function () { return { ord_num : order_num }; }, }, }); im trying to fill the field with $('#id_dn).text(value) im trying to fill the field with $('#id_dn).text(value) <script type="text/javascript"> $('#id_remarks').text('{{remark}}'); $('#idvalidation').hide(); (function () { sendtoSocinModalInit(); })(); </script> -
keep my data test when running TestCase in django
i have a initail_data command in my project and when i try to creating my test database and run this command "py manage.py initail_data" its not working becuse this command makes data in main database and not test_database, actually cant undrestand which one is test_database. so i give up to use this command,and i have other method to resolve my problem . and i decided to create manual my inital_data. inital_data command actually makes my required data in my other tables. and why i try to create data? becuse i have greater than 500 tests and this tests required to other test datas. so i have this tests: class BankServiceTest(TestCase): def setUp(self): self.bank_model = models.Bank self.country_model = models.Country def test_create_bank_object(self): self.bank_model.objects.create(name='bank') re1 = self.bank_model.objects.get(name='bank') self.assertEqual(re1.name, 'bank') def test_create_country_object(self): self.country_model.objects.create(name='country', code=100) bank = self.bank_model.objects.get(name='bank') re1 = self.country_model.objects.get(code=100) self.assertEqual(re1.name, 'country') i want after running "test create bank object " to have first function datas in second function actually this method Performs the command "initial_data". so what is the method for this problem. i used unit_test.TestCase but it not working for me. this method actually makes test data in main data base and i do not want this method. or maybe i used … -
Connect existing Django server project and to local host
I have a django project that have been maintaining on the cpanel server over 3years now with close to 30k lines of code, now I want to work with it on local machine for maintainance but after downloading codes and migrating new database, there are about thousands of database variable that reply on populated database field and will take me months to figure all out.. Anyway I can make a mini copy of my server mysql database and connect or is there any Starndard way to resolve this issue?? -
I have used djangorest to create an api but when i make a post request it returns an error saying 400 BAD request
this is the serializer : class PostSerializer(serializers.ModelSerializer): def create(self, validated_data): post = Post.objects.create( author=validated_data["author"], title=validated_data["title"], text=validated_data["text"] ) post.save() return post class Meta: model = Post fields = ["author", "title", "text", "pk", 'publicationDate'] this is the api view : class PostList(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Post.objects.all() serializer_class = PostSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and this is the request I`m making : axios.post('/api/posts/', form, { "headers": { 'Content-Type': 'application/json', } }) .then(response => console.log(response.data)) this is the error it returns POST http://127.0.0.1:8000/api/posts/ 400 (Bad Request) I have been at this problem for days now and i have tried everything but it just wont work -
How to pass a javascript variable in html to views.py?
I am currently trying to make an website using django. And i faced a problem like i wrote in title. What i want to make is like this, first of all, shop page shows all products. But, when a user select a brand name on dropdown menu, shop page must shows only that brand products. To do this, i have to get a variable which a user select on dropdown menu, and my view function should run at the same time. Please let me know how can i resolve this. i made a dropdown in html as below. <shop_test.html> <form action="{% url 'shop' %}" method="get" id="selected_brand"> <select name="selected_brand" id="selected_brand"> <option value="ALL">Select Brand</option> <option value="A">A_BRAND</option> <option value="B">B_BRAND</option> <option value="C">C_BRAND</option> </select> </form> <script type="text/javascript"> $(document).ready(function(){ $("select[name=selected_brand]").change(function () { $(".forms").submit(); }); }); </script> and my views.py is as below. def ShopView(request): brand_text = request.GET.get('selected_brand') if brand_text == None: product_list = Product.objects.all() elif brand_text != 'ALL': product_list = Product.objects.filter(brand=brand_text) else: product_list = Product.objects.all() context = { 'brand_text': brand_text, 'product_list': product_list, } return render(request, 'shop_test.html', context) i tried to google it a lot of times, but i counldn't resolve this. -
I am facing issue in image uploading through API in django
class ResidenceAreaImage(APIView): def post(self, request): if request.FILES.get("image", None) is not None: img = request.FILES["image"] img_extension = os.path.splitext(img.name)[1] save_path = "/media/company_logo/" # if not os.path.exists(save_path): os.makedirs(os.path.dirname(save_path), exist_ok=True) img_save_path = "%s%s%s" % (save_path, str(uuid.uuid4()), img_extension) with open(img_save_path, "wb+") as f: for chunk in img.chunks(): f.write(chunk) # data = {"success": True} else: raise Exception("plz add image!!!") return Response({"file_url":img_save_path}) -
Why Django can't find static folder in BASE_DIR?
I have these directories: └── MY_FOLDER ├── MY_PROJECT │ └── settings.py │ ├── MY_APP ├── STATIC │ └── style.css ├── MEDIA └── manage.py In the settings.py I've indicated: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIR = (os.path.join(BASE_DIR,'static')) When I print(STATICFILES_DIR) I get a path: MY_FOLDER/STATIC - what is exactly I wanted. But Django don't see any css there, in that folder. I tried to put my css to MY_APP/STATIC and it started to work correctly. But I want to have it not in MY_APP but in BASE_DIR/STATIC. How to do it? Or if it is impossible, how to make a correct path for STATICFILES_DIR to let it search my statics in all apps I'll add in the future. Not only in one app by doing this: STATICFILES_DIR = (os.path.join(BASE_DIR,'MY_APP','static')) Thanks. -
Auto import suggestion django functions in Vscode
hello everyone I am having a problem the visual studio code autoimport suggestion for django functions does not work for me. I appreciate the help. enter image description here pylance don't search in the django modules