Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user authentication and login problem
I created a signup and signin form. when I create a user using signup it is working perfectly and creates user. but when i try to login with same user it is not able to login. It actually go to else block and show the wrong credential messages. whenever I try to login with my existing user it shows wrong credential. can anyone help me how can I solve this issue. Thank you else block error msg even after correct user users I createdlogin window view.py file from django.shortcuts import render, HttpResponse, redirect from .models import Contact from django.contrib import messages from blog.models import Post from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def handleSignUp(request): if request.method == 'POST': username = request.POST.get('username') fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') pass1 = request.POST.get('pass1') pass2 = request.POST.get('pass2') #check verify sign field if len(username) > 10: messages.error(request, 'User name must not more than 10 characters') return redirect('/') if not username.isalnum(): messages.error(request, 'User name must contain alpha numeric characters') return redirect('/') if pass1 != pass2: messages.error(request, 'Password did not match') return redirect('/') #create user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, 'You account has … -
not able to get the driver version pyodbc
Unable to start Django application due to pyodbc error django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') i have tried printing the driver used but do net get any driver info import pyodbc print(pyodbc.drivers()) this is the result of the above ['SQL Server'] any ideas? -
Run Django tests on Heroku CI with postgres extensions
Overview I have an app that is deployed on Heroku and uses Heroku Postgres add-on as the default database. I use PostGIS and Hstore extensions to store geographic and Hstore(key-value pair) data. Problem Statement I am configuring Heroku CI to run the test-cases. As the Django application creates a test database during the test run, I need to provision one for it. But I know that the Heroku's in-dyno database does not support postgis and hstore extension. So I provisioned a free-tier hobby-dev heroku postgres add-on for it. Now I get the following error: Got an error creating the test database: permission denied to create database Below is my app.json config: { "environments": { "test": { "scripts": { "test-setup": "pip install -r requirements.txt", "test": "python manage.py test -v 2 --noinput" }, "addons": [ "heroku-postgresql:hobby-dev", "heroku-redis:in-dyno" ], "buildpacks": [ { "url": "heroku/python" }, { "url": "https://github.com/heroku/heroku-geo-buildpack" } ] } } } The key questions here are: Is it advised to use in-dyno Postgres or provide it as an add-on? If in-dyno Postgres, how do I install the extensions? If as an add-on, how do I run the Django tests using the provisioned database? (as it doesn't allow me to create a … -
Send Dynamic js value stored in variable to the django python backend
Adding popup and displying the selected value from the drop down. when submit button is clicked sending data to the django python backend view to save in mysql db. currently storing the value in a variable i.e OS Value Submit Cancel <script> $('#submit_add').click(function(){ var osvalue = $('#id_os_make option:selected').text(); alert(osvalue); var data2 = $('#id_host_protocol option:selected').text(); var reason = $('#textbox').val(); alert(reason); var confirmBox = $('.confirm-box'); confirmBox.css('display', 'none'); }); -
Django tabularinline from different app models
I am new with Django. My question is how to showing the data as Tabularinline in DetailView in django from two different apps,. I have a Team model in users app and Project and Client in projects app. I want to show all the projects that belong to a specific team in team delailview. my issue is how to show the results in the template form, the results are shown in the django admin but i cant show them in the html code i wrote, here is the codes: 1st App: CustomeUser class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) memberOf = models.ManyToManyField("Team", blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('team_detail', args=[str(self.pk)]) second app Project class Client(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="client_team") title = models.CharField(max_length=150, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title class Project (models.Model): team= models.ForeignKey(Team,on_delete=models.CASCADE ) client=models.ForeignKey(Client,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150, null=False, blank=False) notes = models.TextField( null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) purchase_number= models.CharField(max_length=50, null=True, blank=True) PO_date = models.DateTimeField( blank=True, null=True) completion_date = models.DateTimeField( … -
Does slug url with id is accepted by Google in django
Does slug url with id is accepted by Google? I mean when I add website and pages to Google search console for example example.com/url-1 ? i mean www.example.com/pubg-mobile-4 is that valid URL and accepted by Google? -
Django migration sqlmigrate
I have created a migration file to alter unique key constraint of a model, previously it had 4 fields in unique key , now its has 5 , after running migrate command its worked fine. but now i am unable to generate sql query using sqlmigrate. Error is "ValueError: Found wrong number (0) of constraints for rule_set(business_function_id, business_process_id, process_state, status)" In My DB right now constraint is :- UNIQUE KEY rule_set_business_function_id_bus_6bda6da3_uniq (business_function_id,business_process_id,process_state,rule_set_name,status), What did i do wrong? -
'Request' object has no attribute 'pop' in Django Rest Framework?
I have a Post model which has Foreign key with User model. So when I created Post object I need to pass user instance by overriding the create method inside ModelViewSet but it failed. here is what I have tried: models.py class Post(models.Model): author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() serializers.py class PostSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="api:posts-detail") author = UserSerializer() class Meta: model = models.Post fields = ['url', 'id', 'author', 'title', 'content'] views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = serializers.PostSerializer def get_queryset(self, *args, **kwargs): user = self.request.user return models.Post.objects.all().filter(author=user) permission_classes_by_action = { 'create': [permissions.IsAuthenticated], 'list': [permissions.IsAuthenticated], # other permissions.. } def create(self, validated_data): author = validated_data.pop('author_id') print(author) post = models.Post.objects.create(author=author, **validated_data) return post def list(self, request, *args, **kwargs): return super(PostViewSet, self).list(request, *args, **kwargs) # other methods def get_permissions(self): try: # return permission_classes depending on `action` return [permission() for permission in self.permission_classes_by_action[self.action]] except KeyError: # action is not set return default permission_classes return [permission() for permission in self.permission_classes] the whole error I got Traceback (most recent call last): File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", … -
From PHP to Python [closed]
I kindly request for a refactoring of this PHP code to Python. <?php $response_data = file_get_contents("php://input"); $logFile = "response.json"; $log = fopen($logFile, "a"); fwrite($log, $response_data); fclose($log); ?> -
Aggregate result in django rest framework
In my posgresql I have a model "words": class Words(models.Model): word = models.CharField(db_index=True, max_length=50) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) time_stamp = models.TimeField(auto_now=False, auto_now_add=False) In my view, after a query, I search for words that icontains the query itself A lot of words are duplicated and i need to aggregate them in the result My goal is to respond with a json file that collects the various words and lists their timestamps Something like this: [ { "word": "foo", "list": [ { "id": 10416, "lesson": 11, "time_stamp": "00:02:49.100000" }, { "id": 10702, "lesson": 12, "time_stamp": "00:27:31.300000" }, ... ] }, { "word": "too", "list": [ { "id": 10416, "lesson": 11, "time_stamp": "00:02:49.100000" }, { "id": 10702, "lesson": 12, "time_stamp": "00:27:31.300000" }, ... ] }, ] Is there a smart way to do this? -
How to make a function not included in a rollback?
Let's say I have 3 functions A, B, C. Function B calls Function A and Function C calls Function B. def function_A(): # do something here @transaction.atomic def function_B(): # some code function_A() # calls function A @transaction.atomic def function_C(): try: SomeModel.objects.get(id=id) except SomeModel.DoesNotExist: pass # calls function B function_B() # I don't want this to rollback when something fails here # code that fails and rollsback everything When something fails in functionC it seems that it also rollsback function A, is it possible to make sure function A doesn't get rolledback when function C fails? If so how do I that? -
Update auto_now field in bulk_update
I'm using Django 2.2 and I have a model with auto_now "modification_datetime" field and I need to update it during/after a bulk_update execution only for the affected registries that were really updated. Is it possible to update auto_now datetime model field only on the affected records by bulk_update execution? -
DjangoRestFramework: How to pass value in url?
I've created a simple api using DjangoRestFramework, which adds 3 number: @api_view(["GET"]) def calcDistance(request): a = request.query_params.get('a') b = request.query_params.get('b') c = request.query_params.get('c') r = int(a) + int(b) + int(c) return JsonResponse({"Print": "r={}".format(r)}, status=status.HTTP_200_OK) API call: http://127.0.0.1:8000/calcDistance/?a=2&b=3&c=5 Output: {"Print": "r=10"} Now I want to call API without passing variable names(a,b and c) in url: e.g.: http://127.0.0.1:8000/calcDistance/?2&3&5 Can someone help me to achieve this? -
django (rest framework) serializer usage for incoming and outgoing data
I am new to Django and have a question regarding the serializers. Is a serializer about INCOMING data (from the body) or also about returned data? For example if I have a request with an incoming body of {"test":1} and it returns data like {"new_test": True}, how would I describe this in a serializer? -
django mail with attachment and body text issue
In django i am not able to send body html with attachment . what i am doing wron here i dont know can any one please help me related this ? my code is given below. def mail_booking_invoice(request): result = {} if request.method == 'POST' and request.is_ajax(): try: boking_id = request.POST.get('id') config = EmailConfiguration.objects.filter(pk=1).first() connection = get_connection( host=config.host, port=config.port, username=config.from_email, password=config.password, use_tls=config.tls, ) bookingObj = Booking.objects.get(id = boking_id) email_to = '' if bookingObj.patient_email and bookingObj.contact_person_email == '': email_to = bookingObj.patient_email else: email_to = bookingObj.contact_person_email config = EmailConfiguration.objects.filter(pk=1).first() if email_to!='' and config: all_objects = Booking.objects.filter(id=boking_id) data = serializers.serialize('json', all_objects) json_objects = json.loads(data) customObj = [] for index in range(len(json_objects)): json_objects[index]['fields']['id'] = all_objects[index].id bookingStops = BookingStop.objects.filter( booking_id=all_objects[index].id) bookingStatus = BookingStatus.objects.get( booking_id=all_objects[index].id, status=3) json_objects[index]['fields']['stops'] = bookingStops json_objects[index]['fields']['price'] = bookingStatus.price json_objects[index]['fields']['vehicle_no'] = bookingStatus.vehicle.vehicle_no json_objects[index]['fields']['driver_name'] = bookingStatus.driver.first_name + \ ' ' + bookingStatus.driver.last_name json_objects[index]['fields']['booking_date__format'] = all_objects[index].pickup_date.strftime( "%m/%d/%Y") customObj.append(json_objects[index]['fields']) from django.core.mail import send_mail from django.core import mail from django.core.mail import EmailMessage html = render_to_string('admin/booking/invoice.html',{'result': customObj}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=invoice' + '.pdf' pdf = weasyprint.HTML(string=html,).write_pdf(stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) subject = "Booking invoice" htmls = "Hello Neha,<p> Please find your Booking Invoice in attachement</p>Thanks & Regards Hirbuu.com'" mail.send_mail('subject', 'plain_message', config.from_email, [email_to], html_message=htmls,connection=connection) # EmailMessage.attach("invoice" + '.pdf', … -
How to redirect is_staff user to custom template in Django?
I have a simple issue: I tried to redirect the login page to another page depending on the user role(staff/normal). Normal user have their own dashboard and staff user have the overall dashboard. The redirect function for normal user work perfectly fine. However, for the staff user, it keep redirect me to django-admin page instead of my custom template. I have tried this but it is not working. Staff Redirected Page views.py #login def login(request): if request.user.is_authenticated: if request.user.is_staff: return redirect('staff_dashboard') else: return redirect('user_dashboard') else: if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = auth.authenticate(request,username=username,password=password) if user is not None: if user.is_staff: auth.login(request,user) return redirect('staff_dashboard') else: auth.login(request,user) return redirect('user_dashboard') else: messages.info(request,"Username or Password is incorrect") return redirect('login') #staff_dashboard @login_required(login_url='login') def staff_dashboard(request): vid_size = [] img_query_set = model_images.objects.all() img_query_set_count = model_images.objects.all().count() vid_query_set = model_videos.objects.all() vid_query_set_count = model_videos.objects.all().count() for item in vid_query_set: size = round(item.vid_path.size / 1000000,1) vid_size.append(size) context = { "img_query_set": img_query_set, "vid_query_set": vid_query_set, "img_query_set_count": img_query_set_count, "vid_query_set_count": vid_query_set_count, } return render(request,'admin/index.html',context) urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home'), path('login', views.login, name='login'), path('user/dashboard', views.user_dashboard, name='user_dashboard'), path('staff/dashboard', views.staff_dashboard, name='staff_dashboard'), ] -
Django paginate huge millions data
I'm trying to handle 6 million row data with django pagination, my request taking really long time. get_query_set = self.get_queryset(). # it takes 1 second queryset = self.filter_queryset(get_query_set) # it takes 1 second page = self.paginate_queryset(queryset) # it takes 20 second serializer = self.get_serializer(page, many=True) # it takes 1 second After query to oracle queryset return almost 6 million row. It looks like pagination taking long time. Is there any suggestion, what should i do? I use Django==3.1.1 Thank you so much -
Django rest framework viewsets method return HTTP 405 Method Not Allowed
I am developing a cart api where add item in cart and remove. I craete a CartViewSet(viewsets.ModelViewSet) and also create two method in CartViewSet class add_to_cart and remove_from_cart..But when I want to add item in cart using add_to_cart and remove using romve_from_cart method then got HTTP 405 Method Not Allowed.I am beginner in building Django rest api.Please anyone help me. Here is my code: my configuration: Django==3.1.1 djangorestframework==3.12.0 models.py: from django.db import models from product.models import Product from django.conf import settings User=settings.AUTH_USER_MODEL class Cart(models.Model): """A model that contains data for a shopping cart.""" user = models.OneToOneField( User, related_name='user', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CartItem(models.Model): """A model that contains data for an item in the shopping cart.""" cart = models.ForeignKey( Cart, related_name='cart', on_delete=models.CASCADE, null=True, blank=True ) product = models.ForeignKey( Product, related_name='product', on_delete=models.CASCADE ) quantity = models.PositiveIntegerField(default=1, null=True, blank=True) def __unicode__(self): return '%s: %s' % (self.product.title, self.quantity) serializers.py: from rest_framework import serializers from .models import Cart,CartItem from django.conf import settings from product.serializers import ProductSerializer User=settings.AUTH_USER_MODEL class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email'] class CartSerializer(serializers.ModelSerializer): """Serializer for the Cart model.""" user = UserSerializer(read_only=True) # used to represent the target of the relationship using its __unicode__ … -
Django, CSRF, iFrames and Safari
The question here is similar to the one referred to by the link below but this link is 8 years old, python, Django and Safari have all moved one since then. I would like to know if the solution is still relevant or if there is a new way of solving this. Also, these solutions do not describe the resolution in detail. Django Iframe Safari Fix The problem: When a view has an iFrame loaded from a non-same-site and that iFrame attempts to write to a cookie, Django logs the user out. Thanks! -
Adding font awesome icon as placeholder in django
I want to add a font awesome icon together with a username as a placeholder. I tried using mark safe but did not work. The snippet relating to that part is below username_placeholder = f'''{ mark_safe('<i class="fas fa-user"></i>')} username''' widgets = { 'username': forms.TextInput(attrs= {'placeholder': username_placeholder }), 'email': forms.EmailInput(attrs= {'placeholder': 'email'}) } The full code class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'placeholder': 'Password' } )) confirm_password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'placeholder': 'confirm Password' } )) class Meta: model = User fields = ('username', 'email',) username_placeholder = f'''{ mark_safe('<i class="fas fa-user"></i>')} username''' widgets = { 'username': forms.TextInput(attrs= {'placeholder': username_placeholder }), 'email': forms.EmailInput(attrs= {'placeholder': 'email'}) } labels = { 'username': _(''), 'email':_('') } help_texts = { 'username': None } def clean_confirm_password(self): cd = self.cleaned_data if cd['password'] != cd['confirm_password']: raise forms.ValidationError('Passwords do not match') return cd['password'] -
How can I handle POST data in django middleware?
I have Django middleware to handle POST request. class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, req): response = self.get_response(req) # want to do something with 'r.body', # but it is not able to be read return response As the request body is already read in get_response, I cannot read it again in middleware. Tried copy.copy(), but no luck since the copied stream references same object of the original one. copy.deepcopy() raises an exception. How can I handle POST data in middleware? I want to handle all requests, so implementing the logic in every view is not ideal. -
Count view not working on navbar after chancing page
I have a page with a navbar where the count of posts work very well, but after I go to a other page, lets say to contacts the counts display as (). How can I fix this problem? Thanks on index.html the result is : total posts (43434) on contacts.html the result is : total posts () index.html <div> total posts ({{ postcounts }}) </div> views.py def index(request): posts = Post.objects.filter(active=True) pcounts = posts.count() context = { 'postcounts':pcounts, } return render(request, 'posts/index.html', context) -
Django - I cant migrate my database because of my forms.py
I am trying to migrate my django project but there is this error: (venv) F:\repos\meetmetrics.eu>python src\manage.py migrate Traceback (most recent call last): File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: blog_category The above exception was the direct cause of the following exception: Traceback (most recent call last): File "src\manage.py", line 21, in <module> main() File "src\manage.py", line 17, in main execute_from_command_line(sys.argv) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\commands\migrate.py", line 65, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\urls\resolvers.py", line 577, in … -
Django - TestCase - response.status code failing
Hello everyone out there, I'm starting my journey trough django test-code. The start is not great. I'm starting some very basic testing ( tough important) as follows: from django.test import TestCase, SimpleTestCase from django.urls import reverse # Create your tests here. class RegistryTest(SimpleTestCase): def test_homepage_status(self): response = self.client.get('Registry/search/') self.assertEqual(response.status_code, 200) def test_homepage_url_name(self): response = self.client.get(reverse('search')) self.assertEqual(response.status_code, 200) def test_homepage_template(self): response = self.client.get('Registry/search/') self.assertTemplateUsed(response, 'registry/search_registry.html') here is my urls.py: from django.contrib import admin from django.urls import include from django.urls import path from django.conf.urls import url from .views import * app_name = 'registry' urlpatterns = [ path('search/', search, name='search'), #customerSupplier path('customerSupplier/detail/<int:idCS>/', detail_customerSupplier, name='detail_customerSupplier'), path('customerSupplier/new/', new_customerSupplier, name='new_customerSupplier'), ] this is my search view from views.py: def search(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): azienda = form.cleaned_data['Company'] testo = form.cleaned_data['RagSociale'] tipo = form.cleaned_data['Tipologia'] result = CustomerSupplier.search(azienda, testo, tipo) return render(request, 'registry/search_registry.html', {'form': form, 'CustomerSupplierList':result }) else: form = SearchForm() return render(request, 'registry/search_registry.html', {'form': form }) when I run the test i get back this error: python manage.py test Registry System check identified no issues (0 silenced). FFE ====================================================================== ERROR: test_homepage_url_name (tests.RegistryTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/carloc/Projects/100_CogniSpa/gestionale-cogni/src/Registry/tests.py", line 13, in test_homepage_url_name response = self.client.get(reverse('search')) File "/home/carloc/.local/lib/python3.7/site-packages/django/urls/base.py", line 90, in … -
Why my static files don't load with django and next js
In my django project, I created a frontend folder and i unpackage my react theme (I have download a Next.js theme for free) : public, src, .gitignore, next.config.js, package.json, package-lock.json, readme.md I have install project's dependencies : npm install with npm run build && npm run export, in the frontend folder are generated .next and out folders urls.py : from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), ] settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/out'), ], .... ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/out/_next/static') ] with python3 manage.py runserver I see the index.html but whitout static files