Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to add video to webpage and I keep gettting 404 error anyone know how to fix it?
I believe I have tried almost everything. What I am working with -
Djnago views.py need some assistance to visualize my uploaded file to html
I am working on Django project. I created HTML, css and js files for templates where user can choose a file with choose file button. It is control by .js file. My js file looks like this: document.addEventListener('DOMContentLoaded', function() { const uploadBtn = document.querySelector(".upload-btn"); const trainBtn = document.querySelector(".train-btn"); const visualizeBtn = document.querySelector(".visualize-btn"); const fileInput = document.querySelector("#file-input"); const img = document.querySelector(".csv"); let file = null; // To store the uploaded file uploadBtn.addEventListener("click", (event) => { console.log("Upload button clicked"); event.preventDefault(); fileInput.click(); }); fileInput.addEventListener("change", (event) => { file = event.target.files[0]; // Update the uploaded file if (file) { const reader = new FileReader(); reader.onload = (e) => { const fileURL = e.target.result; img.src = fileURL; visualizeBtn.disabled = false; }; reader.readAsDataURL(file); trainBtn.disabled = false; } else { visualizeBtn.disabled = true; trainBtn.disabled = true; } }); visualizeBtn.addEventListener("click", () => { console.log("Visualizing data..."); if (file) { const reader = new FileReader(); reader.onload = (e) => { const fileContent = e.target.result; saveFile(fileContent); }; reader.readAsText(file); } }); function saveFile(fileContent) { const filename = 'data/' + file.name; const link = document.createElement('a'); link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContent)); link.setAttribute('download', filename); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }); I am trying to create a views in views.py file. where I want to visualize data information … -
Django cannot download docx file in ajax
I have a script directs to badownload function for downloading docx file. The result of this function is download docx file but it didn't work. Here is the script. <script> $("#download_draft").click(function(){ $("#download_draft").attr("disabled","disabled"); $("#download_draft").text("Saving Data...."); var json_data={}; $(".input_data").each(function(){ var value=$(this).val(); var parent_html=$(this).parent(); parent_html.html(value); $(this).remove(); }); var jenis_ba = $('#id_jenis_ba').val(); json_data['jenis_ba'] = jenis_ba; var nomor= $('#id_nomor').val(); json_data['nomor'] = nomor; var tanggal = $('#id_tanggal').val(); json_data['tanggal'] = tanggal; var judul = $('#id_judul').val(); json_data['judul'] = judul; var keterangan = $('#keterangan').val(); json_data['keterangan'] = keterangan; var json_tim = []; $("tbody tr").each(function(row, tr){ json_tim[row] = { 'nama_tim' : $(tr).find('td:eq(0) input').val(), 'nip_tim' : $(tr).find('td:eq(1) input').val() } }); json_data['tim'] = json_tim; var string_data=JSON.stringify(json_data); const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; $.ajax({ url:'{{ download_draft }}', headers: {'X-CSRFToken': csrftoken}, type:'GET', dataType: 'json', data:{data:string_data}, success: function(data) { badownload(data); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); }, complete: function() { $("#download_draft").removeAttr("disabled"); $("#download_draft").text("Download Draft"); } }); function badownload(result){ $.ajax({ url: '../../berita-acara/badownload', headers: {'X-CSRFToken': csrftoken}, type:'POST', dataType: 'json', data:{data:result.result}, success: function(data) { console.log('sukses'); }, error: function(jqXHR, textStatus, errorThrown) { console.log(url); }, }) } }); </script> This is the function. It has to download download.docx file but it didn't work class BeritaAcaraBA(View): def post(self, request): ..... ...... ....... response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response I … -
Why I am I getting a 400 bad request when sending a post request with the correct json data on POSTMAN to my registration url?
I am running my django rest framework backend locally which will act as a backend for a social media app. I am testing out registering a user to my backend by sending a post request to my local register url with the following json data on postman : "username": "johndoe123", "first_name": "john", "last_name": "doe", "cuny_email": "johnluzada22@hunter.cuny.edu", "major": "Economics", "CUNY": "Hunter College", "graduation_year": 2024, "birth_date": "2023-05-02" Even though all fields are correctly filled out I get a 400 bad request. And in postman I get the following response back from my backend { "username": [ "This field is required." ], "cuny_email": [ "This field is required." ], "password": [ "This field is required." ], "confirm_password": [ "This field is required." ], "CUNY": [ "This field is required." ] } I changed the json fields to match the exact name of the fields expected in my backend. I also reset my django rest framework server and I tested the post request in my local django rest framework server which seemed to work. However when I send the request in postman I still get the error. -
How to call spesific function in Django url
I have a script that directs to url Django. I want to call a function call badownload but it says "TypeError: BeritaAcaraCreate.badownload() missing 1 required positional argument: 'request'" I am still new in Django. Please help me to fix this error. Here is my script <script> $("#download_draft").click(function(){ $("#download_draft").attr("disabled","disabled"); $("#download_draft").text("Saving Data...."); var json_data={}; $(".input_data").each(function(){ var value=$(this).val(); var parent_html=$(this).parent(); parent_html.html(value); $(this).remove(); }); var jenis_ba = $('#id_jenis_ba').val(); json_data['jenis_ba'] = jenis_ba; var nomor= $('#id_nomor').val(); json_data['nomor'] = nomor; var tanggal = $('#id_tanggal').val(); json_data['tanggal'] = tanggal; var judul = $('#id_judul').val(); json_data['judul'] = judul; var keterangan = $('#keterangan').val(); json_data['keterangan'] = keterangan; var json_tim = []; $("tbody tr").each(function(row, tr){ json_tim[row] = { 'nama_tim' : $(tr).find('td:eq(0) input').val(), 'nip_tim' : $(tr).find('td:eq(1) input').val() } }); json_data['tim'] = json_tim; var string_data=JSON.stringify(json_data); const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; $.ajax({ url:'{{ download_draft }}', headers: {'X-CSRFToken': csrftoken}, type:'GET', dataType: 'json', data:{data:string_data}, success: function(data) { badownload(data); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); }, complete: function() { $("#download_draft").removeAttr("disabled"); $("#download_draft").text("Download Draft"); } }); function badownload(result){ $.ajax({ url: '../../berita-acara/badownload', headers: {'X-CSRFToken': csrftoken}, type:'POST', dataType: 'json', data:{data:result.result}, success: function(data) { console.log('sukses'); }, error: function(jqXHR, textStatus, errorThrown) { console.log(url); }, }) } }); </script> Here is the url path('berita-acara/badownload', BeritaAcaraCreate.badownload, name='berita-acara/badownload'), This is the badownload function def badownload(self, request): result = … -
Random emails sendt by sendinblue
I made a "Sendinblue" account today. I set up everything with the company name, my name, etc and verified that the SMTP was working fine. One hour later, I got an email which told me that I have reached my 300 daily email limit, but as much as I know, there were only sent two emails from me. The other emails were sent from my email to random emails. Why? -
After logging out from another tab, I still have user in my scope['session'] in django channels
What I want to do is disconnect the websocket connection while the user has logged out from another tab. So, I use get_user() in django channels to check if user is still logged in(in session). I opened multiple tabs at the same time. And I logged out from one of the tabs. However, after logging out, it still shows the user.is_authenticated = True and I can have user from self.scope["user"]. What's problem with my code here? Here is my code. In views.py from django.contrib.auth.views import LogoutView ... class Logout(LogoutView): template_name = "account/logout.html" # log user out In cousumers.py from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer class Chat(JsonWebsocketConsumer): ... def receive_json(self, content, **kwargs): message = content['message'] user = async_to_sync(get_user)(self.scope) logging.info(user.is_authenticated) # still true after logging out logging.info(f'user is {self.scope["user"]}') # show the user as well if user is None: return self.disconnect() self.send_json(content={'message': f'receive: {message}'}) ... I've checked the documentations ans source files of both django and django-channels, and tried to use logout from channels.auth at consumers.py. It works but not what I want to use. I expect that I could get the correct session without user status. -
How to get the id of a post from django and use it on javascript?
I have posts that I'd like to edit. The thing is they're inside a for loop and I don't know which one the user is going to click. How could I do this? Template: {% for post in posts %} {% if request.user == post.poster %} <a id="editPost-{{ post.id }}" href="javascript:;" style="display: block;">Edit</a> <form id="editForm-{{ post.id }}" style="display: none;" method="POST" action="{% url 'editPost' post.id %}"> {% csrf_token %} <input type="hidden" name="_method" value="PUT"> <div class="form-group"> <textarea class="form-control">{{ post.content }}</textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endif %} <p id="postContent-{{ post.id }}">{{ post.content }}</p> </div> {% endfor %} JS: document.addEventListener("DOMContentLoaded", function () { const editBtn = document.querySelector('#editPost'); const postContent = document.querySelector('#postContent'); const editForm = document.querySelector('#editForm'); editBtn.style.display = 'block'; postContent.style.display = 'block'; editForm.style.display = 'none'; editBtn.addEventListener('click', () => { editBtn.style.display = 'none'; editForm.style.display = 'block'; postContent.style.display = 'none'; }); }); -
DRF ModelSerializers dictionary update sequence element #0 has length 1; 2 is required
I'm starting in DRF and I'm trying to make a serializer for my login system with a ModelSerializer passing certain Fields or with all fields but I always get the same error using ModelSerializer, I managed to solve it without using the ModelSerializer but I want to do it with this one but I can't find any solution :( ModelSerializer class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'phone_number', ] View class UserRegisterAPIView(APIView): def post(self, request, *args, **kwargs): serializer = UserRegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() data = {'user_data': UserModelSerializer(user).data} return Response(data, status=status.HTTP_201_CREATED) UserRegisterSeriliazer class UserRegisterSerializer(serializers.Serializer): username = serializers.CharField(min_length = 8, max_length=25, validators = [UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField(min_length=8, max_length=25) password_confirmation = serializers.CharField(min_length=8, max_length=24) first_name = serializers.CharField(min_length=2, max_length=25) last_name = serializers.CharField(min_length=2, max_length=25) email = serializers.CharField(max_length=25, validators = [UniqueValidator(queryset=User.objects.all())]) phone_regex = RegexValidator( regex = r'\+?1?\d{8,10}$', message = 'Please enter a valid phone number' ) phone_number = serializers.CharField(validators=[phone_regex]) I tried using a normal serializer and it solved it but I don't understand why with a modelserializer it doesn't work, besides I want to apply with modelserializer for good practices. -
Django creating mutliple apps but how to structure
I have been using django from last 2 - 3 years.I have always use single app for handling everything for my project. But now i decided to use multiple apps for multiple features and every app handling single feature but i can't decide what approach should i use ? and what is the best approach ?. Should I create an app named core for handling the home page, about page and authentication and then just created different apps for different functionality. What You suggest and is there any hard rules of structuring django project or just it matters of personal choice -
Not able to upload images to Django with form: 404 POST / not found
I was trying to create a webpage where users can upload their images and store them in Django but for some reason am not able to upload it. I followed these tutorials. This is the html code <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-lg btn-success">Upload</button> </form> settings.py STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATICFILES_DIRS = (os.path.join(BASE_DIR,"static"), ) models.py under the app Lightings from django.db import models from django.contrib.auth.models import User class MovieImage(models.Model): image_upload=models.ImageField(null=True,blank=True,upload_to="userimages/") forms.py from django import forms from .models import * class MovieImageForm(forms.ModelForm): class Meta: model=MovieImage fields=('image_upload',) labels={ 'image_upload':'', } views.py from django.shortcuts import render from .forms import MovieImageForm from .models import * # Create your views here. def startlighting(request): return render(request,'Lightings.html') def index(request): if request.method == "POST": form=MovieImageForm(request.POST,request.FILES) if form.is_valid(): form.save() return render(request,"Lightings.html") else: form=MovieImageForm() return render(request,'Lightings.html',{'form':form}) urls.py at project level from django.contrib import admin from django.urls import path,include from homepage.views import start from About.views import aboutstart from Lightings.views import startlighting from django.conf import settings from django.conf.urls.static import static from Lightings.views import * urlpatterns = [ path('admin/', admin.site.urls), path("home",start), path("About",aboutstart), path("Lightings",startlighting), path("Lightings",index) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
autoplay attribute plays all videos that are in django for loop
I'm building a web application with Django that includes a list of video generated by a for loop. Each video element has an HTML5 video tag with a src attribute pointing to a different video file, and an autoplay attribute set to true. However, when I render the page, all videos start playing at once, overlapping each other and creating a chaotic sound. What could be causing this behavior, and how can I fix it? Is there a way to make each video start playing only when it's visible on the screen, or when the user interacts with it? Any help would be appreciated. I want to set the videos in my for loop to autoplay so that when a user visits the website, there is no need to click on the play and pause icons when they want to watch different videos. What I want is for the video to stop when the user scrolls down and the next one to start playing like facebook videos and other social media platform. <div class="container video-container"> <div class="row justify-content-center"> <div class="col-md-3 p-1"> {% for video in my_videos reversed %} <div class="row position-relative my-1 wrapper"> <video loop id="my-video" class="video-js vjs-theme-city vjs-default-skin vjs-big-play-button … -
How to filter related field(array) Django rest framework?
I have 2 models class Employee(models.Model): name = models.CharField(max_length=255) dateOfBirth = models.DateField(blank=True, null=True) phone = models.CharField(blank=True, max_length=255, null=True) passNumber = models.CharField(max_length=255, blank=True, null=True) passGet = models.CharField(blank=True, max_length=255, null=True) passDate = models.DateField(blank=True, null=True) address = models.CharField(max_length=255,blank=True, null=True) position = models.ForeignKey('Positions', on_delete=models.PROTECT, null=True) startDate = models.DateField(blank=True, null=True) userName = models.OneToOneField(User, on_delete=models.CASCADE, related_name="employee", null=True, blank=True) is_fired = models.BooleanField(default=False, blank=True) class Schedule(models.Model): date = models.ForeignKey(Calendar, related_name='workers', on_delete=models.CASCADE) employee_id = models.ForeignKey(Employee, related_name='worked', on_delete=models.CASCADE, null=True) is_worked = models.BooleanField(default=True, blank=True) start_time = models.TimeField(blank=True, null=True) fact_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) And have 2 serializers class ScheduleReportsSerializer(serializers.ModelSerializer): moneys = MoneyOperationsScheduleSerializer(many=True, read_only=True) class Meta: model = Schedule exclude = ['employee_id'] class EmployeeReportsSerializer(serializers.ModelSerializer): position = PositionsSerializer(read_only=True) worked = ScheduleReportsSerializer(many=True, read_only=True) class Meta: model = Employee fields = ('name', 'position', 'worked') And viewSet class EmployeeReportsViewSet(viewsets.ModelViewSet): serializer_class = EmployeeReportsSerializer def get_queryset(self): queryset = Employee.objects.all().filter(is_fired=False).order_by('position__groupName') mindate = self.request.query_params.get('mindate') maxdate = self.request.query_params.get('maxdate') if mindate and maxdate: schedule_qs = Schedule.objects.filter(date__date__range=[mindate, maxdate]).order_by('date') NEED HELP HERE return queryset I need after request reports/?mindate=2023-04-10&maxdate=2023-04-16 Return all Employees and filter WORKED field by mindate=2023-04-10&maxdate=2023-04-16 and order Something like that "worked": [ { "id": 72, "moneys": [], "is_worked": true, "start_time": null, "fact_time": null, "end_time": null, "date": "2023-04-10" }, { "id": 55, "moneys": [], "is_worked": true, "start_time": null, "fact_time": … -
Django Query for current stock list from operations table field with IN, OUT value and field with date and time
Django Query for below case to find list of available stock based on ops_type=IN entry with date and time and ops_type=OUT entry with date and time. date and time field are separate because the data is uploaded from sheet and needs to be in same format to process. Operations model is as follows class Operations(BaseModel): class OPS(IntEnum): IN = 0 OUT = 1 @classmethod def choices(cls): return [(key.value, key.name) for key in cls] date = models.DateField() time = models.TimeField(default=None, null=True) ops_type = models.IntegerField(choices=OPS.choices()) serial = models.CharField(max_length=255, default=None, null=True, db_index=True) product = models.CharField(max_length=255, default=None) Error: Cannot resolve keyword 'latest_out_datetime' into field. Join on 'serial' not permitted. from django.db.models import F, Q, Subquery, OuterRef, ExpressionWrapper, DateTimeField from datetime import datetime in_entries = Operations.objects.filter(ops_type=Operations.OPS.IN.value) out_entries = Operations.objects.filter( ops_type=Operations.OPS.OUT.value, serial=OuterRef('serial') ).values('serial').annotate( latest_out_datetime=Subquery( Operations.objects.filter( ops_type=Operations.OPS.OUT.value, serial=OuterRef('serial') ).annotate( datetime=ExpressionWrapper(F('date') + F('time'), output_field=DateTimeField()) ).order_by('-datetime').values('datetime')[:1] ) ) available_stock = in_entries.annotate( in_datetime=ExpressionWrapper(F('date') + F('time'), output_field=DateTimeField()), latest_out_datetime=F('serial__latest_out_datetime') ).filter( Q(latest_out_datetime__isnull=True) | Q(in_datetime__gt=F('latest_out_datetime')) ) stock_list = [stock.serial for stock in available_stock] print("List of available stock:", stock_list) -
Is there anyway to protect Django source code from being revealed, after giving server access to the client?
After deploying a Django project and giving server access to the client, is there anyway to protect the source code from being revealed? Maybe somthing like seperating the servers for holding the database and the source code? Or having some lock or something on the docker container of the Django project? -
How to query the current user from the database - Django
I am currently in a fix and need your help. I am working on an API using Django_rest_framework and currently on tthe registration module. The code below is a feature that regenerate OTP and send to the current user. However, I can't access the current user, but i have his details in the database..eg: phone_nuumber, is_active=False, is_verified=False. I want to be able to access the user using his phone number then regennerate OTP and send to his phone number after the OTP expires. # regenerate OTP class RegenerateOTP(APIView): @swagger_auto_schema( operation_summary="This endpoint is responsible for regenerating OTP if expired", operation_description="This endpoint regenerate OTP after expiration period", ) def post(self, request): instance = CustomUser.objects.filter(is_active=False).first() if int(instance.max_otp_try) == 0 and timezone.now() < instance.otp_max_out: return Response( "Max OTP try reached, try after an hour.", status=status.HTTP_400_BAD_REQUEST, ) otp = generateRandomOTP(100000, 999999) otp_expire = timezone.now() + timedelta(minutes=10) max_otp_try = int(instance.max_otp_try) - 1 instance.otp = otp instance.otp_expire = otp_expire instance.max_otp_try = max_otp_try if max_otp_try == 0: instance.otp_max_out = timezone.now() + datetime.timedelta(hours=1) elif max_otp_try == -1: instance.max_otp_try = settings.MAX_OTP_TRY else: instance.otp_max_out = None instance.max_otp_try = max_otp_try instance.save() send_otp(instance.phone_number, otp) return Response( "successfully re-generated the new otp", status=status.HTTP_200_OK ) I have tried saving the user's phone_number when registering in … -
How to Display a String on a DJango Form, but still reference the model
I have this form: In this form I prepopulate the dropdown with the golfer's name. I do this by using the str method associated with the model The problem I run into is this no longer has any relationship to the object. So the Form is expecting a Foreign Key, but is getting a string. is there a way to display the sting for the form, but still keep the model's PK when I POST the form? -
Can't upload files to Digital Ocean Spaces
I have managed to set my environment variables for Digital ocean, AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # static settings AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I also ran: ./manage.py collectstatic And it ran successfully, all files uploaded to Digital ocean. But my challenge now is that, when I upload Images with Django Admin, they don't upload to Digital ocean, they rather upload to local folders. What am I missing in the configuration? -
The password page is still not showing up after clicking the form
I need to change the address of my prototype blog post url to http://127.0.0.1:8000/members/password/ from http://127.0.0.1:8000/3/password/. I am using django http://127.0.0.1:8000/3/password/ this is shown in the address bar when I click on the this form link on- Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. But I actually need it to be http://127.0.0.1:8000/members/password/ to be able to update password or work something on that. How can I change my url? My current url path looks like this- path('password/', auth_views.PasswordChangeView.as_view(template_name='blog/password_change.html')), But I already tried this path('members/password/', auth_views.PasswordChangeView.as_view(template_name='blog/password_change.html')), What should I do? -
Deploying django, postgres, react, nginx app to google app engine
I want to deploy my first project on google cloud (didn't had any experience before this project with google cloud). My project is built on django, react, postgresql, nginx. The project is dockerized with a multiple containers and I am using docerk-compose. To my understanding best choice is app engine ( cloud run would be good in case if I had only one container ) cloud compute and kurbernete would be too complicated for my app or as first deployment. I general my questions is to understand the most robust way to deploy my app. In following description will be some more detailer questions to understand overall concept. 1. General process deploying Most similar setup on online courses I found London app developer for example docker-compose -f docker-compose.pd.yml run --rm gcloud sh -c "gcloud app deploy --project my-project" he is running gcloud commands inside container. (I didn't find any similar tutorial/documentation where it's done like this ) Is this common practice to deploy from container? Here is an other example of deploying multiple apps, but does not involve docker-compose. medium url 2. Nginx vs gunicorn In the same London app developer tutorial and google documentation on deployment app.yaml entrypoint is … -
Why is djangorest returning blank brackets on simple get request
I am trying to return a list view of a database records. In testing my database has three records. When my view function is called it returns 3 empty curly brackets instead of the items it should. What is wrong here? The serializer, url and included below. I am not running any special settings. #view @api_view(['GET']) def getTheWashers(request): if request.method == "GET": washer = DishDoer.objects.all() washer_serializer = DishDoerSerializer(washer, many=True) return Response(washer_serializer.data)``` #seriaizer class DishDoerSerializer(serializers.Serializer): class Meta: model = DishDoer fields = "__all__" #url urlpatterns = [ path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls')), path('api/washers', getTheWashers), ] -
I need the text in the description of the news on my site to be formatted
How to make my text in the news, as I add to my site, be formatted using CharField and TextField, the text is displayed as one line without paragraphs, etc. This is the type of class responsible for adding news: `class News(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE) title=models.CharField(max_length=300) image=models.ImageField(upload_to='Imgs') detail=models.TextField() add_time=models.DateTimeField(auto_now_add=True)` -
Django setting env variables: how and which types to use on Docker and in production
When defining the variables in settings.py in Django, I read the variables either from a local config.cfg file or from the .env for Docker and production (using conditional statements to determine which is which). I am still not sure what is the best practice to set, read, and convert the variables accordingly for local, Docker (development), and production. I read for Docker (or production) from the .env using os.getenv(SOMEVAR). And I read the local variables from a config.cfg file using configparser: import configparser cfg = configparser.ConfigParser() cfg.read('/full/path/to/config.cfg')) First example: To set DEBUG True or False for Docker (development) or production, I use the conversion bool() # settings.py DEBUG = bool(os.environ.get("DEBUG", default=0)) where the .env in Docker defines DEBUG with 1, while in production is not defined, so that it defaults to False: DEBUG=1 Second example: I use a flag to set which email backend (console or SMTP) to use on local. And in this case I use the conversion int(): # settings.py USE_SMTP = int(cfg.get('main', 'USE_SMTP')) which in the config.cfg is defined as [main] ... USE_SMTP=0 Note that if I used bool() instead of int(), it would interpret the string '0' as True. Wrap-up: All of this works fine but … -
Nginx does not see Django
I'm trying to create nginx+gunicorn+django in docker but after i added nginx i doesnt get connection to my django Everything i get is nginx start page Can someone help me with that? docker-compose.yml version: '3.8' services: django: restart: always build: . command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && gunicorn --bind 0.0.0.0:8000 Qlubok.wsgi" volumes: - .:/qlubok logging: options: max-size: "10m" max-file: "3" expose: - 8000 env_file: - Qlubok/.env nginx: build: ./nginx ports: - "80:80" depends_on: - django nginx directory: DockerFile FROM nginx COPY nginx.conf /nginx/conf.d nginx.conf upstream qlubok_web { # Список бэкэнд серверов для проксирования server django:8000; } server { listen 80; # Параметры проксирования location / { # Если будет открыта корневая страница # все запросу пойдут к одному из серверов # в upstream django_proj proxy_pass http://qlubok_web; # Устанавливаем заголовки proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; # Отключаем перенаправление proxy_redirect off; } } my project structure: qlubok nginx Dockerfile nginx.conf Qlubok wsgi.py docker-compose.prod.yml DockerFile -
Squareup error in production (AWS EC2): TypeError: window.Square.payments is not a function
I've implemented the square payment just like the documentation indicated and I'm getting an error when loading the page and the card section does not come up. It's a Django project, hosted in AWS EC2. We do use cloudflare but I've disabled it and it still doesn't work. Works perfectly in localhost. Uncaught (in promise) TypeError: window.Square.payments is not a function This is my implementation <script type="text/javascript" src="https://web.squarecdn.com/v1/square.js"></script> <!-- Square payment scripts --> <script> const appId = "{{APPID}}"; const locationId = "{{LOCATIONID}}"; document.addEventListener('DOMContentLoaded', async function () { if (!window.Square) { throw new Error('Square.js failed to load properly'); } const payments = window.Square.payments(appId, locationId); // This is where the error is thrown ... }