Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django restrict choice options according to the usertype
I have two user types usertype a and usertype b i have a form to update the task with fields name,info and status i have STATUS_CHOICES = ( ('A','A'), ('B','B'), ('C','C') ) the user type a should c only ('A','A'),('B','B'), in dropdown and usertype b should have (C,C) as dropdown how do i acheive this in django the user type a should c only ('A','A'),('B','B'), in dropdown and usertype b should have (C,C) as dropdown how do i acheive this in django forms.py class Form(forms.ModelForm): class Meta: model = Model fields = (name', 'info',status') -
Django - Turn settings.DEBUG to True for one test
I have this test for checking if I can ping the swagger endpoint from django.test import SimpleTestCase from django.test.utils import override_settings from django.urls import reverse from rest_framework import status class SwaggerTest(SimpleTestCase): @override_settings(DEBUG=True) def test_successful_swagger_ping(self): """ Test to ensure that Swagger can be reached successfully. If this test throws 5XX that means there's an error in swagger annotation on some view function. """ response = self.client.get(reverse('swagger')) self.assertEqual(response.status_code, status.HTTP_200_OK) So this test fails, because I only have swagger added to url when settings.DEBUG=True. I thought @override_settings(DEBUG=TRUE) would fix that, but it doesn't. My test passes when I manually set settings.DEBUG=True under my settings.py file, otherwise it throws an error because it can't find the endpoint. I've tried decorating both the class and the function with @override_settings -
Can't send email through Django and Gmail
I keep getting this error while trying to send mail through gmail on my sign up form: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 7Iv4Nop2BfVsxIWEI1h5NxEG5QKSiQP2IRGqFYj-mB1tr4my5OBVeMzEbuG1hSttzGi2z\n5.7.14 O6-2CSgs_9v57jLx6MkoOy8yKLcw5zgCYzPQ40opvla_U9TqolpkdWMi5c4jyT1_>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 v8sm557096wrc.114 - gsmtp') Here is my smtp settings # smtp settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xbxx@gmail.com' EMAIL_HOST_PASSWORD = 'dgesfgg' -
How does a method of a class class run if you haven't instantiated an object for that class? Referring to Python's TestCase class
I am fairly new to Python (and programming in general) so this may be a noob question, but I was of the understanding that in python, when you create a class, and you create X methods within it, that if you want to leverage those methods, you need to instantiate the class or create an instance of the class. I am reviewing the TestCase module (testing goat for TDD) and I notice that we can run the program (performs all the logic within the methods of the classes) without actually creating any instance objects to "call" those methods directly. So my question is...how is it running. Ex. class AddStuff(TestCase): def test_equal_two(self): two = 1 + 1 self.assertEqual(two, 2) When I run python manage.py test, this will run, even though I haven't created an instance of AddStuff...I don't get it... -
Multiple model inheritance with one concrete and one abstract model in django
I wanted to inherit the Grandparent abstract model, parent concert model in the child model. How I'll be able to achieve this in django? There are conflicts in field name as the abstract model is having audit fields. which is common going to be common in both parent and child class. How do I override or remove the common field coming from the parent model? Below is the models which showcase what I wanted to achieve. class Audit(models.Model): is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class User(Audit): class Meta: db_table = 'user' email = models.EmailField(unique=True) phone = models.CharField(validators=[phone_regex], max_length=50, unique=True) is_active = models.BooleanField(default=False) class UserProfile(User, Audit): class Meta: db_table = 'user_profile' address = models.TextField(null=True) profile_image = models.TextField(null=True) dob = models.DateField() ..... -
Serving Media files in cPanel Shared Hosting for Django Web App
I am not able to display media files on Cpanel shared hosting Django web app. I receive a Error 404 URL Not Found whenever I try to access the media file. I have specified + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my urls.py file. This error only occurs whenever DEBUG = False. I am using whitenoise to serve the static files without any issue it is only the media directory that causes the 404 web error. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') I am using Python v3.8.6, Django=2.1 and CPanel Shared Hosting via NameCheap. I know it's recommended to have a webserver to store and serve media files in Production Environment but I am unable to edit the Apache httpd.conf file as mentioned in the Django documentation. -
Django Limiting Session Login Time to N seconds
I am trying to limit the amount of time a user can stay logged in for using the settings.py and using Sessions. settings.py LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 60 SESSION_SAVE_EVERY_REQUEST = True home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} urls.py from django.urls import path from django.views.generic.base import TemplateView # new urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home') ] views.py from django.shortcuts import render def index(request): # now the index function renders the home page return render(request,'home.html') Currently it stays logged in and displays the Hi user.username no matter how long the time passes. -
How to send non-empty Origin header in POST request if running an app on localhost?
I just upgraded to Django 4 and it includes the ticket 16010 with csrf origin verification changes. To my knowledge, if you are running an app on localhost, browsers won't send origin (they will send null). So, whenever we run a Django app on localhost, we should expect a header Origin: null in POST requests. But with the recent change CSRF on localhost can't be validated because of another change - CSRF_TRUSTED_ORIGINS now need to have a scheme. release notes Is it possible to add a non-empty Origin header when POSTing from localhost? -
is using base.hml in django templates good option?
I know extends base.html file in other html page is good to avoid repetition of same html tags , But is it good when come to page load speed does it increase load time of page ? , is page load time that extends from base.html same as page who does not ? -
Django Model does not exist error When accessing tabel from admin Panel
Ok so I was working on a project locally and then I followed a guide https://www.codingforentrepreneurs.com/blog/deploy-django-to-digitalocean-app-platform in order to deploy on digital ocean and i did successfully, However; When I open the Django admin panel and try to access my tables, some of the tables open up just fine while two other tables give the following error as illustrated.Error 1,Error 2. After hours and hours of searching questions here I reached a conclusion that something is wrong with the migrations. Regardless of how much I tried I failed to make it work. I will provide the Logs maybe it helps you out more. 10.244.3.92 - - [10/Dec/2021:22:08:06 +0000] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 3912 "https://scheduler-live-rcfr9.ondigitalocean.app/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" [scheduler-live] [2021-12-10 22:08:06] Not Found: /static/admin/js/nav_sidebar.js [scheduler-live] [2021-12-10 22:08:06] 10.244.3.92 - - [10/Dec/2021:22:08:06 +0000] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 3906 "https://scheduler-live-rcfr9.ondigitalocean.app/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" [scheduler-live] [2021-12-10 22:08:08] Internal Server Error: /admin/myapi/schedule/ [scheduler-live] [2021-12-10 22:08:08] Traceback (most recent call last): [scheduler-live] [2021-12-10 22:08:08] File "/workspace/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute [scheduler-live] [2021-12-10 22:08:08] return self.cursor.execute(sql, params) [scheduler-live] [2021-12-10 22:08:08] psycopg2.errors.UndefinedColumn: column myapi_schedule.Start_Time does not exist [scheduler-live] [2021-12-10 22:08:08] … -
Dango - How to use "setUpTestData" with TransactionTestCase
I've created a test class, which is a TransactionTestCase and I tried setting up the test data as so test.py class SomeTester(TransactionTestCase): @classmethod def setUpTestData(cls) -> None: cls.some_data = 'stuff" but when I reference self.some_data in test functions it says self.some_data is not defined. Can you not use setUpTestData with TransactionTestCase? This works with TestCase class. -
Initialize field to constant value in django Form
How can I set up a model/form combination so that the field in the model is initialized to a fixed value and there is no form element displayed when the form is presented to the user? I just want to initialize Source.updated = datetime.datetime(2000, 1, 1, 0, 0, 0, 0) each time a new Source is created from a form. The user cannot over-ride this initial default. (Subsequent interaction with the app will cause this field value to change, but it's not just auto_now because I want the initial value to be far in the past.) What I have now is class Source(Model): name = models.CharField(max_length=168, help_text="Source name") link = models.URLField(primary_key=True, help_text="Data source link") type = models.CharField(max_length=64, help_text="Data source type") # TODO: add this field to the model. # have it initialize to 2000-01-01 #updated = models.DateTimeField(help_text="Most recent time this source has been updated") class SourcesForm(forms.ModelForm): class Meta: model = models.Source fields = ['name', 'link', 'type',] # TBD: how to configure the form so that # it initializes the "updated" field with a fixed value # when .save() is called The logic I'm trying to implement is that: we're getting data from a remote source, so I want to know … -
is there a way to fluidly calculating total sales using JS with Django
I'm looking for a way to take the information being entered into a database and not only calculate the overall total for a year but also calculate the total for individual months. I'm using Django and Javascript. The Django View: @login_required def proposal_signed(request): prop = Proposal.objects.all().order_by('proposal_approved_date') return render(request, 'client/proposal_signed.html', { 'prop': prop, }) The HTML and JS: {% extends 'client/base.html' %} {% block content %} <br> <div class="jumbotron jumbotron-fluid"> <div class="container"> <div class="text-center"> <h1 class="display-4"> Sales For Signed Proposals </h1> </div> </div> </div> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> <title></title> </head> <div class="container"> <table id="countit"> <tr> <th><strong>Approval Date:</strong></th> <th><strong>Job Type:</strong></th> <th><strong>Address:</strong> <th><strong>Client:</strong></th> <th><strong>Bid/Job Total:</strong></th> </tr> {% for item in prop %} {% if item.proposal_approved_date %} <tr> <td>{{ item.proposal_approved_date }}</td> <td>{{ item.client.requested_service }}</td> <td>{{ item.client.work_site_address }}</td> <td>{{ item.who_to_bill_name }}</td> <td class="count-me">{{ item.client.invoice_set.get.bill_amount }}</td> </tr> {% endif %} {% endfor %} </table> <script language="javascript" type="text/javascript"> var tds = document.getElementById('countit').getElementsByTagName('td'); var sum = 0; for(var i = 0; i < tds.length; i ++) { if(tds[i].className === 'count-me') { sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML); } } document.getElementById('countit').innerHTML += … -
Django4 + Jinja2 href url not working in template
I can't get simple urls to work in my Jinja2 templates in Django 4. This literally should be the easiest code, but it keeps throwing errors like this: ("Encountered unknown tag 'url'.",) Request Method: GET Request URL: http://127.0.0.1:8000/browse/a/ Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: ("Encountered unknown tag 'url'.",) Exception Location: /home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/lib/python3.8/site-packages/django/template/backends/jinja2.py, line 47, in get_template Python Executable: /home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/bin/python Python Version: 3.8.10 Python Path: ['/home/joop/sites/khinsider', '/snap/pycharm-community/261/plugins/python-ce/helpers/pydev', '/home/joop/sites/khinsider', '/snap/pycharm-community/261/plugins/python-ce/helpers/third_party/thriftpy', '/snap/pycharm-community/261/plugins/python-ce/helpers/pydev', '/home/joop/.cache/JetBrains/PyCharmCE2021.3/cythonExtensions', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/lib/python3.8/site-packages'] This is the template code: <a href="{% url 'browse' 'a' %}">test</a>. The urls.py path: path('browse/<str:char>/', main.views.browse, name='browse') The settings TEMPLATES config: TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": ['jinja2'], "APP_DIRS": True, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I tried all kinda of variations but nothing works. -
Django models & relationship with store products? how to solve relationship?
I have a relationship that makes my website unable to function properly? I have a picture of my debugging situation, do you why it shows the wrong line error? debugging result debugging result 2 from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='Products/') updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() # to call out the table orderitem in reverse all total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) … -
Django/Ubuntu: Error 1045, "Access denied for user 'www-data'@'localhost' (using password: YES)"
I am trying to test out a Log-In page for a Django site hosted publicly on Apache2 by logging in remotely. However when entering any credentials to test I get the following error: [1045, "Access denied for user 'www-data'@'localhost' (using password: YES)"] I am assuming that this means the www-data Apache2 default user can't access my MySQL table? What would be the best way to allow access safely? -
React working on local machine but not on other local network machine
I am hosting a reactjs project on port 3000 as front end and django project on port 8000 as backend on the same machine. So when rending, reactjs will get data by calling django APIs. I (thought I) had correctly setup CORS headers in Django settings. Both http://localhost:3000/ and http://192.168.86.21:3000/ are working on my local machine. 192.168.86.21 is my LAN IP. But when I access http://192.168.86.21:3000/ on another machine or tablet in my LAN. Only static files are rendered. I inspect the Chrome it shows: " Access to fetch at '..django_ip_port...' from origin '..my_ip_port..' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. " It's really weird. -
django rest api deleting data from db
Whenever I access data using django rest api it gets deleted. Getall seems to work but view detail or update deletes the data. When I create I get a "201 Created" but the information is not stored in db. I am using the django sql_lite db and even with superuser it still gets deleted. I have checked my serializers, models and views for errors. I have to create data directly into the db. I have checked migrations to make sure they were up to date. views.py from django.shortcuts import render from rest_framework import generics from .serializers import RoomListSerializer, RoomDetailSerializer from .models import Room class RoomListAPIView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomListSerializer class RoomRetrieveAPIView(generics.RetrieveAPIView): lookup_field = "id" queryset = Room.objects.all() serializer_class = RoomDetailSerializer class RoomCreateAPIView(generics.CreateAPIView): queryset = Room.objects.all() print(queryset) serializer_class = RoomDetailSerializer class RoomRetrieveUpdateAPIView(generics.RetrieveUpdateAPIView): lookup_field = "id" queryset = Room.objects.all() serializer_class = RoomDetailSerializer class RoomDestroyAPIView(generics.DestroyAPIView): lookup_field = "id" queryset = Room.objects.all() models.py from django.db import models class Room(models.Model): room_name = models.CharField(max_length=200, blank=False) description = models.TextField(blank=True) width = models.CharField(blank=False, default="5", max_length=10) length = models.CharField(blank=False, default="5", max_length=10) def __str__(self): return f"{self.room_name}: {self.width} by {self.length}" serializers.py from rest_framework import serializers from .models import Room from rest_framework.reverse import reverse class RoomListSerializer(serializers.ModelSerializer): absolute = serializers.SerializerMethodField() class … -
can not connect to clearDBmySQL from django
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tajaratdatabase', 'USER': '', #here I am using my username 'PASSWORD':'', #here I am using my password 'HOST':'us-cdbr-east-04.cleardb.com', 'PORT':'3306', } } I f I use the same credentials on MySQLworkbench my connection is successfully established but if I try to connect from my terminal and run command python manage.py makemigrations I got an error django.db.utils.OperationalError: (1044, "Access denied for user 'bf76.....'@'%' to database 'tajaratdatabase'") how can I remove this error and can make my connection successful -
How to build a demo for a Web Dashboard App in 28 days?
Here is my situation: I need to present a demo of an online dashboard app in beginning of January. Skills: I know some Python (especially the data science frameworks) but have not yet worked with django / flask or other languages than Python. Goal: The app does not have to have many features. Mainly: login and visualisation of data, maybe some filters like date or category. It mainly needs to LOOK really good but can involve some parts being hard-coded. My first approach: I saw bootstrap templates which look good already but is using django with such templates really the most efficient way for only a demo? I guess there is some really nice way which may not even involve extensive coding but still offers some flexibility regarding page elements? Thank you for your advice! -
Trying to write a script to upload files to a django project
I have a django 3.x project where I can upload multiple files and associated form data through the admin pages to a model called Document. However, I need to upload a large number of files, so I wrote a small python script to automate that process. I am having one problem with the script. I can't seem to set the name of the file as it is set when uploaded through the admin page. Here is the script...I had a few problems getting the csrf token working correctly, so there may be some redundant code for that. import requests # Set up the urls to login to the admin pages and access the correct add page URL1='http://localhost:8000/admin/' URL2='http://localhost:8000/admin/login/?next=/admin/' URL3 = 'http://localhost:8090/admin/memorabilia/document/add/' USER='admin' PASSWORD='xxxxxxxxxxxxx' client = requests.session() # Retrieve the CSRF token first client.get(URL1) # sets the cookie csrftoken = client.cookies['csrftoken'] print("csrftoken1=%s" % csrftoken) login_data = dict(username=USER, password=PASSWORD, csrfmiddlewaretoken=csrftoken) r = client.post(URL2, data=login_data, headers={"Referer": "foo"}) r = client.get(URL3) csrftoken = client.cookies['csrftoken'] print("csrftoken2=%s" % csrftoken) cookies = dict(csrftoken= csrftoken) headers = {'X-CSRFToken': csrftoken} file_path = "/media/mark/ea00fd8e-4330-4d76-81d8-8fe7dde2cb95/2017/Memorable/20047/Still Images/Photos/20047_Phillips_Photo_052_002.jpg" data = { "csrfmiddlewaretoken": csrftoken, "documentType_id": '1', "rotation" : '0', "TBD": '350', "Title": "A test title", "Period": "353", "Source Folder": '258', "Decade": "168", "Location": "352", … -
Save sensor data in a Django database
Im doing a Django app that tries to show data taken from an ultrasonic sensor. What I want is to take the distance from the sensor and save it in its Django table. Normally this is done with a form, but i want it to be done in the backend for each sensor object. This is the code that i have for the moment: Ultrasonicsensor.py import time from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger def main(): # Grove - Ultrasonic Ranger connected to port D16 sensor = GroveUltrasonicRanger(16) counter = 10 while (counter < 10): distance = sensor.get_distance() #This is the distance i want to save for each sensor object distance = (float(distance) / 100) print('{:.4f} m'.format(distance)) if distance < 1: print('Cerca') elif 1 <= distance <= 1.9: print('Medio') else: print('Lejos') time.sleep(1) counter = counter + 1 Models.py class UltrasonicSensor(models.Model): name = models.CharField(max_length=50, default="HC-SR04") description = models.TextField() pin = models.IntegerField() distance = models.DecimalField(max_digits=20, decimal_places=4) date = models.DateTimeField(auto_now_add=True) Views.py class uSensorDetailView(DetailView): template_name = 'sensor_detail.html' context_object_name = 'sensor' def get_queryset(self): return UltrasonicSensor.objects.all() -
Getting wrong headers for Traefik ForwardAuth middleware
I've been trying to develop a custom auth thing for Traefik using Django and the ForwardAuth middleware. Unfortunately, I'm having troubles with the provided headers for my application: My auth app has three endpoints: /auth/, which checks whether the user is authenticated. If it is, returns a "OK" with status code 200. If it's not, tries to get the X-Forwarded-Host in order to build a redirect argument using f"?redirect={request.headers['X-Forwarded-Proto']}://{request.headers['X-Forwarded-Host']}" and then redirect to /auth/login/{redirect_url} /auth/login, which renders a form and then authenticates with Django (it uses the same logic as /auth/ for setting up a redirect URL /auth/logout It's exposed at https://auth.my-ip.nip.io, using the following: apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: django-auth spec: entryPoints: - websecure routes: - match: Host(`auth.my-ip.nip.io`) kind: Rule services: - name: django-auth port: 80 tls: secretName: auth.my-ip.nip.io The middleware is configured as follows: apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: django-auth spec: forwardAuth: address: https://auth.my-ip.nip.io:443/auth/ trustForwardHeader: true Finally, I've got an example app exposed and using the django-auth middleware: apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: game-2048 spec: entryPoints: - web - websecure routes: - match: Host(`2048.my-ip.nip.io`) kind: Rule services: - name: game-2048 port: 80 middlewares: - name: django-auth tls: secretName: 2048.my-ip.nip.io But then, when I try to … -
Django deployment with docker - create superuser
I have 3 environments set up and cannot createsuperuser. The way I migrate and runserver now follows the container so I have an entrypoint.sh: #!/bin/sh 1 2 echo "${RTE} Runtime Environment - Running entrypoint." 3 4 if [ "$RTE" = "dev" ]; then 5 6 python manage.py makemigrations --merge 7 python manage.py migrate --noinput 8 python manage.py runserver 0:8000 9 10 python manage.py createsuperuser --username "admin" --email "admin@banl.com" --password "superuser" 11 echo "created superuser" 12 13 elif [ "$RTE" = "test" ]; then 14 15 echo "This is tets." 16 python manage.py makemigrations 17 python manage.py migrate 18 python manage.py runserver 19 20 elif [ "$RTE" = "prod" ]; then 21 22 python manage.py check --deploy 23 python manage.py collectstatic --noinput 24 gunicorn kea_bank.asgi:application -b 0.0.0.0:8080 -k uvicorn.workers.UvicornWorker 25 26 fi lines 10/11 is what I want to make work, I think I have a syntax issue. Originally I wanted the password and username to be variables stored in an env file: 1 RTE=dev 1 POSTGRES_USER=pguser 2 POSTGRES_PASSWORD=pgpassword 3 POSTGRES_DB=devdb 4 DJANGO_SUPERUSER_PASSWORD=superuser 5 DJANGO_SUPERUSER_EMAIL=admin@bank.com 6 DJANGO_SUPERUSER_USERNAME=admin But now I just want it to work, I need to create a superuser account in order to develop. Can anyone spot what's wrong? … -
react-django connectivity issues, 500 internal server errors
I’m working on a project using react as the frontend and Django rest api as backend. Unfortunately, I’m having some issues. Here are the issues I’m facing: From the Django setting.py file, I set the static directory folder to “build” (for css, images and JavaScript) and media folder (for user uploaded files) file to “media” as shown below. But I observed that only the “media” folder shows up in the directory structure and not the “build” folder. PLEASE WHAT COULD BE PREVENTING THE “BUILD” FOLDER FROM SHOWING? STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/medial/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I understand that normally when you run “npm build” and copy the build folder generated from the frontend to replace the one in the Django backend, then you can begin to use “localhost:8000” to access your pages rather than continue to use “localhost:3000”. I did the above, but I wasn’t able to load the pages using “localhost:8000” but instead getting 404 error. PLEASE WHAT COULD BE THE ISSUES? I created some routes (post and get), tested all the routes in postman as well as the browser, and they (routes) are all working perfectly. …