Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get the value from drop down and send it to the view.py method
Filter By Year Select Year . this is the code of drop down. i want that the selected one should be send to the views. so i wrote this script code. // Get the current year const currentYear = new Date().getFullYear(); // Set the maximum number of years to display in the dropdown menu const maxYears = 50; // Get the year menu element const yearMenu = document.getElementById("year-menu"); // Set the height of the year menu and add a scrollbar yearMenu.style.maxHeight = "200px"; yearMenu.style.overflowY = "scroll"; // Generate the years dynamically from 1950 to the current year, up to the maximum number of years for (let year = currentYear; year >= 1950 && year > currentYear - maxYears; year--) { // Create a new year item const yearItem = document.createElement("li"); // Create a new year link const yearLink = document.createElement("a"); yearLink.setAttribute("href", "#"); yearLink.textContent = year; // Add an event listener to update the year button when a year is clicked yearLink.addEventListener("click", function() { document.getElementById("year-button").textContent = year; }); // Add the year link to the year item yearItem.appendChild(yearLink); // Add the year item to the year menu yearMenu.appendChild(yearItem); } </script> but if i submit the form. It is throwing the error … -
Celery dockerfile
I'm using Django and celery together in an app(or container) but I want to separate celery in another app(or container). I am not sure how should I do this because my tasks are in the Django app. so how should I set celery parameters in order to access tasks? -
How do I pass kwargs to url when posting data? I keep getting: No ReserveMatch Error
I have spent all day trying but cannot workout what I am doing wrong. I have two views, one loading the main view and one calling a modal to send an email. When I post data through the modal I get a reverse match error and not sure why. Funny enough if I empty a field in the modal it get no error as the pk is there. Please tell me what I am doing wrong. I understand that someone I am not passing the pk back to the template ones data are posted, but how do you do that? Using get_form_kwargs did not work. Error: Reverse for 'application-update' with keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)/$'] Template {% url 'application-update' pk=application_update.id %} {% url 'send-message' %} urls.py re_path(r'^update/(?P<pk>[0-9]+)/$', views.ApplicationViewUpdate.as_view(), name="application-update") re_path(r'^send/$', views.SendMesssageView.as_view(), name="send-message"), ] views.py class ApplicationViewUpdate(UpdateView): model = Application form_class = ApplicationForm template_name = 'update_application.html' context_object_name = 'application_update' success_url = '/update/{id}/' def get_context_data(self, *args, **kwargs): context = super(ApplicationViewUpdate, self).get_context_data(*args, **kwargs) context['id'] = self.kwargs['pk'] application = Application.objects.get(id = context['id']) context['message'] = MessageForm() return context class SendMesssageView(FormView): form_class = MessageForm template_name = 'message.html' context_object_name = 'send_message' success_url = '/send/' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) … -
How to position Django help_text between Label & Input instead of under Input?
I have a custom form where each field is added as a widget, i.e. widgets = { "title": forms.TextInput( attrs={"class": "review-input review-title"}, ), } I also added help_texts in the Meta class of this form i.e. help_texts = { "title": "Help text title", } By default, this puts the help text below the input tag. enter image description here However, I want to place the help text between label & input. The form is generated as {{ form.as_p }} inside a flex-box. Could you please help with that? I already tried to style the generated help text, but it messed the whole form/layout. It would help to have it generated in the right place from the start. -
AttributeError: type object 'Product' has no attribute 'object'
`models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=100) selling_price = models.FloatField() discounted_price = models.FloatField() description = models.TextField() composition = models.TextField(default='') prodapp = models.TextField(default= '') #brand = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) product_image=models.ImageField(upload_to="product") def str(self): return self.title views.py from django.views import View from . models import Product, Cart, Customer def add_to_cart(request): user=request.user product_id=request.GET.get('prod_id') product = Product.object.get(id=product_id) Cart(user=user,product=product).save() return redirect("/cart")` ''' my error: File "C:\Users\SIRI\OneDrive\Desktop\E-com\ec\app\views.py", line 107, in add_to_cart product = Product.object.get(id=product_id) ^^^^^^^^^^^^^^ AttributeError: type object 'Product' has no attribute 'object' [29/Apr/2023 13:08:43] "GET /add-to-cart/?prod_id= HTTP/1.1" 500 67990 ''' I am learner i don't where i did mistake can you please fix it DM me by mail eaglemem78@gmail.com ` -
App is crashed while deploying django app on railway
while deploying my django app it always run collectstatic and asking yes or no. Adding whitenoise didn't solve it . -
The last_run_at time is inconsistent with my current time
Summary: Include a brief description of the problem here, and fill out the version info below. Celery Version: 5.2.7 Celery-Beat Version:2.3.0 Django 4.0.7 Exact steps to reproduce the issue: django settings.py DJANGO_CELERY_BEAT_TZ_AWARE = False TIME_ZONE = 'Asia/Shanghai' USE_TZ = False celery app.conf.timezone = 'Asia/Shanghai' app.conf.enable_utc = False CrontabSchedule 'timezone': app.conf.timezone Detailed information I set the expires property of the task, but the task does not stop executing when it expires. I checked the task data and found that the last_run_at is 8 hours ahead of the current time. I think it might be a time zone issue,but both django and celery I set timezone='Asia/Shanghai' and set enable_utc=False. Can anyone tell me how to solve this problem The last_run_at time is consistent with my current time -
Django capture agent's computer device info
In my web application, I want to capture complete info of agent's computer device and if user logs in my web application on a different device, system will trigger some function. I have already checked django-user-agents but it is not giving complete info, for ex. a user can have same browser(version) and same os family and version on two different computers. In this case my application will not be able to identify whether the user is using same computer device or different. -
Using MediaRecorder i stored video from web camera and than send data by an AJAX call to my django backend. But data is Currupted
Using MediaRecorder i stored video from web camera and than send data by an AJAX call to my django backend. Their im storing video in (mp4 or webM) format. The issue is that stored video is currupted because other than VLC player no other one is running file. The main issue is that than im sending this video to a python code which than extract audio from video. to do this pyhton script first take video duration to process it. As file is currupted, in VLC file is running but duration bar is not showing anything. So, what i think is that data is not storing the way i want. Im new to django and specially to frontend so please help me with this. Suggest me any alternative i just want my video to be stored correctly also with video there is an audio parameter as well. Im separetely sending audio so i somehow bypass the python script which extract audio from video file. But audio sent using AJAX is empty or i think currupted. Here is JS code at frontend side. const preview = document.getElementById("preview"); const startButton = document.getElementById("startButton"); const stopButton = document.getElementById("stopButton"); const recorded = document.getElementById("recorded"); const saveButton … -
How to separate legacy table from Django built-in models?
I have a legacy table that I would like to use in a database-first way. To achieve this, I executed the following command in my Django project directory: python manage.py inspectdb > models.py However, I do not want to modify this database or add any of the Django core models. Instead, I would like to set a local SQLite database for all built-in models, including Auth, User, and Group. In my settings.py file, I have configured two databases as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'admin.db'), }, 'legacy': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blahblah', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, } I understand that there is an option for automatic database routing, but I am unsure what else I need to configure to separate these databases and ensure that the separation works in the Django admin panel. Can you please provide guidance on how to accomplish this? Thank you in advance. -
Background image isn't showing in all apps
I created two apps named as admin and student, admin templates holds base.html and login.html. I set the background image and navbar in base.html. The background image is stored in static/admin/image/background.jpg the same path I gave to set the background for the body tag present inside base.html. Inside the login page I extends base class and override content block and background image shows as well for login.html which is present in same app. but after login i redirect to student apps registration.html page which also extends base.html present inside admin but the background image not shown for students apps any page and it gives error in terminal asNot Found: /display/static/admin/images/baloon.jpg. I added static path to urlpatterns as well but still didn't work I created two app admin, student under one project. admin template holds base.html,login.html. student holds registration.html and display.html. background image set inside base.html. all other web pages extends base.html. background image is shown for login.html but not for student apps HTML pages. It gives an error as Not Found: /registration/static/admin/images/baloon.jpg on the terminal. static file stored under the main project name as 'static' already mentioned in the settings STATIC_URL = '/static/' STATIC_ROOT=BASE_DIR/'static' STATICFILES_DIRS=( BASE_DIR/'staticfiles', ) -
Not Found 404 Error Django Crud Application
i am creating a Django Crud Application.i have it crudapplication while i testing through postman i ran into the problem with Not Found: / [29/Apr/2023 10:40:06] "GET / HTTP/1.1" 404 2272 Not Found: / [29/Apr/2023 10:40:06] "GET / HTTP/1.1" 404 2272 Not Found: /favicon.ico [29/Apr/2023 10:40:07] "GET /favicon.ico HTTP/1.1" 404 2323 Not Found: /users [29/Apr/2023 10:40:11] "GET /users HTTP/1.1" 404 2305 urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from Student import views` urlpatterns = [ url(r'^user$',views.userApi), url(r'^user$',views.userApi), url(r'^user/([0-9]+)$',views.userApi), path('admin/', admin.site.urls), ] -
How to add Tailwind to a React App in django?
I'm trying to build a django app with React and Tailwind. I have checked and tried countless tutorials, now I'm able to preview the react app on http://127.0.0.1:8000/ But the tailwind classes are not working, no matter what I do. I have followed https://tailwindcss.com/docs/guides/create-react-app this tutorial, the css i use is linked correctly because if i add regular css classes I can see the changes. But the tailwind classes are not applied. This is the structure of my django app with react: ┃ ┣ src ┃ ┃ ┣ components ┃ ┃ ┃ ┗ App.js ┃ ┃ ┗ index.js ┃ ┣ static ┃ ┃ ┣ css ┃ ┃ ┃ ┗ index.css ┃ ┃ ┣ frontend ┃ ┃ ┃ ┣ main.js ┃ ┃ ┃ ┗ main.js.LICENSE.txt ┃ ┃ ┗ images ┃ ┣ templates ┃ ┃ ┗ frontend ┃ ┃ ┃ ┗ index.html ┃ ┣ init.py ┃ ┣ admin.py ┃ ┣ apps.py ┃ ┣ models.py ┃ ┣ tests.py ┃ ┣ urls.py ┃ ┗ views.py Any suggestions? I noticed after I run npm run build, the tailwind 'className' is converted to 'class', I don't know if that's expected or a problem. If I change 'class' to 'className' in inspector, the style is still not … -
how to add limit of users in my django channels chat room
i wish to had not more than 2 users limit in my chat room from channels.consumer import SyncConsumer,AsyncConsumer from channels.exceptions import StopConsumer from asgiref.sync import async_to_sync class MySyncConsumer(SyncConsumer): def websocket_connect(self, event): chat_channel_name = self.scope['url_route']['kwargs']['channelname'] async_to_sync (self.channel_layer.group_add)(self.chat_channel_name,self.channel_name) self.send({ 'type':'websocket.accept' }) I want to add limited number of users in my chat room -
Including additional data in Django DRF serializer response that doesn't need to be repeated every entry?
Our Django project sends GeoFeatureModelSerializer responses and we want to include an additional value in this response for JS to access. We figured out how to do this in serializers.py: from rest_framework_gis import serializers as gis_serializers from rest_framework import serializers as rest_serializers from core.models import Tablename class MarkerSerializer(gis_serializers.GeoFeatureModelSerializer): new_value = rest_serializers.SerializerMethodField('get_new_value') def get_new_value(self, foo): return True class Meta: fields = ("date", "new_value") geo_field = "geom" model = Tablename JS can get this value with geojson.features[0].properties.new_value where const geojson = await response.json(), but it's unnecessarily added with every entry. We'd like for it to be included only once so JS can access it with something like newResponse.new_value and existing functionality can continue getting the same data via newResponse.geojson or similar. How can we include a single additional value in this response? We thought maybe wrapping our serializer in another, but they seem to be asking a different thing we don't understand. Can we append this somehow? In the serializer can we do something like newResponse = {'new_value': new_value, 'geojson': geojson} somewhere? We've had a dig through the Django Rest Framework serializers docs and couldn't work it out, so perhaps we're missing something. Other SO threads seem to only ask about adding … -
How do I fix SAML authentication on Heroku app which works fine on localhost?
I have a django app that uses SAML authentication to sign in .edu users. I recently upgraded my packages and after a lot of trial and error, I found a set of packages that all work with each other on Python 3.10. Here are the packages my requirements.txt currently holds that are related to SAML: python3-saml==1.15.0 xmlsec==1.3.13 isodate==0.6.1 six==1.11.0 lxml==4.9.2 SAML authentication for .edu users works fine on localhost but I get the following error when I run the application on Heroku Dev. SAML Response not found, Only supported HTTP_POST Binding I used the SAML tracer to check if I was receiving POST data upon sign in and this is what I found: The Summary tab shows the certificate / key values. On https://herokuapp/account/?acs this is the error: OneLogin_Saml2_Error at /account/ SAML Response not found, Only supported HTTP_POST Binding I have also observed that I can randomly log in using my .edu user sometimes. How can I go about fixing this? -
Django: How to get images from csv file and populate them in Django Image field?
I am trying to save image from CSV file to Product Image Field in Django, this images are already uploaded to an external website so i am finding it difficult populating the image field with the image from the url. Please i need some help to fix this issue This is how my CSV data looks like title price image Item 1 21 http://www.website.com/wp-content-7384/77984357987.jpg ! alt : image-alt Item 2 32 http://www.website.com/wp-content-7854/779534587987.jpg ! alt : image-alt Item 3 433 http://www.website.com/wp-content-2784/72347987987.jpg ! alt : image-alt Product Model class Product(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to=user_directory_path, default="product.jpg") price = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) ... This is how i have been importing data so far from .csv file class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **options): df = pd.read_csv('products.csv') for title, image, price in zip( df.post_title, df.images, df.regular_price): product = Product( title=title, price=price, ) product.save() # How do i process and save image # From the URL in the csv above Some other thing that i have tried doing that did not work class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, **options): df = pd.read_csv('products.csv') for title, image, price in zip( df.post_title, df.images, df.regular_price): images = [] for row in image: product … -
SSL issue in Python Django Elasticsearch environment
I am running a local dockerised Elasticsearch instance for a Python Django project, which I set up by following the elastic docker guide. One of the steps involved downloading a CA cert file. When the container is running I can connect to it using this cert file, or by ignoring certs altogether # both of these work curl --cacert my_cert.crt "https://${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}@localhost:9200" curl -k "https://${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}@localhost:9200" I have then added the ELASTICSEARCH_DSN details to my settings.py file as described in the elasticsearch dsl docs but there is no mention of certificates in the documents, and running commands gives an SSL error: python manage.py search_index --rebuild <snip> elasticsearch.exceptions.SSLError: ConnectionError([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002)) caused by: SSLError([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002)) I'm not sure of the best way to resolve this. Any advice would be appreciated. -
Server not starting because of error in accounts\urls.py
I have no idea what I'm missing, I can't even run the django server without getting an error. This is my accounts.urls and it seems like django cannot find it but I dont know the problem. from django.urls import path from . import views app_name = "accounts" urlpatterns = [ path("login/", views.login_view, name="login"), ] this is my project urls from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView urlpatterns = [ path("", RedirectView.as_view(pattern_name="list_projects"), name="home"), path("admin/", admin.site.urls), path("accounts/", include("accounts.urls")), path("projects/", include("projects.urls")), ] if i comment out the "path("accounts/", include("accounts.urls"))," line the server runs fine. can also post my views and forms if relevant! im new to django -
UnsupportedTokenTypeError when making request to Google Calendar API
I'm attempting to make a request to get a user's events for their calendar in the Google Calendar API using AuthLib and Django. When I get to the schedule view, I get a UnsupportedTokenTypeError stating nsupported_token_type: Unsupported token_type: 'access_token'. Relevant snippets from views.py are below. CONF_URL = "https://accounts.google.com/.well-known/openid-configuration" oauth = OAuth() oauth.register( name="google", server_metadata_url=CONF_URL, client_kwargs={ "scope": "openid email profile https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.readonly" }, ) # Function decorator that checks whether there is an active user def auth_required(func): @wraps(func) def wrapper(request): user = request.session.get("user") if user: return func(request) else: return redirect("/login") return wrapper def login(request): redirect_uri = "http://127.0.0.1:8000/auth/" # TODO: Change URL to match actual URL once hosted return oauth.google.authorize_redirect(request, redirect_uri) def logout(request): request.session.flush() return redirect("/") def auth(request): token = oauth.google.authorize_access_token(request) request.session["user"] = token["userinfo"] return redirect("/") @auth_required def schedule(request): token = request.session.get("user") email = token["email"] url = "https://www.googleapis.com/calendar/v3/calendars/%s/events" % email resp = oauth.google.get(url=url, token=token, request=request) print(resp) return redirect("/") The token when I make the request looks like this: {'at_hash': 'x', 'aud': 'x.apps.googleusercontent.com', 'azp': 'x.apps.googleusercontent.com', 'email': 'x@gmail.com', 'email_verified': True, 'exp': 1682721445, 'family_name': 'Last', 'given_name': 'First', 'iat': 0, 'iss': 'https://accounts.google.com', 'locale': 'en', 'name': 'First Last', 'nonce': 'x', 'picture': '', 'sub': '0'} Is there an additional, different token that I need to retrieve? -
How can I pass data from django to react at render time
The question is fairly simple. I need to pass data from django to a react component. In django, I have a json object being dumped: class PulseHome(TemplateView): template_name = "pulse_murasa/pulse_home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) efestos_queryset = Efesto.objects.filter(deleted=False).order_by('-id') efestos = EfestoSerializer(efestos_queryset, many=True) context['efestos'] = json.dumps(efestos.data) // THIS IS WHAT MATTERS return context In the html, I get the data like this, it logs correctly: <script id="efestos-data" type="application/json"> {{ efestos|safe }} </script> <script> const efestosData = JSON.parse(document.getElementById('efestos-data').textContent); // THIS IS WHAT MATTERS console.log(efestosData); </script> <script src="{% static 'js/main.de0443a6.js' %} "> </script> Then, in my React index.js file, I try to get the data but it is undefined: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import EfestoComponent from './components/pulseHome'; import reportWebVitals from './reportWebVitals'; const efesto_objects = window.efestosData; // THIS IS WHAT MATTERS console.log("efesto_objects: ", efesto_objects); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <EfestoComponent objects={efesto_objects}/> ); I guess it has something to do with timing. I could try to tie everything to a DOMContentLoaded listener, but I wonder if there is a standard way to achieve this. -
Django Modeling relationships based on MultiSelectField
Trying to model this for a Django REST Framework project, and I don't know if this is even realistic to do. The idea is that a User can have one relationship with a Track, and it's defined by one of the three choices for relationship_type, which is a MultiSelectField type field, in a UserTrackRelationship instance. Below, I've mocked up the Track and User fields that I'm trying to define. Can this actually be coded? class Track(models.Model): # owner = ForeignKey relationship, based on instance of UserTrackRelationship, where relationship_type=user_owns_track and this track's ID matches class User(models.Model): # tracks_watching = ManyToMany relationship, all instances of UserTrackRelationship, where relationship_type=user_watching_track and this user's ID matches # tracks_copy_purchased = ManyToMany relationship, all instances of UserTrackRelationship, where relationship_type=user_purchased_copy and this user's ID matches class UserTrackRelationship(models.Model): REALTIONSHIP_CHOICES = (('user_owns_track', 'This User Owns This Track'), ('user_watching_track', 'This User Is Watching This Track'), ('user_purchased_copy', 'This User Has Purchased a Copy of This Track')) user = models.ForeignKey(User, related_name='usertrackrel_user', on_delete=models.CASCADE) track = models.ForeignKey(Track, related_name='usertrackrel_track', on_delete=models.CASCADE) relationship_type = MultiSelectField(choices=REALTIONSHIP_CHOICES, max_choices=1, max_length=1) -
Django - Attempting to deploy app on Heroku
I am attempting to deploy a Django app on Heroku. The instance appears to start and I see the following in the logs when it starts: 2023-04-28T15:36:03.694071+00:00 heroku[web.1]: Starting process with command `gunicorn config.wsgi -- logfile -` 2023-04-28T15:36:05.869274+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [2] [INFO] Starting gunicorn 20.1.0 2023-04-28T15:36:05.869477+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [2] [INFO] Listening at: http://0.0.0.0:14398 (2) 2023-04-28T15:36:05.869516+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [2] [INFO] Using worker: sync 2023-04-28T15:36:05.871197+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [7] [INFO] Booting worker with pid: 7 2023-04-28T15:36:05.908573+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [8] [INFO] Booting worker with pid: 8 2023-04-28T15:36:06.373542+00:00 heroku[web.1]: State changed from starting to up 2023-04-28T15:36:07.000000+00:00 app[api]: Build succeeded However, when I attempt to visit the site (at the Heroku provided URL) I see the following error in the browser: Not Found The requested resource was not found on this server. I see this in the Heroku logs: 2023-04-28T15:37:50.232938+00:00 app[web.1]: 10.1.55.214 - - [28/Apr/2023:15:37:50 +0000] "GET / HTTP/1.1" 404 179 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/112.0" 2023-04-28T15:37:50.233993+00:00 heroku[router]: at=info method=GET path="/" host=sitename.herokuapp.com request_id=77318e40-99f5-47bd-9f29-f828ab07097f fwd="71.81.213.118" dyno=web.1 connect=0ms service=293ms status=404 bytes=343 protocol=https 2023-04-28T15:42:26.163509+00:00 heroku[router]: at=info method=GET path="/" host=sitename.herokuapp.com request_id=b6490fc8-a242-4214-a39d-657f0e295f68 fwd="71.81.213.118" dyno=web.1 connect=0ms service=119ms status=404 bytes=343 protocol=https 2023-04-28T15:42:26.163514+00:00 app[web.1]: 10.1.50.56 - - [28/Apr/2023:15:42:26 … -
Logging out on django user authentication redirects to django admin logout page
I am learning to create a simple website using Django's LocalLibrary tutorial. I just used Django's authentication system to create a default view for logging in and logging out users on my page. However, when I log out, Django does not redirect to the template I created to display that the user has been logged out. Instead, it redirects to the Django admin logout page.There is also an issue where functions other than login, including the password reset form and the HTML for changing passwords, cannot be rendered correctly. Here is my base urls.py file. from django.contrib import admin from django.urls import path from django.urls import include from django.views.generic import RedirectView urlpatterns += [ path('catalog/', include('catalog.urls')) urlpatterns += [ path('', RedirectView.as_view(url='catalog/', permanent=True)), ] # Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] Here is my base.html template. <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Local Library</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> … -
How to debug a test in visual studio code?
Attempts to debug a test fail with Error discovering unittest tests: Failed to import test module: tests. Yet the only existing test file runs without error in the terminal. Testing is necessary - I'm just getting started with Python! The question is how do I configure either VSC and/or the Django code to allow debugging of tests? I've tried both unittest & pytest to no avail. Environment: Visual Studio Code 1.77.3, Python 3.11.3, Django 4.1, Windows 10 Pro Test objective: create a dictionary of dictionaries; includes access to test database Test Explorer: Error discovering unittest tests: Failed to import test module: tests Traceback: Traceback (most recent call last): File "C:\Python311\Lib\unittest\loader.py", line 407, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\unittest\loader.py", line 350, in _get_module_from_name __import__(name) File "g:\workspace\python-land\diet\reaction\tests.py", line 4, in <module> from reaction.models import Reaction File "g:\workspace\python-land\diet\reaction\models.py", line 4, in <module> class Reaction(models.Model): File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\db\models\base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\conf\__init__.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or …