Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django skips domain name while appending urls
While using @user_passes_test(function, login_url) decorator on production server I found out login_url is not getting appended as host/mysitename/login_url but just like host/login_url. Though it worked just fine on my local PC. I found out that changing the login_url to /mysitename/login_url solves the problem, but is there an elegant solution how to avoid this? -
Ordering django Group model for all related objects
I'm trying to order the group objects alphabetically by name in all usages. So in every dropdown where the groups are displayed, they should be ordered by name. Right now the are "random" (in the order the were created). There are some third party models (django-cms: class AbstractPagePermission code) which are using the Group model from django.contrib.auth.models. I can't change their code, so I can't modify the form nor the models... I can code a GroupAdmin but this is only ordering the objects in the admin itself, not in other forms... Any ideas? I guess there is no easy/simpel and beautiful way to solve this. P.S. I hate this kind of SO questions myself... forgive me... there is no code to show... Help is appreciated! -
How to check an item in a tuple in a tuple with inconsistent items
I have a tuple that has some single items in it as well as some more 2 item tuples in it, and I need to be able to check the 2 item tuples for a specific match. I have tried specifying the 2 item tuple to avoid the problem, but I am using django and it is a fieldset field item and if I specify down to the 2 item tuple that I know the item I'm looking for is in, I can't perform the operation that the check is testing for. The django error that comes up is "cannot be specified for myModel model form as it is a non-editable field". I also don't think that I can do a nested for loop because not all items in the tuple are nested tuples. I've also tried to make a testing variable as a boolean of if the item is there or not, but then I get the error thrown when I try and do the if statement, even though it should be skipped due to the fact that the item is actually present in the list. I've looked at a lot of the answers here and on the web … -
In Django how do I call a function in the template
As you can see I am trying to create a function and use it in the template by calling it in the get_context_data But when I refresh the page, it gives me the error: name 'sidebar' is not defined. I think I might need to pass some variables into the sidebarFunction but I am not entirely sure. HTML: {% if user.is_staff %} {% for client in sidebar %} <li> <!-- <a href="{% url 'public:client_detail' client.client.pk %}"> --> <p class="client-title" onclick="subNavDropDown(this)">{{ client.client }}</p> <!-- </a> --> </li> <ul class="sub-nav" id="{{ client.client }}-subnav"> {% for project in client.projects %} <!-- Add a link to this --> <li class="sub-nav" id="project-dropdown-{{ project.pk }}"> {{ project }} </li> {% endfor %} </ul> {% endfor %} <br> {% else %} {% for project in sidebar %} <li> <a href="{% url 'public:client_detail' client.pk %}"> <p class="client-title"></p>{{ client }}</p> </a> </li> {% endfor %} {% endif %} Python: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) client = self.request.user.groups.all() context["project"] = Project.objects.filter(client=self.get_object()) context["projects"] = Project.objects.filter(client__in=client, active=True) context["sidebar"] = sidebar return context def sidebarFunction(self): if self.request.user.is_staff: sidebar = [] for client in Client.objects.all(): data = { "client": client, "projects": Project.objects.filter(client=client), } sidebar.append(data) else: sidebar = Project.objects.filter(client__in=client, active=True) -
how to count total student according to 'course' model in django
I am trying to count the number of the student according to CourseMasterModel. I did it in MySQL, but I want to in Django. select cn.course_name,count(st.id) from course_master cn,semister_master sem,division_master di,student_profile st where st.division_id = di.id and di.semister_id = sem.id and sem.course_id = cn.id GROUP BY cn.course_name; class CourseMasterModel(models.Model): course_name = models.CharField(max_length=20,unique=True) total_semister = mod`enter code here`els.SmallIntegerField() class Meta: db_table = "course_master" verbose_name_plural = 'Course (Department)' verbose_name = "Course" def __str__(self): return self.course_name class SemisterMasterModel(models.Model): semister = models.SmallIntegerField() total_div = models.SmallIntegerField() course = models.ForeignKey(CourseMasterModel,on_delete=models.PROTECT) class Meta: db_table = "Semister_master" verbose_name_plural = 'Semister' verbose_name = "semister" def __str__(self): return "%s - %d" %(self.course.course_name,self.semister) class DevisionMasterModel(models.Model): div_name = models.CharField(max_length=2) semister = models.ForeignKey(SemisterMasterModel,on_delete=models.CASCADE) class Meta: db_table = "division_master" verbose_name_plural = 'Division' verbose_name = "Division" def __str__(self): return "%s - %s - %s"%(self.semister.course.course_name,self.semister.semister,self.div_name) class StudentProfileModel(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") division = models.ForeignKey('core.DevisionMasterModel',on_delete=models.CASCADE,verbose_name="Course / Semister / Division") roll_no = models.IntegerField() enrollment_no = models.IntegerField(unique=True, error_messages={'unique':"This enrollment number has already been registered."}) def __str__(self): return self.user.username class Meta: db_table = "Student_Profile" -
Django Channels (and other framework) session id/key uses
I would like to assign a meaningful value to self.group_name in a channels application and I would like this tied to the user session (i.e. data will go anywhere the same user is logged in). Is it safe to use the session ID (from self.scope['session'].session_key) as this identifier, provided this value never leaves the server? I want my channels connection lifetime to match that of my Django session, so this seems like the most straight forward approach and avoids cluttering up the session with other variables. The alternative would be to assign something like a uuid4 value to a new session variable. That would make it more difficult for me to leak a users session_key. -
Error importing "openwisp_utils.admin import ReadOnlyAdmin"
I am trying to implement django-freeradius, but I get the error cannot import name 'ReadOnlyAdmin', when I write the line * in urlspatters within urls.py of my project. I have tried to use the same configuration in https://github.com/openwisp/django-freeradius/blob/master/tests/urls.py, but it does not work. # myproject/urls.py from django.contrib import admin from django.urls import path, include from openwisp_utils.admin_theme.admin import admin, openwisp_admin openwisp_admin() admin.autodiscover() urlpatterns = [ url(r'^', include('django_freeradius.urls', namespace='freeradius')), #* This line path('admin/', admin.site.urls), ] I have installed: Python 3.6.8 Django 2.2.4 django-filter 2.1.0 django-freeradius 0.1a0 openwisp-utils 0.2.2 These are my apps in settings.py # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_freeradius', 'django_filters', ] And, this is the complete error when I run python manage.py runserver () Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate … -
How can I exclude script tags and style tags from a TextField that will turn eventually to a plain html code
I need a way that removes Script tags and Style tags from a textarea since it runs when I post a post. When I post something as a Post-it should turn everything from HTML tags to plain text that HTML was applied on, therefore, script tags and style tags will be applied as well, which is quite unprofessional and risky. class Post(models.Model): user = models.ForeignKey(User, related_name = 'posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable = False) group = models.ForeignKey(Group, related_name='posts',on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs = {'username': self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message'] I expect the output not to be applied or built, instead, I expect it to delete the , and show everything inside as plain text. -
How to serialize a dictionary containing lists with Django-Restframework?
I'm creating a REST-API for my Django-App. I have a function, that returns a list of dictionaries, that I would like to serialize and return with the rest-api. The list (nodes_of_graph) looks like this: [{'id': 50, position: {'x': 99.0, 'y': 234.0}, 'locked': True}, {'id': 62, position: {'x': 27.0, 'y': 162.0}, 'locked': True}, {'id': 64, position: {'x': 27.0, 'y': 162.0}, 'locked': True}] Since I'm a rookie to python, django and the Restframwork, I have no clue how to attempt this. Is anybody here, who knows how to tackle that? somehow all my attempts to serialize this list have failed. I've tried with class Graph_Node_Serializer(serializers.ListSerializer): class Nodes: fields = ( 'id', 'position' = ( 'x', 'y', ), 'locked', ) def nodes_for_graph(request, id): serializer = Graph_Node_Serializer(nodes_of_graph) return Response(serializer.data) The result I hope for is an response of the django-rest-framwork, containing the data in the list of dictionaries. -
How to display queryset list?
I am creating website for game tournaments. I have specialized queryset. I want to display on one page teams' names and their players. I tried to work with "get_queryset()" function but I don't understand what exactly. Probably there is mistake in template section. models.py from django.db import models class TestTeam(models.Model): name = models.CharField(max_length=30, default='Team') slug = models.SlugField(max_length=5) def __str__(self): return self.name class TestPlayer(models.Model): name = models.CharField(max_length=100, default='Player') nick = models.CharField(max_length=20, default='Nickname') team = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, default='Team') #photo = models.ImageField(upload_to='', null=True) No = 'N' Yes = 'Y' STANDIN_CHOICES = [ (Yes, 'Yes'), (No, 'No'), ] standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No) slug = models.SlugField(max_length=20, default=nick) def __str__(self): return self.name class TestMatch(models.Model): name = models.CharField(max_length=100, default='Match') leftTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Left Team') rightTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Right Team') slug = models.SlugField(default=str(name)) def __str__(self): return (str(self.leftTeam) +" - "+ str(self.rightTeam)) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.TestView.as_view(), name='home'), path('<slug:slug>/', views.MatchView.as_view(), name='match'), ] views.py from django.views.generic import ListView, DetailView from . import models from django.shortcuts import get_list_or_404 class TestView(ListView): model = models.TestMatch template_name = 'home.html' class MatchView(DetailView): model = models.TestPlayer template_name = 'match.html' def get_queryset(self): queryset = super().get_queryset() if 'slug' in self.kwargs: team_slug = self.kwargs['slug'] TEAM … -
Bootstrap CDN not loading inside Django?
I am following this tutorial to learn Django : https://realpython.com/get-started-with-django-1/#why-you-should-learn-django All the steps were successful until the author started implementing Bootstrap CDN in his code: Django simply ignores it and doesn't show any different text fonts from the Bootstrap style. The section in the tutorial "Add Bootstrap to Your App" is the one I encountered a problem with and also later on "Projects App: Templates". I checked if all the code from the tutorial is correct in my project already. Do I need to install anything from Bootstrap? from the tutorial I understood I only needed to add the link. Thank you -
How can i get custom fields on ModelSerializer
I have a model class Teacher(models.Model): name = models.CharField(max_length=100) message = models.CharField(max_length=300) status = models.OneToOneField(Dictionary, on_delete=models.CASCADE) money = models.IntegerField(default=None, blank=True, null=True) My urls urlpatterns = [ path('get', views.GetViewSet.as_view({'get': 'list'})), ] My view class GetViewSet(viewsets.ModelViewSet): def get_serializer_class(self): GeneralSerializer.Meta.model = Teacher return GeneralSerializer def post(self, request): return self.select_api() def select_api(self): queryset = Teacher.objects.values("name","money").annotate(Count("money")) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) serializer class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None depth = 2 fields = '__all__' in this example in annotate func i have +1 field "money__count" but i can't display it cause my model have not a this field. How can i display it in api and i want a universal serializer (without adding static field to serializer cause it is universal serializer for all models) Please help me -
How to return each iteration using for loop in Django views
How to print iteration in template -
ArrayField In Django is giving error while doing migrations
I have added arrayfield to model in my application. Below is my model class employees(models.Model): firstName=models.CharField(max_length=10), lastName=models.CharField(max_length=10), tags_data = ArrayField(models.CharField(max_length=10, blank=True),size=8,default=list,) Below is my migrations file data. class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='employees', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tags_data', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=10), default=list, size=8)), ], ), ] when I am doing migrate I am getting the below error django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[8] NOT NULL)' at line 1") What is wrong with the syntax. Please help me where I am going wrong? -
After user login based on the user role page should redirect
Table called profile,in that table there is a field called designation,when user logins based on the designation the page should redirect. -
Django, limit many to many choices with exactly equal forignkeys
I have three models like that: " Model.1 X = CharField(...) Model.2 Y = ForeignKey (Model.1...) Model.3 ¥ = ForeignKey (Model.1...) Z = ManyToMany(Model.2...) " I want to just show up just some model 2 that have equal foreign key with model 3, in many to many field of model 3. I use limit chooses in models.py but its not affect dynamically when I make or edit new model3 object. How can I make this check box limited to equal forignkeys? -
How to access and share the model in django microservices
I splited my application from monolith to microservice architecture, but i'm using same Database across the microservices. But how will i fetch data from one application to other, because the model is specified in one application. But i want that data to displayed in other application. Same problem is already asked in stackoverflow, but there is no proper answer. The already existing question, they proposed request to access the data. But i don't feel that is best practice, because i need to make a request lot of times for every record. -
Django boto3 error during collectstatic command
I'm trying to run a gitlab project on a local machine. I have a problem at the start of the command manage.py collectstatic error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file if self.storage.exists(prefixed_path): File "/home/y700/Env/healthline/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 532, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 634, in _make_api_call api_params, operation_model, context=request_context) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 680, in _convert_to_request_dict api_params, operation_model, context) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 712, in _emit_api_params params=api_params, model=operation_model, context=context) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/hooks.py", line 356, in emit return self._emitter.emit(aliased_event_name, **kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/hooks.py", line 228, in emit return self._emit(event_name, kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/hooks.py", line 211, in _emit response = handler(**kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/handlers.py", line 219, in validate_bucket_name if VALID_BUCKET.search(bucket) is None: TypeError: expected string or bytes-like object I tried to update the boto3 version, but … -
Is it possible to view/receive user form inputs from django site?
I have been experimenting with setting up an eCommerce section on a website. It's on a small scale so making a dedicated system isn't strictly necessary. I was wondering if it were possible to set up a form so that once filled in with for example a Name and Email, the owner of the site can see the contact information and get in touch. As mentioned, it's pretty small and won't have much traffic so having a massive amount of automation isn't needed. The site is run on Django (2.1.11) -
Advanced ORM usage for constraint filtering by an annotated value
I have the following Query/(ies) that I have constructed: users = User.objects.filter(is_active=True) date_range = [start_date, timezone.now()] results = SurveyResult.objects.filter( user__in=users, created_date__range=date_range, ).annotate( date=TruncDate('created_date'), total_score=Sum('score'), participants=Count('user'), ).values( 'survey', 'user', 'date', 'total_score', 'participants', ).order_by( 'date', ) A quick print of each result in the resulting QuerySet as: for result in results: print(results) ...outputs data as this: django_1 | {'survey': UUID('eb51368e-994a-4c0b-8d8a-e00ed20b5926'), 'user': UUID('25afbbfd-bddf-4fe8-bbac-758bd96093b0'), 'date': datetime.date(2019, 7, 26), 'total_score': 90, 'participants': 1} django_1 | {'survey': UUID('09947780-8d60-499f-87e3-fc53a9490960'), 'user': UUID('6afdea22-ea10-4069-9e7b-43fb6955ce0e'), 'date': datetime.date(2019, 7, 26), 'total_score': 17, 'participants': 1} django_1 | {'survey': UUID('890d0a21-6e27-457f-902e-e2f37d2fad6c'), 'user': UUID('d98684f7-97ab-49d7-be50-0cc9b6465ef5'), 'date': datetime.date(2019, 7, 26), 'total_score': 35, 'participants': 1} django_1 | {'survey': UUID('890d0a21-6e27-457f-902e-e2f37d2fad6c'), 'user': UUID('d98684f7-97ab-49d7-be50-0cc9b6465ef5'), 'date': datetime.date(2019, 7, 27), 'total_score': 62, 'participants': 1} The eagle eyed amongst you might notice that the last two records are pseudo-duplicate on the 'user' and 'survey' keys, but not on any of the other. My question is: how the heck do I remove the records from this record set (either using the Django ORM Query I have constructed or in a standard pythonic way) where the 'survey' and 'user' keys match - only keeping the most recent record according to the 'date'...so leaving me: Expected Outcome: django_1 | {'survey': UUID('eb51368e-994a-4c0b-8d8a-e00ed20b5926'), 'user': UUID('25afbbfd-bddf-4fe8-bbac-758bd96093b0'), 'date': datetime.date(2019, 7, 26), 'total_score': … -
using an isolated database like django models
I have a database (postgresql) which is not created by django models (orm). Now I need to use that database in my django project. I can write raw sql to retrieve data from database. But I do want to fetch data like I do with django models. How can I do that? -
How to implment nested queryset in Django ORM?
I am building API from django rest framework. I have a model in which there are certain foreign keys. For that model listing I am using ListAPIView. In that listing I want to implement nested queryset. Foreign key models are not directly in relation with each other. In following example. For multiple x there can be multiple y and for multiple y there can be multiple z. So I want json response as for unique x and in that object its y and its z. I tried with annotate and subquery. But that does not seem to solve my issue. Table: |x_id | y_id | z_id | |1 | 2 | 3 | |1 | 4 | 5 | |1 | 2 | 6 | class Workitem(models.Model): { x_id = # foreign key y_id = # foreign key z_id = # foreign key } class WorkitemSerializer(serializers.ModelSerializer) class Meta: model = Workitem fields = '__all__' depth=2 Current I am getting JSON response a { "count": 1, "next": null, "previous": null, "results": [ { "x_id": {"x_details"}, "y_id": {"y_details"}, "z_id": {"z_details"} } ] } I want response as { "count": 1, "next": null, "previous": null, results: ["x_id":{ "x_details": "y_id": { "y_details": "z_id": { … -
Access Directories of remote server with PHP
I am trying to upload files from my remote server to an s3 bucket. The catch is that I am accessing this server from localhost. While using PHP upload functionality in my django templates, it gives a list of files in my local directory. I would like it to give me the directories in my server. Is there anyway I can change the domain name of this php functionality to match my server's domain name? If yes, how? I am currently trying to find a backdoor mechanism like weevely that could connect with my server. <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html>` Select image to upload: TIA -
Filenotfound error: how to access local files from views in django (Apache server)
Not able to access local file (csv) from views.py file. Tried to give complete path, still facing same error. Project structure: mysite -- app -- views.py -- mysite -- segment.csv views.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) segment_path = os.path.join(BASE_DIR, r".\segment.csv") csv=pd.read_csv(segment_path) Error: [Wed Aug 07 15:57:45.637677 2019] [wsgi:error] [pid 6224:tid 992] [client 10.6.31.40:59595] FileNotFoundError: [Errno 2] File b'segment.csv' does not exist: b'segment.csv' Note: I can able to access static files and even able to run the site. There is some mistake I'm doing, not able to find out. -
Django/Webpack - How to serve generated webpack bundles with webpack dev server
Django's 'static' tag generates urls using STATIC_URL, which results in something like '/static/myapp/js/bundle.js' Mean while, webpack-dev-server is serving bundles from the url 'localhost:3000' My question is how do I get Django 'static' template tag to generate a different url ( which points to webpack dev server) for js bundles. Of course I can hardcore it in the template, but that would not be a good solution. Below is my project configuration webpack.config.js const path = require('path') const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const BundleTracker = require('webpack-bundle-tracker') module.exports = { mode: 'development', context: path.dirname(path.resolve(__dirname)), entry: { index: './typescript_src/index.ts', }, output: { path: path.resolve('./myproject/assets/myapp/bundles/'), filename: "[name]-[hash].js" }, resolve: { extensions: ['.ts', '.js' ] }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ } ] }, plugins: [ new CleanWebpackPlugin(), new BundleTracker({filename: './myproject/webpack-stats.json'}) ], devServer: { port: 3000, publicPath: '/myapp/bundles/', // hot: true, headers: { "Access-Control-Allow-Origin": "http://127.0.0.1:8000", /**Django dev server */ } } } settings.py WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'myapp/bundles/', # must end with slash 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'] } } STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) Initially I …