Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
all users are displayed as "Active" even though they are supposed to be inactive, [closed]
list.html <p>Active Status: {% if datas.employee.is_active %}Active{% else %}Inactive{% endif %}</p> models.py class Employee(models.Model): is_active = models.BooleanField(default=True) def delete(self): self.is_active = True self.save() ) -
Django Migration Error: admin.0001_initial is applied before its dependency users.0001_initial
I'm building a Django application with a custom user model, and I'm getting a migration error. I've already created my initial migrations but when trying to apply them, I get a dependency error. Error Message django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'. here is my My Settings Configuration (settings/base.py): AUTH_USER_MODEL = 'users.User' DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'rest_framework', 'django_filters', 'corsheaders', 'django_extensions', 'simple_history', 'phonenumber_field', ] LOCAL_APPS = [ 'apps.users.apps.UsersConfig', 'apps.courses.apps.CoursesConfig', 'apps.calendar_app.apps.CalendarAppConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS What I've tried: Running python manage.py makemigrations users Running python manage.py migrate Both commands result in the same error. How can I fix this without deleting my database? -
Sending an array from jQuery to a Django view
I am making a very small application to learn Django. I am send a nested array from jQuery and trying to loop it in my Django view. The jQuery code is as follows: $(document).on('click','#exModel',function () { const sending = []; $("table tr").each(function () { var p1 = $(this).find("th label").html(); var p2 = $(this).find("td input").attr('id'); var p3 = $(this).find("td input").val(); const build = []; build.push(p1, p2, p3); sending.push(build); console.log(sending); }); $.ajax({ url: '../coreqc/exModel/', data: {'sending': sending}, type: 'post', headers: {'X-CSRFToken': '{{ csrf_token }}'}, async: 'true', success: function (data) { console.log("I made it back") //dom: 'Bfrtip', } }); }); The above works and takes the following form in the console: Note that the 3rd value is intentionally empty as I sent the form with no values in the fields to get the console read out. [Log] [["Product A", "1", ""], ["Product B", "2", ""], ["Product C", "3", ""], ["Product D", "4", ""], ["Product E:", "5", ""], ["Product F", "6", ""], ["Product G", "7", ""], ["Product H", "8", ""], ["Product I", "9", ""], ["Product K", "10", ""], …] (36) (coreqc, line 491) [Log] I made it back # This is the success text in the above jQuery code It is making it to … -
detected dubious ownership in repository
I have a django project called my_project containing a database. In order to run the website with apache, I had to modify the access rights and ownership with sudo chown www-data:www-data my_project/ sudo chmod 755 my_project/ At least this is how I got it to work. But now, when I run git pull I get the following error message: fatal: detected dubious ownership in repository Can I just suppress this error message or is this a security issue? Please let me know if I have to configure something differently. -
The image is not being stored in the media folder in Django, but the database contains the image name
views.py employee = Employee.objects.create( user=request.user, # Assigning the current user first_name=request.POST.get('employee_firstname'), middle_name=request.POST.get('employee_middlename'), last_name=request.POST.get('employee_lastname'), email=request.POST.get('employee_email'), land_phone_number=request.POST.get('employee_landphone'), mobile_phone_number=request.POST.get('employee_mobile'), gender=request.POST.get('gender'), hire_date=request.POST.get('hire_date'), position=position, address=address, date_of_birth=request.POST.get('dob'), img=request.FILES.get('imgg'), # Make sure you're using request.FILES for image files ) models.py class Employee(models.Model): img = models.ImageField(upload_to='pics') settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') `# Define Media URL `MEDIA_URL = '/media/' urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) add_user.html <div class="contact-img"> <input type="file" id="imgg" name="imgg" class="form-control" accept="image/*"> list.html <img src="{{ datas.employee.img.url }}" alt="User Avatar" class="user-avatar"> "Why is this not being stored in the media/pics folder?" -
Azure App Service (oryx) does not use the set startup command
I want to deploy a Django DRF application to a azure App Service using artifacts (zip deployment) the artifact gets sucessfully uploaded from azure devops but the execution of the container fails since not all required packages are installed. Since my python packages are managed with pipenv I use a custom startup.sh script to start my App Service the file looks like this: python -m pip install --upgrade pip pip install pipenv pipenv install pipenv run python manage.py migrate pipenv run gunicorn --workers 2 --threads 4 --timeout 60 --access-logfile \ '-' --error-logfile '-' --bind=0.0.0.0:8000 \ --chdir=/home/site/wwwroot kez_backend.wsgi and I set it in my CD pipeline like this: but when I look at the logs of my App service the startup.sh script is not used and a custom one is create by oryx. Since oryx also creates a virtualenviroment and can't handle Pipfiles dependencys are missing. Application Logs: 2024-10-23T22:34:29.046573859Z _____ 2024-10-23T22:34:29.046642461Z / _ \ __________ _________ ____ 2024-10-23T22:34:29.046646861Z / /_\ \\___ / | \_ __ \_/ __ \ 2024-10-23T22:34:29.046650061Z / | \/ /| | /| | \/\ ___/ 2024-10-23T22:34:29.046653661Z \____|__ /_____ \____/ |__| \___ > 2024-10-23T22:34:29.046656961Z \/ \/ \/ 2024-10-23T22:34:29.046659861Z A P P S E R V I C E O … -
Why when I login in django, it throws error that username or password doesn't exists
I have this in terminal 'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'} [ but, I have saved my username and password via browser, setting very common username and password that is impossible to write wrong may problem lay in form that is used during registration, or it happens because of registration form, or it happens because of models? My models from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) bio = models.CharField(max_length=255, blank=True) image = models.ImageField(blank=True) Forms: from django import forms from django.contrib.auth.models import User from users.models import Profile from django.contrib.auth.forms import AuthenticationForm, UserCreationForm class ProfileRegistrationForm(UserCreationForm): username = forms.CharField(required=True, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Enter username'})) email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': 'Enter email'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Enter password'}), label="Password") password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm password'}), label="Password") class Meta: model = User fields = ['first_name', 'last_name','username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() profile = Profile(user = user, first_name = self.cleaned_data['first_name'], last_name = self.cleaned_data['last_name']) if commit: profile.save() return profile def clean_username(self): username = self.cleaned_data['username'].lower() new = User.objects.filter(username=username) if new.count(): raise forms.ValidationError("User already … -
Optimal Approach for Training an AI Model to Correct Errors in Multipolygon Coordinates (Django REST Framework GIS)
I need to select an AI model and a Python library that would be the most optimal for training. I have coordinates represented as a Multipolygon field from the djangorestframework-gis library, and they have small errors within different ranges—approximately 0.75 to 1 meter. Additionally, I have correct coordinates for the same land plots. The model needs to learn to find the difference between the correct and incorrect data and, based on that, discover an algorithm to determine the error for future correction of the incorrect coordinates. -
Next.js Project Works in One Branch, API Requests Fail in Another
I'm working on a project using Next.js where I have two separate branches. The code works perfectly in one branch, but I'm encountering issues with API requests in the other branch. The code in both branches is almost identical, but in the non-working branch, the data I send is being accepted as empty on the backend, and I'm getting an error. Here’s the code I’m using: The data I’m sending to the API: sending data {title: 'test4', company: 'test', city: 'test2', country: 'tst', description: 'asdasda', ...} The error I receive: error: 'null value in column "title" of relation "core_exp..."' I'm only able to log into my project with part of the code, but I'm encountering issues when trying to update the form fields. Things I've tried to resolve the issue: Checked the .env files; they have the same values. Ensured that the library versions are the same. Verified that the API endpoints are correct. Checked that the Redux state is being updated properly. I compared most of my code and did not find any significant differences. Even on some pages, I observe that although I receive a 200 response from the backend, the changes I made are not being updated. … -
upload file in background process in django drf (get this error : Object of type TemporaryUploadedFile is not JSON serializable)
this is my create function: def create(self,request,*args,**kwargs): serializer = ArchiveSerializer( data = request.data, context = {"request":request} ) serializer.is_valid(raise_exception=True) filename=serializer.validated_data.pop('file') serializer.save() id = serializer.validated_data.get("id") save_file_in_background.delay(id,filename) return Response(serializer.data, status=status.HTTP_201_CREATED) and this is the tasks.py from celery import shared_task from django.core.files.base import ContentFile from .models import Archive @shared_task def save_file_in_background(id,filename): try: archive = Archive.objects.get(pk=id) if filename: archive.file.save(filename, ContentFile(filename)) archive.save() except Archive.DoesNotExist: pass but when try to add object and upload the file get this error: Object of type TemporaryUploadedFile is not JSON serializable except to upload file in background but get this error: "Object of type TemporaryUploadedFile is not JSON serializable" -
Django session doesn't work in Chrome Incognito mode
I have 3 views like this: def download_file(request, doc): if not request.session.get('is_authenticated'): return redirect(f"{reverse('pingfed_auth')}?next={request.get_full_path()}") return downloadfile(doc) def pingfed_auth(request): original_url = request.GET.get('next') or 'home' request.session['original_url'] = original_url return redirect('Some third party authentication') def redirect_pingfed_auth(request): if request.method == 'POST': request.session['is_authenticated'] = True request.session['username'] = get_username_from_saml(request.POST.get('SAMLResponse')) return redirect(request.session['original_url'] if 'original_url' in request.session else 'home') Where pingfed_auth start the authentication and redirect_pingfed_auth is the callback URL from that thrid-party authentication. However, the session doesn't work in chrome Incognito mode. I can't see any session from browser console, and I can't get redirect correctly. But I do see the session is stored properly in the database. Is that because Incognito mode block the session after redirect to third party site or something else? -
Django DB Foreign Key on_delete=CASCADE combined with null=True
What happens if a Django model contains both - on_delete=CASCADE and null=True: class MyModel(models.Model): ID = models.AutoField(primary_key=True) SomeInfo = models.BooleanField(default=False) SomeInfo2 = models.BooleanField(default=False) ID_FK1 = models.ForeignKey(OtherModel1, on_delete=models.CASCADE, null=True) ID_FK2 = models.ForeignKey(OtherModel1, on_delete=models.CASCADE, null=True) I see entries in the DB of MyModel with ID_FK2 being NULL which is not supposed to happen. -
Django-Nginx-React: How to fix ERR_CERT_COMMON_NAME_INVALID and Self-Signed Certificate Issues
I am working on a project using SimpleJWT tokens stored in HttpOnly cookies for authentication. The architecture involves a Django backend, an Nginx server, and a React+Vite frontend. Below is the configuration setup: I have created a self-signed Certificate Authority (CA). I issued two separate certificates signed by the same CA: one for the Nginx server (serving the Django backend) and one for the React+Vite app When I run my React+Vite app on Google Chrome and try to call the login API /api/auth/login/ of the Djagno backend, I receive the following error: POST https://172.x.x.x/api/auth/login/ net::ERR_CERT_COMMON_NAME_INVALID Additionally, I set up a Node.js project to test the same API by making Axios requests. In this case, I get the Error: self-signed certificate in certificate chain However, if I run the Node.js project with NODE_TLS_REJECT_UNAUTHORIZED='0', the API works fine, and I can see the HttpOnly cookies and the correct response from Django. It seems to be related to the self-signed certificates, but I’m unsure how to resolve this for Chrome to correctly accept the certificates and allow setting cookies. I’m also looking for a solution that doesn't involve disabling certificate validation with NODE_TLS_REJECT_UNAUTHORIZED=0. Questions: How can I resolve the ERR_CERT_COMMON_NAME_INVALID in Chrome? How … -
Django channels authentication with http post and use websockes after
I am working on a project where we have been using crud with a rest api, standard stuff. Now we want to switch to websockets as we want to have realtime updates. Think airline reservation calender. When someone clicks on a box in calender it needs to be blocked on every connected user. I see a lot of examples of people giving examples of authentication over the websocket. But I find creation of web-socket before login to a system wasted full. So ideally I would like to authenticate the user via JWT over an HTTP POST and get a token and if use it authenticated then create a websocket with the token that i get from JWT. Before I get into details. Is this the write way to do or should one create a websocket connetion right away and do the whole api stuff over websocket including the initial auth(username ,password stuff) . Thanks -
i got TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'
I want to create super user just from email and password so it should create super user without username. I am using custom user model and when i try to create superuser i got this error TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' This is my manager.py file from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') return self._create_user(email, password, **extra_fields) This is my models.py class User(AbstractUser) """ Abstract User of django auth user model. """ uuid = models.UUIDField(default=uuid.uuid4, unique=True, null=False) email = models.EmailField(_("email address"), unique=True) middle_name = models.CharField(max_length=120, blank=True) image = models.ImageField(upload_to='user_profile/', blank=True) department = models.CharField(blank=True, choices=Department.choices, max_length=2) designation = models.CharField(max_length=120, blank=True) last_logout = models.DateTimeField(null=True) is_superuser = models.BooleanField(default=False) view = models.TextField(blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Django Cloned Project does not give tables after migrating
I cloned a project that I want to modify and experiment with, and I have all the necessary credentials. However, I'm encountering issues while following the steps outlined in the ReadMe.md file since I cloned it: Clone the project. Create a .env file and add the following information: Database variables: DATABASE_NAME: Database name DATABASE_USER: Database user DATABASE_PASSWORD: Database password DATABASE_HOST: Database host DATABASE_PORT: Database port Authentication variables for the Telnyx API: Telnyx_v2_key: Telnyx API v2 key x-api-token: Telnyx API v1 token x-api-user: Telnyx API v2 user email Create a virtual environment: python -m venv ./venv Activate the environment: source venv_telnyx-invoicing/bin/activate.csh Install requirements: pip install -r requirements.txt Create a logs directory: mkdir logs Make migrations: python manage.py makemigrations Migrate: python manage.py migrate I’m currently stuck at the migration step. When I try to run python manage.py makemigrations, I receive the following error: Traceback (most recent call last): File "C:\Users\DominykasPavlijus\Desktop\Telnyx-Invoicing-1\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UndefinedTable: relation "Project_tenant" does not exist LINE 1: ...nant"."id", "Project_tenant"."billing_group" FROM "Project_t... My settings.py file appears to be configured correctly: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DATABASE_NAME'), 'USER': os.getenv('DATABASE_USER'), 'PASSWORD': os.getenv('DATABASE_PASSWORD'), 'HOST': os.getenv('DATABASE_HOST'), 'PORT': os.getenv('DATABASE_PORT'), } } This is the model that … -
Mock patching a callable upload_to in a Django ImageField
In Django I have a model and a test similar to the following, both in a photos module (Django app). models.py def get_user_photo_path(instance, filename): return str(uuid.uuid4()) class UserPhoto(models.Model): uploader = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_user_photo_path) upload_timestamp = models.DateTimeField(auto_now_add=True) tests.py @mock.patch('photos.models.get_user_photo_path') def test_image_upload_path(self, mock_photo_path): mock_photo_path.return_value = 'mocktest' user_photo = UserPhoto.objects.create( uploader=self.parking_user, # these self variables are defined in setUp() image=self.image ) expected_path = 'mocktest' self.assertTrue(user_photo.image.name.endswith(expected_path)) # Assertion fails # For demonstration, this assertion DOES pass from .models import get_user_photo_path self.assertEquals(get_user_photo_path(), 'mocktest') This does not work, and I'm not sure why. But if I import the get_user_photo_path function directly in the test and call it, it does return 'mocktest'. I can only guess it has something to do with the way the ImageField processes its arguments, but from the source code nothing stands out to me as particularly strange or unusual. I got around it by patching photos.models.uuid.uuid4 instead, but if someone could explain why the above patch didn't work, I would be very grateful! -
Django SSO integration for JumpCloud
Newbie question. I am trying to configure my company admin website to use JumpCloud for SSO auth. I can't find any simple solution. Is there a conventional/standard practice way to integrate OIDC into a simple Django website? Secondly, if my web application runs in a private network (ie No public access), does the IDP have to have access to my web application to return the auth code (back channel)? -
Failed lookup for key [site_header] when extending admin/change_list.html
i tried to extend change_list.html template from using this two guide https://hakibenita.com/how-to-turn-django-admin-into-a-lightweight-dashboard & https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template this is my view @admin.register(summery) class StaisticsSummery(ModelAdmin): change_list_template ="admin/stat_summary_change_list.html" def changelist_view(self, request,extra_context=None): extra_context = extra_context or {} filterUser = request.GET.get("q","") filterStart = request.GET.get("startDate","") filterEnd = request.GET.get("endDate","") if filterStart=="": filterStart = "1300-01-01" if filterEnd=="": filterEnd = "1500-12-29" result = list(User.objects.values("username").annotate( total_Balance=Sum('statistics__balance',default=0,filter=Q(statistics__created_at__gte=filterStart)|Q(statistics__created_at__lte=filterEnd)), ...) ).order_by("username")) if(filterUser!="" and filterUser is not None): result =result.filter(username=filterUser) extra_context["result"]=result return super().changelist_view(request,extra_context) i request when there was'nt any start and end to querystring everything looks works fine and all result are valid i use the given query in django shell an everything were valid but somehow opt context variable is changing when trying to query with dates via the browser is there any better way to debug this problem related to context object -
render_to_string function not displaying context variables
I am trying to implement the render_to_string function in a Django project. I have an HTML template (strategy.html) containing many Django Template Language variables and 'if conditions' and would like to save the rendered output in a DB model. The output is saved in the db model but the context variables are ignored. The action has to be triggered once the 'Save' button is clicked (see code below). Important note: the DTL variables and 'if conditions' are correctly displayed when using the render function by clicking the 'Generate' button. Here is the views.py file: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.template.loader import render_to_string from strategiesAPI.models import strategiesList @login_required def index(request): if request.method == "POST": # Get form information starttime = request.POST.get("starttime") endtime = request.POST.get("endtime") trigger = request.POST.get("trigger") entrieslimit = request.POST.get("entrieslimit") direction = request.POST.get("direction") pattern = request.POST.get("pattern") stoploss = request.POST.get("stoploss") takeprofit = request.POST.get("takeprofit") tradeliquid = request.POST.get("tradeliquid") # Context variables for the render and render_to_string function content = { "starttime": starttime, "endtime": endtime, "trigger": trigger, "entrieslimit": entrieslimit, "direction": direction, "pattern": pattern, "stoploss": stoploss, "takeprofit": takeprofit, "tradeliquid": tradeliquid } # Action based on the button pressed inside the index.html template # GENERATE button if request.POST['button'] == 'Generate': # Write … -
Apache WSGI module Fails to Start with net start apache2.4, but Works with httpd.exe
I’m currently facing an issue with my Apache server setup on Windows. I’ve been able to run Apache successfully using httpd.exe, but when I attempt to start it using net start apache2.4, the service fails to start, and I receive an error in the Event Viewer (no corresponding Apache error log though) System Details Apache Version: Apache 2.4 (64-bit) Python Version: Python 3.13 mod_wsgi Version: 5.0.1 (64-bit) Django App Path: C:/webapp WSGI Module Path: C:/Users/{me}/AppData/Local/Programs/Python/Python313/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp313-win_amd64.pyd What I’ve Tried 1. Running httpd.exe Directly: Apache starts successfully and serves my Django application as expected. No issues with the Django app or the WSGI module when starting manually. **2. Running httpd -t ** Returns Syntax OK. 3. Windows Event Viewer Error: When starting Apache with net start apache2.4, I see the following error in the Event Viewer: The Apache service named reported the following error: >>> httpd.exe: Syntax error on line 194 of C:/Apache24/conf/httpd.conf: Cannot load C:/Users/{me}/AppData/Local/Programs/Python/Python313/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp313-win_amd64.pyd into server: The specified module could not be found. . 4. Verified File Paths: I have confirmed that the mod_wsgi file exists in the exact location specified in the httpd.conf file: c:\Apache24\bin>dir "C:\Users\{me}\AppData\Local\Programs\Python\Python313\Lib\site-packages\mod_wsgi\server" Volume in drive C is Windows Volume Serial Number is 8205-BA06 Directory of … -
ODBC Driver Error: File Not Found When Running Python Script in Docker Container
I'm running a Python script (sharepoint_to_json.py) inside a Docker container that connects to a SQL Server database using the ODBC driver. My goal is to convert data from an Excel (.xlsx) file into JSON format within my server, using the sharepoint_to_json.py script. This process should run inside the Docker container after establishing a connection to a SQL Server database. I have already installed the msodbcsql17 driver in the container, and my connection to the database works when running other scripts. However, when I try to run the sharepoint_to_json.py script, I encounter the following error: Ocorreu um erro ao processar o arquivo Excel: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1' : file not found (0) (SQLDriverConnect)") Here's the relevant part of my Dockerfile: FROM python:3.12 RUN apt-get update && apt-get install -y curl gnupg2 apt-transport-https unixodbc unixodbc-dev python3-distutils build-essential && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list && apt-get update && ACCEPT_EULA=Y apt-get install -y msodbcsql17 Set the working directory in the container WORKDIR /app Upgrade pip, setuptools, wheel to ensure the latest versions RUN pip install --upgrade pip setuptools wheel Copy the requirements.txt file COPY requirements.txt . Install the dependencies RUN pip install -r requirements.txt Copy … -
How to set environment variables in a Google Cloud VM (Ubuntu) for Django project without exposing sensitive information?
I am using a virtual machine on Google Cloud with Ubuntu as the operating system, and I have deployed a Django backend on it. In my settings.py, I use environment variables like this: EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') I would like to know how to properly set environment variables on the VM so that my Django application can access them. Specifically: How do I create environment variables on the VM (Ubuntu)? How can I ensure that sensitive data (like EMAIL_HOST_PASSWORD) is not exposed in plain text, but still accessible by my Django app? Any best practices for securely managing these environment variables in a Google Cloud VM would be appreciated. Thanks! -
Trying to test multiple test files with multiple test classes but PyTest doesn't recognize other files
I've been scouring all over the internet in order to find solution for this problem. I've been trying to make sure that PyTest recognizes multiple test files to account for the multiple test files and the classes inside them in order to build a full test suite. Here's the config file: [pytest] asyncio_mode=auto asyncio_default_fixture_loop_scope="class" DJANGO_SETTINGS_MODULE = personal_blog.settings testpaths = tests Here's the test class that it recognizes: test_members.py import pytest import factory from django.contrib.auth import get_user_model from factories import MemberFactory from faker import Faker from django.urls import reverse from django.contrib.auth.models import Permission fake = Faker() # Create your tests here. User = get_user_model() # Basic Tests class TestMembers: #Confirms that a user has been created @pytest.mark.django_db def test_if_user_exists(db): user = MemberFactory() assert user.username is not None assert user.email is not None # Checks if the password fails @pytest.mark.django_db def test_set_check_password_fail(db): # basic_user.set_password("password") user = MemberFactory() assert user.password != 'Wrong' # Checks if the password fails @pytest.mark.django_db def test_set_check_password_success(db): user = MemberFactory() assert user.password == 'password' # Checks if the user is not a contributor by default. @pytest.mark.django_db def test_is_not_contributor_by_default(db): user = MemberFactory() assert user.is_contributor is False # Checks if the User is a contributor @pytest.mark.django_db def test_is_contributor(db): user = MemberFactory(is_contributor … -
Django Static Image Not Displaying When Using Variable for Image Path
I'm trying to load and display a static image in a Django template. I have a dictionary named post that contains an image value, for example, "mountain.jpg". I checked, and the dictionary has the correct data. However, when I try to set the image path dynamically using post.image, the image is not displayed. If I hardcode the URL, the image shows up correctly. Here is my image tag in the template // not working <img src="{% static "blog/images/"|add:post.image %}" alt="Mountain" /> // working <img src="{% static "blog/images/mountain.jpg" %}" alt="Mountain" />