Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTPServerDisconnected at /users/password_reset/ Connection unexpectedly closed, why am I getting this error in 2022?
I am trying to send emails using sendgrids SMTP relay. I created a apikey, added this into my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'jajamensanson@gmail.com' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'mysendgridpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True When I try to send the email, I get this error: SMTPServerDisconnected at /users/password_reset/ Connection unexpectedly closed Anyone have an answer to this? Also, just for your info, I am using the django for beginners book. -
How to run Celery container without starting multiple Django servers
My docker-compose setup has several services. The ones I am concerned about are: celery, celery_beat, and backend (django). Every tutorial I have found online has the celery container using the same image as backend. The problem is that it is forcing 3 django containers to fire up (which can't be the optimal way of deploying my app). I currently use an ENTRYPOINT bash script at the end of my Dockerfile which waits for the database to be ready, then it handles migrations, then runs the development server: Dockerfile FROM python:3.9.5-alpine WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update RUN apk add gcc musl-dev python3-dev libffi-dev openssl-dev postgresql-dev COPY ./requirements.txt /requirements.txt RUN pip install --upgrade pip RUN pip install -r /requirements.txt COPY ./entrypoint.dev.sh /entrypoint.dev.sh COPY . /backend/ ENTRYPOINT [ "/entrypoint.dev.sh" ] entrypoint.dev.sh #!/bin/sh if [ "$POSTGRES_DB" = "digibrain_db" ] then echo "-------------- Waiting for postgres... -------------------" while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do sleep 0.1 done echo "-------------- Postgres database started! ----------------" fi python3 manage.py makemigrations python3 manage.py migrate python3 manage.py collectstatic --no-input --clear python3 manage.py runserver 0.0.0.0:8000 exec "$@" Since the ENTRYPOINT file/command is causing all 3 containers to run django I tried to change it to … -
How to get file ID from box.com by passing the file name in python
How to obtain file_id from "file name" in Box.com API Not sure which call will I make from this https://developer.box.com/reference/#searching-for-content. I want to pass filename and get file id of that filename. I am using python SDK -
Django/Heroku first deployment results in H10 error
When I try to access my app after deployment it results in an H10 error. It seems to reference favicon in the log and also says that Django isn't installed (I have run pip3 list in my venv and it appears to be there, it is also in requirements.txt). Here is the log: 2022-01-14T04:51:29.245939+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0.0.0:42836` 2022-01-14T04:51:30.238629+00:00 app[web.1]: Traceback (most recent call last): 2022-01-14T04:51:30.238658+00:00 app[web.1]: File "manage.py", line 11, in main 2022-01-14T04:51:30.238659+00:00 app[web.1]: from django.core.management import execute_from_command_line 2022-01-14T04:51:30.238659+00:00 app[web.1]: ModuleNotFoundError: No module named 'django' 2022-01-14T04:51:30.238660+00:00 app[web.1]: 2022-01-14T04:51:30.238660+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2022-01-14T04:51:30.238660+00:00 app[web.1]: 2022-01-14T04:51:30.238660+00:00 app[web.1]: Traceback (most recent call last): 2022-01-14T04:51:30.238661+00:00 app[web.1]: File "manage.py", line 22, in <module> 2022-01-14T04:51:30.238661+00:00 app[web.1]: main() 2022-01-14T04:51:30.238661+00:00 app[web.1]: File "manage.py", line 13, in main 2022-01-14T04:51:30.238662+00:00 app[web.1]: raise ImportError( 2022-01-14T04:51:30.238672+00:00 app[web.1]: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2022-01-14T04:51:30.414522+00:00 heroku[web.1]: Process exited with status 1 2022-01-14T04:51:30.500903+00:00 heroku[web.1]: State changed from starting to crashed 2022-01-14T04:51:33.725668+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=vygrapp.herokuapp.com request_id=357ddcbf-e6fe-4c68-ba23-24777b56d20d fwd="61.68.159.52" dyno= connect= service= status=503 bytes= protocol=https 2022-01-14T04:51:34.113095+00:00 heroku[router]: at=error code=H10 … -
Django redirection errors
I currently have an issue using my button as I need to open a modal which is successful but when clicking from other pages it needs to redirect back to the page it was clicked on. <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfile">+</button> I have tried return redirect(request.META.get('HTTP_REFERER')) which does stay on url but I need to use context['is_post'] in case it fails to reopen up the modal which should be passed. So currently if I used mine it'll reopen on false data but won't hold the page url. context['nmenu'] is what is used to make sure the a tag is currently active. views.py: def index(request): context={} context['is_post']= False editProfileForm = UserProfileForm() if request.method == "POST": if 'editProfileForm' in request.POST: editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm() context['editProfileForm'] = editProfileForm return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) else: # Checks if user is logged out or in and passes to form if request.user.is_authenticated: Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by("-time", "read") context['Inbox'] = Inbox unreadMessagesCount = Messages.objects.filter(Q(receiver=request.user) & Q(read=False)).count() context['unreadMessagesCount']=unreadMessagesCount editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['nmenu']='home' return render(request, "home.html", context) html: {% block content %} <div class="col-md-3" … -
Why do I need to call (Django's)object before I link it to another object in Windows powershell?
I intuitively feel that, but I don't understand it step by step. Example: In Windows Powershell I open my main folder with manage.py and open the shell with: python manage.py shell. Then I need to write something like: Product.objects.get(id=1), so later I can link this to an object: obj = Product.objects.get(id=1). My question is, why does the shell need to have it in this fashion. Why I can't to type just obj = Product.objects.get(id=1)? Without this part before: Product.objects.get(id=1). I wonder about it, because the second part of this code points out to class and method. -
How to test a URL in Django?
I wrote this detail view: def blog_detail(request, pk): blog = get_object_or_404(Blog, pk=pk) comment = blog.comment_set.all() paginator = Paginator(comment, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'blog': blog, 'page_obj': page_obj, } return render(request, 'blog/blog_detail.html', context=context) Here's the url: urlpatterns = [ path('blog/<int:pk>/', views.blog_detail, name='blog-detail') ] Here my test for the view: class BlogDetailViewTest(TestCase): def setUp(self): user = User.objects.create(username='user01', password='123456') author = Author.objects.create( user=user, date_of_birth='1998-09-08', bio='I am user01') topic = Topic.objects.create(name='Testing') blog = Blog.objects.create(title='My blog', content="It's my blog") blog.author.add(author) blog.topic.add(topic) for c in range(3): Comment.objects.create(blog=blog, user=user, comment='I am testing') self.blog_instance = Blog.objects.get(id=1) def test_url(self): response = self.client.get(f'/blog/blog/{self.blog_instance.pk}') self.assertEqual(response.status_code, 200) def test_url_name(self): response = self.client.get(reverse('blog-detail', kwargs={'pk': self.blog_instance.pk})) self.assertEqual(response.status_code, 200) The test_url function are returning this assertion error: AssertionError: 301 != 200 Why the test_url function are returning the status code 301 if the test_url_name function are returing the status code 200? Both are the same url, I don't understand. -
Django/Django Channels - weird looking json return with double \ between each field
Hello I'm trying to do a real time friend request notification system and having this weird looking json return. I'm new to backend development and django (1st year software engineering student). Im just wondering if this is normal since i havent seen anything like this and if theres a way to fix it. Ive worked on a chat app before but it was just all text messages and so I got confused when it comes to django models. I have tried multiple ways I found but only this works. I think it might be because I called json.dumps twice but if i remove either of them, it wont work. Thank you When a user sends a friend request, this is what i got back from the web socket(with double \ for each field) Heres the code //views.py class SendRequestView(views.APIView): permission_class = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): receiver_username = self.kwargs['receiver_username'] if receiver_username is not None: receiver = get_object_or_404(User, username=receiver_username) request = ConnectRequest.objects.create(sender=self.request.user, receiver=receiver) notification = ConnectNotification.objects.create(type='connect request', receiver=receiver, initiated_by=self.request.user) channel_layer = get_channel_layer() channel = f'notifications_{receiver.username}' async_to_sync(channel_layer.group_send)( channel, { 'type': 'notify', 'notification': json.dumps(ConnectNotificationSerializer(notification).data, cls=DjangoJSONEncoder), } ) data = { 'status': True, 'message': 'Success', } return JsonResponse(data) // consumer.py class ConnectNotificationConsumer(AsyncJsonWebsocketConsumer): async … -
AttributeError at /register Manager isn't available; 'auth.User' has been swapped for 'account.Account'
I have been working on debugging this code for last 2 days but not able to find out the mistake. I have seen the tried the user = get_user_model() but it is not working. Also i have added in settings AUTH_USER_MODEL = 'account.Account' and account is a registered app in settings. models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.conf import settings # account manager class MyAccountManager(BaseUserManager): def create_user(self, email, username, profile, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, profile_image=profile ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # models here. def uploadImageHandler(instance,filename): fpath = pathlib.Path(filename) newFileName = str(uuid.uuid1()) return f"images/profile/{newFileName}{fpath.suffix}" class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, upload_to=uploadImageHandler, null=True, blank=True) hide_email = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() … -
Loop through list of JSON objects using Django HTML tags/template
Context I want to allow the users to aggregate a DF and create multiple tables by passing through a list of JSON objects. Sample Data Person_ID hair_color eye_color gender 111 Brown Brown M 222 Blonde Brown M 333 Brown Green F 444 Brown Blue M Current Code views.py 'function code to read in excel and create DF goes here' 'pull in the sample data and create a dataframe based on count of hair / eye color' df_list = [] for trait in person_list: <-- ['hair_color', 'eye_color'] var_df = df.groupby([trait]).size().reset_index(name='counts') data = var_df.to_json(orient='records') data = json.loads(data) df_list.append(var_df) context = {'d': df_list} return render(request, 'URL_test', context) DF_LIST looks like: [ [{'hair_color': 'Brown', 'gender': M, 'counts': 2}, {'hair_color': 'Blonde', 'gender': 'M', 'counts': 1}, {'hair_color': 'Brown', 'gender': 'F', 'counts': 1}], [{'eye_color': 'Brown', 'gender': 'M', 'counts': 2}, {'eye_color': 'Green', 'gender': 'F', 'counts': 1}, {'eye_color': 'Blue', 'gender': 'M', 'counts': 1}] ] HTML Template Code: <body> <center> {% if d %} {% for i in d %} <----- for each JSON object in DF_LIST <div class="container"> <table class="altrowstable" id="alternatecolor"> <thead> <tr> <th align=left>VAR NAME GOES HERE</th> <--- dynamic based on i <th align=left>GENDER GOES HERE</th> <th align=right>COUNT</th> </tr> </thead> <tbody> <tr> <td align=left>{{i.variable}}</td> <td align=right>{{i.gender}}</td> <td align=right>{{i.counts}}</td> … -
how to create view for django root module
I have a django project with nested smaller apps call: blog, research, report. I would like to create a view at the root folder (django project level) so that it displays all the blog, research and report posts. what can i do? usually i wire the django project urls so that the request '' go to the blog home view. Now i dont want it to be wired that way anymore. I would like that the '' go to a page (i think at django project root level) that can render all blog, research and report articles. -
Python 3.8 Django2.2 some bootstrap decode
Exception happened during processing of request from ('127.0.0.1', 2103) Unhandled exception in thread started by <bound method Thread._bootstrap of <Thread(Thread-5, started daemon 2540)>> and another exception occurred: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 182: invalid start byte I'm Chinese Developer, so I use GBK to decode file before enter image description here -
Django add a model field based on another field
I'm very new to Django and know there has to be an easy way to do this that makes sense: I have a form where I would like the user to enter the URL for a YouTube video (https://www.youtube.com/watch?v=XXXXXXXXXXX). I would like to take input and convert it to the format to embed a YouTube video (https://www.youtube.com/embed/XXXXXXXXXXX). My models.py field uses a URL field. I don't have a forms.py file (I'm willing to add one if needed) and instead I'm calling the models.py fields individually on my html page. I'm happy to take any advice on if you would add a forms.py file. I imagine the cleanest way to move from one url format to the other on user entry is to slice the original user input and concatenate but I don't know where or with what format in djagno. -
How do I make Django insert an ID value into a field that I specify (models pulled from existing DB)?
Context: I have a pre-existing database that I should not alter. What I have done was use manage.py inspectdb and pulled the models I needed into webapi/models.py. I have the following model: class Clerk(models.Model): clientid = models.BigAutoField(db_column='clientId', primary_key=True) clerkname = models.CharField(db_column='clerkName', max_length=30) ... class Meta: managed = False db_table = 'Clerks' I am not sure if I need to show anymore code for the purposes of this test, but I feel like I should be able to simply make an instance and see that an id has been assigned. However, as per below, id is not being assigned. I have also included some troubleshooting I've done >>> from chokowebapi.models import Clerk >>> Clerk.objects.all() <QuerySet []> >>> clerk = Clerk(clerkname="hi") >>> clerk.clientid Additional troubleshooting (continuation of the above snippet) >>> clerk.save() Traceback (most recent call last): File "C:\git\django-mssql\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\git\django-mssql\venv\lib\site-packages\mssql\base.py", line 576, in execute return self.cursor.execute(sql, params) pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert the value NULL into column 'clientId', table 'web.dbo.Clerks'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") The above exception was the direct … -
Django Channels notifications not working
I'm trying to do a real time friend request notification system for a project i'm working on. Thought this was going to be easy because I have used channels for a chat application before and because I think theres no need to listen for signals from the other side of the web socket. Presumably its not the case. Would be much appreciated if you could help. I used JwtAuthMiddleware from django_channels_jwt_auth_middleware, it works for my chat app. I can connect to the websocket but doesn't get notified when a user sends a friend request. Everything else works fine. Thank you Heres the code // views.py class SendRequestView(views.APIView): permission_class = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): receiver_username = self.kwargs['receiver_username'] if receiver_username is not None: receiver = get_object_or_404(User, username=receiver_username) request = ConnectRequest.objects.create(sender=self.request.user, receiver=receiver) notification = ConnectNotification.objects.create(type='connect request', receiver=receiver, initiated_by=self.request.user) channel_layer = get_channel_layer() channel = f'notifications_{receiver.username}' async_to_sync(channel_layer.group_send)( channel, { 'type': 'notify', 'notification': json.dumps(ConnectNotificationSerializer(notification).data, cls=DjangoJSONEncoder), } ) data = { 'status': True, 'message': 'Success', } return JsonResponse(data) // consumer.py class ConnectNotificationConsumer(AsyncJsonWebsocketConsumer): async def connect(self): user = self.scope['user'] group_layer = f'notifications_{user.username}' await self.accept() await self.channel_layer.group_add(group_layer, self.channel_name) async def disconnect(self, close_code): user = self.scope['user'] group_layer = f'notifications_{user.username}' await self.channel_layer.group_discard(group_layer, self.channel_name) async def notify(self, event): notification = … -
specific name object django-money to render in template?
What is the specific object name in django field for currency and currency code ? i want to add class "form control" in that field. templates.html <div class="col-sm-4"> <label for="jumlahUsulanDana">Jumlah Usulan Dana</label> {{form.jumlah_dana_usulan}} </div> forms.py class Meta: model = UserUsulan exclude = ['status_usulan' ,'jumlah_dana_disetujui', 'keterangan_operator', 'com_reviewer_1', 'com_reviewer_2' ] widgets = {'jumlah_dana_usulan' : forms.TextInput({'class' : 'form-control', 'id' : 'jumlahUsulanDana', 'placeholder' : 'Jumlah Usulan Dana'}), } -
Django Allauth Social Login Return to Login Page
So I'm currently working with a single sign on server using django allauth and oauth-toolkit. After this I have two clients the first one is general purpose while the second one is a support kind of access portal. When a person is logging onto the support side I have a check to make sure that they are a support a support user (based on some fields within a shared view in mysql). If the person isn't part of said support team I want to redirect them to the login page and display an error. But when doing so I'm caught on an exception where I get 'HttpResponseRedirect' object has no attribute 'is_existing' As for the code class AuthAdapter(OAuth2Adapter): provider_id = AuthProvider.id # Fetched programmatically, must be reachable from container access_token_url = '{}:{}/o/token/'.format(settings.AUTH_BASE_URL, settings.AUTH_PORT) profile_url = '{}:{}/profile/'.format(settings.AUTH_BASE_URL, settings.AUTH_PORT) # Accessed by the user browser, must be reachable by the host authorize_url = '{}:{}/o/authorize/'.format(settings.AUTH_BASE_URL, settings.AUTH_PORT) def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) extra_data = resp.json() from support.users.views import check_support_user is_support_user = check_support_user(extra_data['id'], extra_data['username'], extra_data['email']) if not is_support_user: base_url = reverse("login") query_string = urlencode({ 'error': "Invalid" }) url = '{}?{}'.format(base_url, query_string) return HttpResponseRedirect(url) return self.get_provider().sociallogin_from_response(request, … -
Django admin: How to reverse the order of list_filter?
I have a dataset with models that show the year. What I need to do is reverse the order (since by default, the Django admin interface shows the year by order of ascending number value). models.py ... def model(models.Model): year = models.IntegerField() admin.py ... class ModelAdmin(admin.ModelAdmin): list_filter = ("year") I think this is a very trivial question, but I haven't found the solution yet. Thanks in advance. -
Django multiple jQuery Ajax html responses
I have a jQuery ajax call like this to get an html response and popolate an html div function loadProducts(url){ $.ajax({ type:"POST", url: url, data:{ data1: xxx }, dataType:"html",success:function(a){ $('#div1').html(a); } }) } Django response in python is like this def call_view(request): if request.method == "POST": return render(request, 'file1.html', { 'val1': val1, 'val2': val2 }) I would like to handle multiple html blocks in jQuery response like this and popolate more than one html div i tried this.. function loadProducts(url){ $.ajax({ type:"POST", url: url, data:{ data1: xxx }, dataType:"html",success:function(a){ $('#div1').html(a.resp1); $('#div2').html(a.resp2); } }) } and this from django.shortcuts import render def call_view(request): if request.method == "POST": return { 'resp1': render(request, 'file1.html', { 'val1': val1, 'val2': val2 }), 'resp2': render(request, 'file2.html', { 'val3': val3, 'val4': val4 }) } but doesn't work any suggestion? -
VSCode with Django: highlight unresolved static filess path
I would like to replicate the pycharm functionnality shown in this video at 10.45: https://www.youtube.com/watch?v=w9F9k-JHvcQ&ab_channel=JaradPython Basically it reveals/highlights unresolved url path in django html templates for static files. I've found the thread on this functionnality on pycharm but cannot replicate it on VSC editor. Many thanks -
How to display image in model instance in django admin instead of image path
I am writing a Django web app and I'm having a problem with displaying an image in existing model instance in Django admin and I hope you will be able to help me with it. I have a model with ImageField, when I upload an image to my model it is properly uploaded but instead of displaying the image in admin page there is path to the image displayed, please see screenshot: django admin screenshot Instead of a path I would like to display actual image. I checked with multiple solutions but I was only able to find an instructions how to display a thumbnail in a page listing all model instances. Could you advise me? -
Migrating Sqlite database to PostgreSQL for Heroku
I had a local Django project with a sqlite database. I am attempting to launch my project on Heroku and so I had to switch my database to PostgreSQL. To do this I dumped my sqlite database into a file called dump.sql and datadump.json I also changed my database settings to the below. I am getting an error about the database port and am unsure which port Heroku uses for me to put. I would appreciate any help in solving this error, I have attached my code below. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'NAME_OF_DB', 'USER': 'DB_USER_NAME', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', 'PORT': '5432', } } Error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? -
How to change default postgres user on django deployed on app engine standard environment?
I have a project using django which is deployed in app engine standard environment. When I use cloud_sql_proxy.exe for makemigrations on django, an error like this appears : (venv) G:\John Drive\Python\Project\My Project>python manage.py makemigrations G:\John Drive\Python\Project\venv\lib\site-packages\django\core\management\commands\makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "postgres" warnings.warn( No changes detected This is my settings.py # [START gaestd_py_django_secret_config] env = environ.Env(DEBUG=(bool, False)) env_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(env_file): # Use a local secret file, if provided env.read_env(env_file) # [START_EXCLUDE] elif os.getenv("TRAMPOLINE_CI", None): # Create local settings if running with CI, for unit testing placeholder = ( f"SECRET_KEY=a\n" f"DATABASE_URL=sqlite://{os.path.join(BASE_DIR, 'db.sqlite3')}" ) env.read_env(io.StringIO(placeholder)) # [END_EXCLUDE] elif os.environ.get("GOOGLE_CLOUD_PROJECT", None): # Pull secrets from Secret Manager project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") client = secretmanager.SecretManagerServiceClient() settings_name = os.environ.get("SETTINGS_NAME", "django_settings") name = f"projects/{project_id}/secrets/{settings_name}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env.read_env(io.StringIO(payload)) else: raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.") # [END gaestd_py_django_secret_config] # Database # [START db_setup] # [START gaestd_py_django_database_config] # Use django-environ to parse the connection … -
Nginx not serving any static files despite correct paths
I've been fighting this issue for about a week straight. At this point, I've tried every solution posted for this issue with no luck... I'm trying to deploy a test Django app with Gunicorn and Nginx. Nginx will not serve any static files. I am able to connect to the site through Nginx however, just without the static files. I have a folder 'static' within /home/my_name/testenv/testproject containing all my static files. Nginx is looking in the correct path for the static files, which I've confirmed with the access logs. Gunicorn also gives the correct paths when outputting the 404 errors. Things I've tried: Changed owner of the directory to www-data (user Nginx is using) Given 777 permissions to the directory containing the static files. added/removed trailing '/' to all paths in the configuration, tried in all different combinations. used 'root' and 'alias' in configuration. Tried both inside and outside of a virtual environment. Tried on a publicly accessible server as well as on localhost. Tried on different machines. Nginx configuration: server { listen 80; server_name 34.125.177.135; location /static { alias /home/my_name/django/testenv/testproject/static; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; … -
Django: is RawSQL dangerous inside a .annotation() method
I have a situation where I need to use RawSQL() over F() because of specific prosperities being 'some__prop', and I'm wondering if this is a risk for SQL Injection. I think it's not, because the RawSQL is only used within the select statement, but I'm not sure. .annotate(**{f"{alias}{key}": RawSQL(f"{key}_temp.value", [])})