Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I set a password for a Custom User model inside the Django admin page?
I have defined a custom user model using AbstractBaseUser class. Below is the implementation for your reference. #models.py class UserManager(BaseUserManager): def create_user(self, email, firstname, lastname, contact, password): if not email: raise ValueError('You must provide an email address') if not contact: raise ValueError('You must provide a contact number') email = self.normalize_email(email) user = self.model(email=email, firstname=firstname, lastname=lastname, contact=contact) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, firstname, lastname, contact, password): user = self.create_user(email, firstname, lastname, contact, password) user.is_admin = True user.save(using=self._db) return user class Users(AbstractBaseUser): id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) contact = models.CharField(max_length=10, unique=True) email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname', 'lastname', 'contact'] objects = UserManager() def save(self, *args, **kwargs): if not self.firstname or not self.lastname or not self.contact or not self.email or not self.password: raise ValueError('All required fields must be provided') super().save(*args, **kwargs) def __str__(self): return str(self.id) + '. ' + self.firstname + ' ' + self.lastname def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True class Meta: db_table = 'users' verbose_name_plural = 'Users' Everything works well apart from setting password for a new user or updating same for an existing user in Django's native … -
Custom backend for Python Social Auth encounters error saying "issubclass() arg 1 must be a class"
I'm attempting to create a custom backend (Ping Identity) in Python Social Auth for a Django project following these directions: https://python-social-auth.readthedocs.io/en/latest/backends/implementation.html. I've tried using my own custom backend for Ping Identity and the GitHubOAuth2 example that is found within the documentation, but I keep getting an error saying "issubclass() arg 1 must be a class". When I step through the code it seems that PSA thinks my custom class is not a subclass of BaseAuth. This check is found in social_core/backends/utils line 35: if issubclass(backend, BaseAuth): BACKENDSCACHE[backend.name] = backend My Ping Identity code looks pretty much the same as the example in the documentation, so lets look at that code: from social_core.backends.oauth import BaseOAuth2 class GitHubOAuth2(BaseOAuth2): """GitHub OAuth authentication backend""" name = 'github' AUTHORIZATION_URL = 'https://github.com/login/oauth/authorize' ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ',' EXTRA_DATA = [ ('id', 'id'), ('expires', 'expires') ] def get_user_details(self, response): """Return user details from GitHub account""" return {'username': response.get('login'), 'email': response.get('email') or '', 'first_name': response.get('name')} def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" url = 'https://api.github.com/user?' + urlencode({ 'access_token': access_token }) return self.get_json(url) The class uses BaseOAuth2 -> OAuthAuth -> BaseAuth, so I'm not sure why PSA is complaining. My settings.py (project_name.project_name.settings) … -
Get QuerySet in View by number page, paginator drf
I have a view with pagination. class CatalogList(generics.ListAPIView): pagination_class = MyOwnPagi serializer_class = ProductSerializer queryset = Product.objects.all() I receive a page number by GET parameter as {'current_page': 10} So, if I receive, for example a request by {'current_page': 12}, how can I get this part of queryset in view? Like: def get_queryset: self.paginator.page.get(12) I hope I've made myself clear) -
I’m dealing with an error when I run server in Django
PS C:\Users\besho\OneDrive\Desktop\DjangoCrushcourse> python manage.py runserver C:\Users\besho\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'C:\Users\besho\OneDrive\Desktop\DjangoCrushcourse\manage.py': [Errno 2] No such file or directory PS C:\Users\besho\OneDrive\Desktop\DjangoCrushcourse> So I created a django file called lecture3 and an app called hello but when I start run server it shows me this error -
django runserver error no such file in directory
I downloaded the django web framework for python but struggle to run my server online with the help of the python3 manage.py runserver command. I've already tried it it without the 3 in the command but without luck. Everytime I try to run the python3 manage.py runserver command I get the following Error message: (I left out some lines where my user data is mentioned.) can't open file : [Errno 2] No such file or directory I expected it to give me a link to my newly created django server though haven't had much success yet. -
Every request sent with fetch() has a different sessionId cookie, which prevents me from tracking the session across requests
I have a react front-end application running on localhost:3000, and a Django backend server running on 127.0.0.1:8000 I am sending the request from a function using fetch() Using both widthCredentials and Access-Control-Allow-Credentials is probably overkill but I am trying anything at this point. const response = await fetch(url, { method: 'POST', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Credentials': 'true', 'withCredentials': 'true', }, body: JSON.stringify(data) }) In my Django backend I have installed django-cors-headers and set all settings correctly AFAIK. Djang is not complaining about any requests so I believe my Django setup is correct. For some reason the sessionId cookie in every request is different so I can't use it to track a session across requests. Instead Django creates a new session for each request. Django settings INSTALLED_APPS = [ .... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", "cache-control", "pragma", "access-control-allow-credentials", "withCredentials", ] # use file to store sessions SESSION_ENGINE = 'django.contrib.sessions.backends.file' SESSION_FILE_PATH = "/home/gilles/Projects/personal-assistant/backend/assistant_backend/sessions_file" SESSION_COOKIE_NAME = 'sessionid' SESSION_COOKIE_DOMAIN = "localhost" SESSION_COOKIE_SECURE = True # if this is to TRUE cookies dont work propoerly, … -
django updateview define clean_attr on automatic form
I'm deriving from UpdateView, and I would like to use the automatic form, but add a validation test for a field. ModelForm offers clean_, which is just what I need. My problem is overriding that method on a class that my code is not building I can do this... but is there a cleaner way ? def check_myattr(self): data = self.cleaned_data["myattr"] if anything_wrong(data) : raise ValidationError("not like that") return data class SomeEditView(UpdateView): model = Some fields = ('myattr', 'more') template_name = "/some_edit.html" def get_form(self, form_class=None): """Return an instance of the form to be used in this view.""" if form_class is None: form_class = self.get_form_class() setattr(form_class, 'clean_myattr', check_myattr) return form_class(**self.get_form_kwargs()) -
Get field value from Django model
I have a rental apartment booking page and the user has to state their arrival and departure dates in a booking form. I am trying to set up a date validator function that doesn't allow the picked departure date to be before the arrival date. For this I need to get the value of the entered arrival_date field to use in the departure_before_arrival( ) function. Could anybody help out? models.py def departure_before_arrival(value): if value < ??arrival_date??: raise forms.ValidationError("Your departure date must be after your arrival date!") return value class Booking(models.Model): [...] arrival_date = models.DateField() departure_date = models.DateField(validators=[departure_before_arrival]) [...] I have been trying the suggested methods from this post but none work for me. I have also tried def get_value(self, obj): return getattr(obj, self.name) def departure_before_arrival(value): if value < get_value(Booking, self.arrival_date): raise forms.ValidationError("Your departure date must be after your arrival date!") return value but keep getting a NameError "name 'arrival_date' is not defined" -
Django e-mail not sending [duplicate]
I've been trying to send a confirmation mail upon registering through the django-email-verification app. However, despite having no error being shown, no e-mail is received. My web app is hosted on PythonAnywhere (Paid plan). I have tried multiple e-mails and multiple debugging. No shots. Here is the code : class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['email', 'password1', 'password2'] def save(self, commit=True): [...] if commit: user.save() send_email(user) user.is_active = False return user The send_email function brings to this : def send_inner_thread(user, kind, token, expiry, sender, domain, subject, mail_plain, mail_html, debug, context): domain += '/' if not domain.endswith('/') else '' [...] try: msg.send() # Attempt to send the email print("Email sent successfully!") except Exception as e: print(f"Error sending email: {e}") And here's my console log : 2024-05-31 17:08:48 <django.core.mail.message.EmailMultiAlternatives object at 0x7f78fff17bb0> 2024-05-31 17:08:48 Content-Type: multipart/alternative;#012 boundary="===============XXXXXXXXXX=="#012MIME-Version: 1.0 [... rest of the mails infos ... ] 2024-05-31 17:08:48 Email sent successfully! Here's my settings.py : EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "MAIL@gmail.com" EMAIL_HOST_PASSWORD = 'APP PWD' EMAIL_PORT = 587 EMAIL_USE_TLS = True Any help is very welcome ! Thanks for reading :) -
ugettext_lazy - app1 passing django messages to app2. Messages do not get translated in app2, strings get translated in app1
I am managing two django apps built by third parts. One of these app manages a UI (app-ui), while the other one is a backend app (app-api). Now, app-api uses django messages. The default language is english, and the author made transaltions in italian. The translations are collected in the file app-api/apps/sub_app1/locale/it/LC_MESSAGES/django.po. The django function used to manage the translated messages is ugettext_lazy from django.utils.translation import ugettext_lazy as _ Furthermore, app-api has other apps. One of these is sub_app. This one has models, defined in sub_app1/models.py together with some data validations. Among those ones there is this one: if client.status != ACTIVE: raise ValidationError(_(f'customer {customer.name} not active')) When the user navigates app-ui, it fires requests towards app-api, and if the above condition is met, the ValidationError is raised, and the error message 'customer {customer.name} not active' is passed to app-ui, which shows it at the top of the window. I have added and changed the transations for app-api in app-api/apps/sub_app1/locale/it/LC_MESSAGES/django.po, run django-admin makemessages and django-admin compilemessages , changed my browser setting to request for pages in italian, and I obtained every marked string appearing successfully translated in app-api. However, the strings that are printed as django messages in app-ui do … -
How can I use Django Auth username to fetch new content from a PostgreSQL database?
im trying to do a simple crud proyect with django and postgresql, How can I use Django Auth username to fetch new content from a PostgreSQL database? i want use the username like id, to bring the content from the database -
How to correctly make a query to database with Django ORM?
I have stuck in how to write query to avoid for loops Calculation of the number of sick days during the period of the first creation of the sick object for an employee + 365 days (That is, during the period of the year after the first creation of the object) After the year, the counter should reset and after the iteration will go from the first creation of the object after the date (the first sick object + 365 days) I have two models class Employee(Model): birth_name = CharField(_('Nom De Naissance'), max_length=120) last_name = CharField(max_length=120, verbose_name="Nom D'Usage") first_name = CharField(_('Prénom'), max_length=120, unique=True) class Sick(Model): class TypeSick(Enum): Initial = 'Initial' Prolongation = 'Prolongation' Accident_Travail = 'Accident Travail' Accident_Trajet = 'Accident Trajet' Congés_Maternités = 'Congés Maternités' AUTRES = 'Autres' type_sick = CharField( max_length=120, choices=choice_handler(TypeSick), ) start_date = DateField( editable=True, null=False, blank=False ) end_date = DateField( editable=True, null=True, blank=True ) after_year = DateField(editable=True, null=True, blank=True) employee = ForeignKey( Employee, on_delete=SET_NULL, null=True, blank=True, verbose_name='Employe', related_name='sick', ) Here what i've done for get a first sick object of every employee and count his end year +365 days def save_sick_end_year( request: HttpRequest, sick_model: Model, type_sick: str, employee_model: Model, ) -> tuple[ QuerySet[Model, dict[str, dt.date]], QuerySet[Model, … -
Form Validation message for Password Confirmation Field
I have below code in forms.py file. from django.contrib.auth.forms import UserCreationForm from .models import User class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ('first_name','last_name','email','date_of_birth', 'gender', 'user_type', 'phone', 'address','photo', 'password' ) error_messages = { field: { 'required': f"{field.replace('_', ' ').title()} is required." } for field in fields } I would like to add 'password_confirmation' field in fields tuple. I would like to use Form validation message like below in my HTML template. <label class="form-label">PassWord Confirmation</label> <input type="password" class="form-control" name="password2" /> {% if form.confirm_password.errors %} <div class="alert alert-danger">{{ form.confirm_password.errors }}</div> {% endif %} But I am getting errors django.core.exceptions.FieldError: Unknown field(s) () specified for User. -
password_confirmation in forms.py
Can I add password_confirmation in fields ? I am getting error. # forms.py from django.contrib.auth.forms import UserCreationForm from .models import User class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ('first_name','last_name','email','date_of_birth', 'gender', 'user_type', 'phone', 'address','photo', 'password', 'password_confirmation' ) -
How to get counts based on multiple conditions with grouping in a single query in django orm?
Suppose that I have the following customer model: class Customer(models.Model): name = models.CharField() city = models.CharField() first_joined = models.DateField(auto_now_add=True) last_visited = models.DateField() def __str__(self): return self.name The last_visited field is updated by the code whenever a customer visits the store. Now, I want to see that in a particular time period, how many new customers joined the store, and how many total customers visited the store. I need this information to be grouped by city. The output is expected to be something like: city | new | visitors ------------------------------- A | 12 | 24 B | 34 | 43 C | 9 | 21 Currently I am doing it in two seperate queries like this: visited = Customer.objects.filter(last_visited__gte=from_date, last_visited__lte=to_date).values("city").order_by("city").annotate(count=Count("id")) new_customers = Customer.objects.filter(first_joined__gte=from_date, first_joined__lte=to_date).values("city").order_by("city").annotate(count=Count("id")) But I don't prefer this approach for two reasons: It makes the database go through the same set of customers twice while this could be done in one traversal only. It leads to two different dictionaries which is then required to be combined into just one dictionary, which again is an inefficient process. I have gone through this question, but it only concerns multiple conditions but not how to group them. Is there a way to do … -
Django admin negative search
Is there an easy and intelligent way to make admin search for Django-admin, that shows instances, that DON'T have searched value. For example User(name="Name") -> UserAdmin.search_fields = ("name",) -> searching for "a" -> User is not shown searching for "b" -> User is shown Watched through internet - did not find even close solutions. I'll check docs, but maybe someone already knows the answer. -
Why is Django not giving me a list of articles from the for loop
Right, why is Django no bothering to give me a list of articles, despite me correctly setting up the for loop in my template? `from django.db import models import random, string def generate_unique_id(charlimit): '''This will generate a random set of numbers and letters which will be used to generate a unique URL for each object in the model. ''' random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=charlimit)) # Generates a random string return f"{random_string}" Create your models here. class MediaModule(models.Model): article_identifier = models.CharField(max_length=50, default=generate_unique_id(12), unique=True, editable=False) article_headline = models.CharField(max_length=100) article_body = models.TextField() article_synopsis = models.TextField(null=True) article_journalist = models.CharField(max_length=20) article_date = models.DateTimeField(auto_now=True) article_image = models.ImageField(upload_to='media/assets') article_image_summary = models.TextField(default="", null=True, blank=True) def __str__(self): return self.article_headline ` In my views.py, I have the following: `def details(request, article_identifier): article = get_object_or_404(MediaModule,article_identifier=article_identifier) meta_object__title = utils.meta_object__title(article.article_headline) meta_object__narrative = utils.meta_object__narrative(article.article_synopsis) meta_object__image = utils.meta_object__image(article.article_image) meta_object__url = utils.meta_object__url(request) context = { 'article' : article, 'meta_object__title' : meta_object__title, 'meta_object__narrative' : meta_object__narrative, 'meta_object__image' : meta_object__image, 'meta_object__url' : meta_object__url } return render(request, 'media-article.html', context)` in my media-article.html document, I have the following: `{% for x in article|slice:"0:5" %} <a href="/news/articles/{{x.article_identifier}}" title="{{x.article_headline}}" class="ContainerWithSideBarWrapper__ArticleItem"><p>{{x.article_headline}}</p></a> {% empty %} <p>No articles found.</p> {% endfor %}` Why is it that I am constantly surrounded by complete and utter stupidity? … -
Retrieve images from mysql database in django
I'm new to django and creating a listing site. I want to retrieve the users' image number 1 of 2 to display as thumbnails for a category page. I have since been able to retrieve the images for user's 'view listing' page, but not for my category page. I tried applying the url tags in the same way I did for the 'view listings' page, as below: <div class="flex-container"> {% if listing.image1 %} <img src="{{ listing.image1.url }}?" class="small-image" alt="Small image 1"> {% endif %} {% if listing.image2 %} <img src="{{ listing.image2.url }}?" class="small-image" alt="Small image 2"> {% endif %} </div> But this approach didn't work. So after some research, I used this in the 'category page' <h1>{{ category.title }}</h1> <p></p> <ul> {% for pedal in pedals %} <li> <h3>{{ pedal.pedal_name }}</h3> <a href="{% url 'pedal_detail' pedal_id=pedal.id %}"> <img src="{% if pedal.images.all|length > 0 %}{{ pedal.images.first.image.url }}{% else %}{% static 'path/to/default/image.jpg' %}{% endif %}" alt="Pedal Thumbnail" class="pedal-thumbnail"> </a> </li> <p></p> {% endfor %} </ul> But again, this hasn't worked. I'm unsure of the best way to do this. I've included other relevant code below to help advise. settings.py STATIC_URL = "/static/" STATICFILES_STORAGE = "cloudinary_storage.storage.StaticHashedCloudinaryStorage" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] # development STATIC_ROOT … -
Dynamic SSO integration in Django using SAML protocol
My company wants me to build an engine that will store SSO IDP's details like login url, client key, client secret and any other field required for SSO login. All the details should be stored in the database and the information should be collected from the client using the dashboard. I cannot configure the details in settings.py file. As in when a client company of ours wants to implement SSO, all the should do is login to the dashboard, go to a specific screen and enter the fields mentioned above and or any required fields that I would need to setup the SSO. Also I cannot configure the SSO details in settings.py as the credentials will be added by the client. So this has to be outside the scope of settings.py file. The SSO login url given by the client will be used for SSO redirection and the user should be authenticated from there. My issue is that my company does not want to configure the SSO for each individual client based on their need but rather use the engine so that the client company can set up SSO on their own without our interference. I have discussed potential cybersecurity … -
Django-Rest-FrameWork Post-Foreignkey
I am using DRF(Django-Rest-Framework) my Models.py class Followers(models.Model): id = models.AutoField(primary_key=True) followers_no = models.IntegerField() class Person(models.Model): followers = models.ForeignKey(Followers,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=120) age = models.IntegerField() def __str__(self) -> str: return self.name my serializers.py class Personserializer(ModelSerializer): followers = FollowerSerializer(read_only=True) class Meta: model = Person fields = "__all__" def validate(self,data): if data['age'] < 18: raise serializers.ValidationError('age should be more than 18') return data i want to add data about Person With Followers Field for that i create views.py def get(self, request): person_id = request.query_params.get('id') try: person = Person.objects.get(pk=person_id) except Exception as e: return Response({"status": False, "message": "Person not found"}, status=status.HTTP_404_NOT_FOUND) serializer = Personserializer(person) return Response({"status": True, "data": serializer.data}, status=status.HTTP_200_OK) def post(self, request): data = request.data serializer = Personserializer(data=data) if serializer.is_valid(): serializer.save() return Response({'status': True, "message": "Person created", "data": serializer.data}, status=status.HTTP_201_CREATED) return Response({"status": False, "message": "error", "error": serializer.error_messages}, status=status.HTTP_400_BAD_REQUEST) if i try to post data using postman as below { "followers": { "id": 1, "followers_no": 150 }, "name": "hello", "age": 19 } it shows as null value of followers instead if i pass the data it should post i Expect to store the data of followers field too -
Django delete record with ajax only disappears after manual refresh
I want to delete records from my table using Ajax and Sweetalert2 dialog. However, when I click the delete button and confirm the delete, the item is deleted from the modal but is still visible in the table. The element only disappears after a manual page refresh. I already reviewed many questions and videos but I think I'm missing some basic knowledge to identfy my issue.. html <tbody> {% if dogs %} {% for dog in dogs %} <tr> <td>{{ dog.dog_name }}</td> <td>{{ dog.gender }}</td> <td>{{ dog.breed }}</td> <td>{{ dog.size }}</td> <td>{{ dog.dob }} ({{dog.age}} Jahre)</td> <td>{{ dog.owner }}</td> <td>{{ dog.created_at }}</td> <td>{{ dog.updated_at }}</td> {% if dog.status == "ACTIVE"%} <td class="text-center"> <span class="badge text-bg-success" style="font-size:0.7em;">{{ dog.status }}</span> </td> {% elif service.status == "INACTIVE"%} <td class="text-center"> <span class="badge text-bg-danger" style="font-size:0.7em;">{{ dog.status }}</span> </td> {% endif %} {% if request.user.is_superuser == True %} <td class="text-center"> <!--Update--> <a href="{% url 'dog_record' dog.id %}" class="text-decoration-none"> <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service"> <i class="bi bi-pencil-fill"></i> </button> </a> <!-- Delete --> <button type="button" class="btn btn-danger btn-sm DeleteButton" data-url="{% url 'delete_record' dog.id %}"> <i class="bi bi-trash"></i> </button> </td> {% endif %} </tr> {% endfor %} {% endif %} </tbody> </table> {% endblock %} {% … -
Issue with Send mail by django.core.email import send_mail
I am trying to send a forget password email by send_mail in django. I am using gmail smtp with port 587. I have already made app password and 2 factor authentication. Problem is that I am recieving the email myself but if I send the email to someone who is not on my local network, the code doesn't throw any errors but they don't recieve any emails. I tried setting up an outbound rule in firewall settings but it is of no use. -
Django and sentry are not connected, Containers-to-containers connection
django, postgresql consists of docker-compose, and sentry consists each as a container while looking at the official document. Then, I created a new network (my_network) and connected django and sentry. However, issue tracking does not work. ps) It worked when django was turned locally instead of as a container. version: '3.8' volumes: postgres: driver: local redis: driver: local services: postgresql: image: postgres # build: ./.docker/postgresql volumes: - postgres:/var/lib/postgresql/data/ environment: POSTGRES_DB: aio_setting POSTGRES_USER: root POSTGRES_PASSWORD: aio0706! restart: unless-stopped ports: - '5432:5432' redis: # image: redis/redis-stack-server:latest image: "redis:alpine" restart: unless-stopped ports: - '6379:6379' volumes: - redis:/data app: build: . container_name: app command: /entrypoint.sh volumes: - .:/usr/src/app restart: unless-stopped ports: - "8000:8000" depends_on: - postgresql - redis import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="http://<secret>@my-sentry:8080/2", # dsn="http://<secret>@localhost:8080/2", # this worked when undockerizing integrations=[DjangoIntegration()] ) 🚀 docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES test_container cf5917ebf752 hubsettings-app "/entrypoint.sh" 2 hours ago Up 30 minutes 0.0.0.0:8000->8000/tcp app d096160bfd5d sentry "/entrypoint.sh run …" 2 hours ago Up 2 hours 0.0.0.0:8080->9000/tcp my-sentry 36aa3792c5b5 sentry "/entrypoint.sh run …" 2 hours ago Up 2 hours 9000/tcp sentry-worker-1 61906d23cab7 sentry "/entrypoint.sh run …" 2 hours ago Up 2 hours 9000/tcp sentry-cron 29d6b99e67c2 postgres "docker-entrypoint.s…" 3 hours ago Up … -
I can't access Django from Thonny or Python. Also sudo and apt-get don't work
I am trying to access Django. I installed using pip install django, but I can't access it in Thonny or Python. I tried using sudo, but I couldn't update it. I have version 1.0 of sudo, and apt-get doesn't work. I have tried many options to update sudo, but none of them have worked so far, but my biggest problem is being unable to access Django. -
Why won't Django load my CSS file with my HTML?
I am new to building django apps, and trying to add a simple CSS File to a simple HTML file for style points. I am not having any luck getting the CSS file to read into the HTML document on my web server. Can you please help me with this issue? my directory looks similar to this: web3/ ├── home1/ │ ├── static/ │ │ └── home1/ │ │ └── style.css where home1 is the app, and I have my template for HTML in the first home1 folder (ie. home1/template/home1/home.html) Here is what I have in my html document: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Kirby is the greatest</title> <!-- Link the CSS file --> {% load static %} <link rel="stylesheet" href="{% static 'home1/style.css'%}"> </head> <body> <h1>Great Job</h1> <h2>Proud</h2> </body> my views.py: `# home1/views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader def hello_world(request): return HttpResponse("you did it") def home(request): return render(request,"home1/home.html")' and the static portion of my settings.py: `# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "home1/static", ] # Define the directory where 'collectstatic' will place all static files for production STATIC_ROOT …