Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store and serve static images using Django, Pythonanywhere, CDN and cloud storage
I'm quite new to web development, just a self-taught enthusiast, so be kind :) Right now I'm trying to deploy my website (built with Django) on Pythonanywhere. Following all advice on static files and it actually works. So basics are done. But images load painfully slow. I know there is some size and weight optimisation to do, but I also heard that the best way to serve large amount of images is to store them separately from the code (in Amazon S3, Google Cloud Storage) and serve through CDN. I have also found a nice service called IMGIX to always serve the most appropriate version of an image. Now the hard question: how does it work together? OK, I can upload all images to the bucket, point CDN to it too. But then how do I go about 'collectstatic' in Django? How do I keep those images linked to the models? Do I resolve it by pointing STATIC_DIR and STATIC_ROOT to that bucket? My mind is failing me here and googling did not help either. Any help would be highly appreciated. -
AWS beanstalk + Django: 502 Bad Gateway - ModuleNotFoundError: No module named 'application'
I'm trying to deploy Django project to Elastic Beanstalk. I'm following their guide: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But after eb open all pages return "502 Bad Gateway". My AWS admin shows django environment as "Degraded". Please see the screenshot: My logs, seems like something with "ModuleNotFoundError: No module named 'application'": ---------------------------------------- /var/log/web.stdout.log ---------------------------------------- Jan 27 19:30:21 ip-172-31-32-137 web: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Jan 27 19:30:21 ip-172-31-32-137 web: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Jan 27 19:30:21 ip-172-31-32-137 web: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked Jan 27 19:30:21 ip-172-31-32-137 web: ModuleNotFoundError: No module named 'application' Jan 27 19:30:21 ip-172-31-32-137 web: [2021-01-27 19:30:21 +0000] [3483] [INFO] Worker exiting (pid: 3483) Jan 27 19:30:21 ip-172-31-32-137 web: [2021-01-27 19:30:21 +0000] [3476] [INFO] Shutting down: Master Jan 27 19:30:21 ip-172-31-32-137 web: [2021-01-27 19:30:21 +0000] [3476] [INFO] Reason: Worker failed to boot. Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3488] [INFO] Starting gunicorn 20.0.4 Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3488] [INFO] Listening at: http://127.0.0.1:8000 (3488) Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3488] [INFO] Using worker: threads Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3495] [INFO] Booting worker with pid: 3495 Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 … -
Cannot override templates found in admin/auth and admin/widgets in Django
Context I want to override the following django templates: django/contrib/admin/templates/admin/widgets/clearable_file_input.html django/contrib/admin/templates/admin/auth/user/change_password.html With these custom templates: <project_root>/templates/admin/widgets/clearable_file_input.html <project_root>/templates/admin/auth/user/change_password.html My TEMPLATES settings are configured as followed: TEMPLATES = [ { "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", ], }, }, ] Problem While I have managed to successfully override a lot of other templates that exist in the django/contrib/admin/templates/admin/ path, I cannot seem to be able to override templates that exist in the paths mentioned above. Regarding the widgets, I also tried the instructions found in the docs here to no avail. -
How to convert ReturnList to simple array with objects or modify this list?
I am using serializers.ModelSerializer in Django to get my objects from database. participants = ParticipantSerializer(Participant.objects.all(), many=True) Now I have a contidtion that if elements in returned list is not equals to some constant then I should fill this list with null values. participants = ParticipantSerializer(Participant.objects.all(), many=True) placeLeft = tournament.max_participants - len(participants.data) if(placeLeft > 0): for _ in range(0, placeLeft): participants.append(None) But I've got AttributeError: 'ListSerializer' object has no attribute 'append'. I could not find any source which would help me. Could I ask you for help? How could -
How to deploy a django project to google cloud with celery workers?
So i have a django project which I installed celery and heroku redis for it and I use google cloud for deployment. Everything works fine at local but i need to run my celery workers on website 24/7. I searched for supervisor and installed it too. I start supervisor from my command line. Celery workers runs since I ran supervisor. But there is a problem. I can not hold my pc open all the time. When I close, supervisor stops too. I did not figured out cloud tasks as well. Lastly, I read some infos about kubernetes and celery. Is it possible to use celery with kubernetes and how can i install kubernetes-celery django setup? -
Django Generate Random String Internally and Validate in Form POST Request
Let's say I have a form and want to add some extra security to it. <form method="POST" enctype="multipart/form-data"> ... <button name="delete" role="button">Delete</button> <button name="save" role="button" type="submit">Save</button> </form> I use class-based views. I add a random string to the context within get_context_data(): import random, string def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['random_string'] = ''.join(random.choices(string.ascii_letters + string.digits, k=20)) return context My form then is: <form method="POST" enctype="multipart/form-data"> ... <button name="delete" value="{{ random_string }}" role="button">Delete</button> <button name="save" role="button" type="submit">Save</button> </form> So what I want to do is: Generate a unique string internally and pass to template using context variable named random_string. When form is submitted, if request.POST has a 'delete' key, I want to validate that the value was generated internally from my system. request.POST would look something like this: <QueryDict: { 'csrfmiddlewaretoken': ['gqYBmmeba8Y...EQFVbzpXyPU0TXF'], 'user': ['19'], ... 'delete': ['h3teSs4bLizQF69EvtAU'] }> I'm hoping someone experienced can tell me either: I'm going about this all wrong, here's how to do it, or here's what I should do instead, or there's no need because xyz. My overall goal is just a sanity check to know that the generated random string was actually generated from my system and the user isn't trying to delete something in some … -
What's the problem with sharing job stores in APScheduler?
I did quite get the problem that arises by sharing a job store across multiple schedulers in APScheduler. The official documentation mentions Job stores must never be shared between schedulers but doesn't discuss the problems related to that, Can someone please explain it? and also if I deploy a Django application containing APScheduler in production, will multiple job stores be created for each worker process? -
Django: How to display a pdf file in a new tab?
Most of the posts showing how to open a pdf file in a new tab are 3 years old. What is the best way in Django to open a pdf file uploaded to a model? invoice.py class Invoice(models.Model): file = models.FileField(upload_to='estimates/', blank =True) name = models.CharField(max_length=250, blank =True) def __str__(self): return self.name views.py def view_invoice(request, invoice_id): invoice = get_object_or_404(Invoice, pk=invoice_id) return render(request, 'index_invoice.html', {'invoice': invoice}) index_invoice.html <a href=""><i class="fas fa-eye"></i>&nbsp;</a> Many Thanks -
How to get exception in custom handler500?
I'm developing my own template for errors pages, but the handler500 don't get the exception parameter, and I can't know what is the cause of error. How can I do this? My custom template already is working, but I need the information about the exception cause. My handler500: def error_500(request): template_name = "error_500.html" error_code = "500" url = request.build_absolute_uri() username = request.user.username useruuid = request.user.uuid date = datetime.datetime.now() errorObject = Errors(error_code=error_code, url=url, username=username, useruuid=useruuid, date=date) errorObject.save() errorUUID = errorObject.uuid context = { "errorUUID": errorUUID } return render(request, template_name, context) -
AWS EB Django ModuleNotFoundError: No module named 'my_project'
I am trying to deploy a django webapp into AWS EB. The app works fine in the localhost but when I try to deploy it, I keep getting ModuleNotFoundError: No module named 'my_project'. File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'my_project' django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application packages: yum: mod_ssl: [] wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() My local directory looks like this: my_project ├── .ebextensions ├── myapp │ ├── settings.py │ └── wsgi.py ├── manage.py ├── requirement.txt . . . I am using Amazon Linux 2 with the Python environment. How can I make it work? -
send django ModelForm through JsonResponse
I'm wondring how to send a django ModelForm through JsonResponse(if i'ts possible). I have a form as class RecordForm(forms.ModelForm): class Meta: model = Records fields = ("title", "file", "doctor") ... in views.py ... return JsonResponse({"form": RecordForm(instace=x)}) ... I want to user form.as_p based on return data after the response returned the form with instance of the object. Thanks in advance gyus! -
How to programmatically set the model when using Django CreateView?
I am trying to programmatically set the model for a Django class-based view that inherits from CreateView and displays a form for creating a 'member' object. My problem is that my template is not displaying the form itself. Note that I override the 'get' method to determine what model the view should use. The template page renders and I see the submit button but when I view the page's source code, the form is missing. Here's my code: # urls.py path('profile/create/', views.ProfileCreate.as_view(), name='profile-create'), # views.py class ProfileCreate(CreateView): model = None template_name = None def get(self, request, *args, **kwargs): member = Member.objects.get(user=request.user) if member.is_couple: self.model = ProfileCouple self.template_name = 'account/profile_couple_create.html' self.fields = ['person1_name', 'person2_name', 'person1_dob', 'person2_dob'] else: self.model = ProfileSingle self.template_name = 'account/profile_single_create.html' self.fields = ['person1_name', 'person1_dob'] context = {} return render(request, self.template_name, context) # models.py class ProfileSingle(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) person1_name = models.CharField(_("Name"), max_length=50) person1_dob = models.DateField() def __str__(self): return self.user.username class ProfileCouple(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) person1_name = models.CharField(_("Name 1"), max_length=50) person1_dob = models.DateField() person2_name = models.CharField(_("Name 2"), max_length=50) person2_dob = models.DateField() def __str__(self): return self.user.username # forms.py class CreateSingleProfileForm(forms.ModelForm): class Meta: model = ProfileSingle fields = ('user', 'person1_name', 'person1_dob') labels = {'user': _('Username'), 'person1_name': _( … -
How to connect local React app to local REST API for production
I have a system where I want several tablets to connect to a local server on a local network. It would be nice to use react native on the tablets and connect to a local Django REST API on an apache server. I don't want this system touching the web whatsoever (totally offline). Is there a way to do this given self-signed SSL certs are supposedly development only? This networking part of it is new to me. -
iframe pdf preview at change event
$(document).ready(function(){ $("#id_quotationFile").change(function(){ url=$("#id_quotationFile").attr(value); $("#pdf-view").attr("src",url); }); }); Trying to load pdf file browsed in input field using above jquery code but not working <input type=file id="id_quotationFile"> <iframe src="" id="pdf-view" frameborder="0px" title="Preview"></iframe> How to preview pdf file in iframe. -
Django, OOP question to deal with EAV and complex attributes tables/models for diverse products
I have this model and I want to run select_related query for the category related product's attributes. class auction_product(models.Model): title = models.CharField(max_length=64) date_added = models.DateField(default=timezone.now) user = models.ManyToManyField(User, through='product_ownership', related_name='product_user') category = models.ForeignKey(Categories, on_delete=models.CASCADE) condition = models.CharField(max_length=5, choices=[('N', 'New'), ('U', 'Used')]) description = models.CharField(max_length=4096) product_bid = models.ManyToManyField(User, through='bid', related_name='product_bid') product_comment = models.ManyToManyField(User, through='comment') album = models.OneToOneField(ImageAlbum, related_name='product_model', blank=True, null=True, on_delete=models.CASCADE) class extra_vehicle_attributes(auction_product): product = models.OneToOneField('auction_product', primary_key=True, parent_link=True, on_delete=models.CASCADE, related_name="vehicle_attributes") make = models.CharField(max_length=128) model = models.CharField(max_length=128) year = models.IntegerField() mileage = models.IntegerField() class extra_pc_attributes(auction_product): product = models.OneToOneField('auction_product', primary_key=True, parent_link=True, on_delete=models.CASCADE, related_name="pc_attributes") processor = models.CharField(max_length=264) ram = models.FloatField() brand = models.CharField(max_length=64) motherboard = models.CharField(max_length=264) case = models.CharField(max_length=264) screen_size = models.FloatField() weight = models.FloatField() Now in the views.py for instance I am running this code below, but it is getting really tedious to write because each time I have to write .vehicle_attributes or pc_attributes or whatever attributes I may have and write it after the object in python code. Is there a way where I can get all the select_related mentioned fields properties without having to write like .vehicle_attributes for each object? I just want python to spit out all the possible fields auction_product may belong to its attributes foreign table without having … -
Uploading duplicated files with Django when reloading page
I'm trying to upload some files and I'm having problems with duplication. To uploading the file I do the following: views.py: from django.core.files.storage import FileSystemStorage def contView(request): if request.method == 'POST' and request.FILES.get('myfile'): myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save('uploads/'+myfile.name, myfile) uploaded_file_url = fs.url(filename) # Return template_name ='cont/mainCont.html' context = {} return render(request, template_name, context) Template: <form method="post" enctype="multipart/form-data">{% csrf_token %} <div class="input-group"> <input type="file" name="myfile" class="form-control"> <span class="input-group-btn"> <button class="btn btn-default" type="submit">Importar</button> </span> </div> </form> The upload works perfectly but when I refresh the page it upload the same file again. Why is this happening? I need to empty something? Thank you very much! -
Use Twitter API in Celery task - need to use access_key and access_secret from auth user
I have the following function in my views.py that will send me the authorised user's key tokens. I can then manually amend these tokens for my Twitter API function locally to run the program. def like(request): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = request.session['access_key_tw'] access_secret = request.session['access_secret_tw'] send_mail( 'Auth Codes', # subject 'access key - ' + os.environ['oaccess_key'] + '\n' + 'access_secret - ' + os.environ['oaccess_secret'], # message DEFAULT_FROM_EMAIL, # from email [DEFAULT_FROM_EMAIL], ) return render(request, "home.html") However having to do this manually isn't great and for security reasons I'd rather not have them emailed. I want to push the function to a celery task so that I don't need the sendmail() at all. My celery task would look like this after liking.delay() being called within like() - @app.task(bind=True) def liking(self): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) ** Rest of my code using the Twitter API ** I have tried setting the access_key and access_secret as environmental variables but they do not import to the celery.py. Is there any way that I'm missing that can enable this to work? -
How to pass the url from the datepicker to Chartjs URL
I need to pass the url from the datepicker to loadChart() var requestURL = 'http://127.0.0.1:8000/api/v1/rainfall/'; the date-picker have 2 urls. defaultUrl and url and everytime those urls been modified on the frontend. it automatically passes the url to the loadChart() url. How can I do it? Thanks! <script> (function rfChart(rainfall, amount, timestamp) { amount = loadChart().amount; timestamp = loadChart().timestamp; var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: timestamp, datasets: [{ label: 'Rainfall Graph', data: amount, lineTension: 0, backgroundColor: 'transparent', borderColor: '#c9c5c5', borderWidth: 2, pointRadius: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: false } }] }, legend: { display: false } } }) }()); </script> <script> var myVar = setInterval(loadChart, 60000); // updates chart every one minute function loadChart() { var rainfall, amount = [], timestamp = []; var requestURL = 'http://127.0.0.1:8000/api/v1/rainfall/'; //URL of the JSON data var request = new XMLHttpRequest(); // create http request request.onreadystatechange = function() { if(request.readyState == 4 && request.status == 200) { rainfall = JSON.parse(request.responseText); for (var i=0; i<rainfall.length;i++) { amount.push(rainfall[i].amount); timestamp.push(rainfall[i].timestamp); } console.log('amount', amount); console.log('timestamp', timestamp); console.log('rainfall', rainfall); return rainfall,amount,timestamp; rfChart(amount,timestamp); } } request.open('GET', requestURL); request.send(); // send the request } loadChart() … -
How to save a model form with two Models in Django
There is a model Listaflor linked to Estados with another model named Flora2Estado, i made a form with ModelMultipleChoiceField. It saves successfully into Listaflor but nothing into the Flora2Estado, what can i do about this? forms.py class FloForm(forms.ModelForm): familia = forms.ModelChoiceField(queryset=Familia.objects.all().order_by('familia_nome').filter(aprovado=1)) Especie = forms.CharField(label="Nome da espécie*") estados = forms.ModelMultipleChoiceField(queryset=EstadosM.objects.all().order_by('nome_abbr')) class Meta: model = Listaflor ordering = ["estados",] fields = ['Especie','estados'] views.py def CreateFlo(request): form = FloForm() if request.method == 'POST': form = FloForm(request.POST) if form.is_valid(): Listaflor = form.save(commit=False) Flora2Estado = form.save(commit=False) Listaflor.save() Flora2Estado.save() return render(request,'accounts/enviar_flora.html') models.py class Flora2Estado(models.Model): estado = models.ForeignKey(EstadosM, models.CASCADE) especie = models.ForeignKey(Listaflor, models.CASCADE) flora2estado = models.AutoField(primary_key=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie'),) Any tips on helping me making a better post is welcome, have a good day! -
Run django and cron in docker-compose
I have two similar dockerfiles. They differ only in the entrypoint This is Dockerfile-cron FROM python:3.8 WORKDIR /src COPY requirements.txt ./ COPY requirements-dev.txt ./ RUN apt-get update -y RUN apt-get install libgl1-mesa-glx -y RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements-dev.txt CMD [ "chmod", "+x", "cron.sh" ] This is cron.sh #!/usr/bin/env bash * * * * * python manage.py check_subscriptions > /proc/1/fd/1 2>/proc/1/fd/2 I have cron service in docker-compose cron: build: dockerfile: deploy/Dockerfile-cron context: . volumes: - .:/src networks: - sortif-network When I up docker-compose I get error backend_cron_1 exited with code 0 sudo docker logs backend_cron_1 is empty. -
Django templates not loading without errors
I am trying to load my templates in Django but it does not load anything except the base.html and does not show any error as well. I have tried these solutions but did not see and changes: Templates not loading in Django Django Template not loading Django template doesn't load Here is my views: def all(request): lead_list = Lead.objects.all() print(lead_list) return render(request, "leads.html", {'leads': lead_list}) URLS: urlpatterns = [ path('leads/', views.leads, name="leads"), path('newlead/', views.newlead, name="newlead"), path('leads/<int:pk>', views.lead_details, name="lead-details"), path('leads/<int:pk>/update', views.lead_update, name="lead-update"), path('leads/<int:pk>/delete', views.lead_delete, name="lead-delete"), path('all/', views.all, name="all"), ] Here is the HTML: {% extends 'base.html' %} {% block content %} <h1>Hello World</h1> {% for lead in leads %} <div class="max-w-sm mx-auto bg-white dark:bg-gray-800 shadow-lg rounded-lg overflow-hidden"> <img class="w-full h-56 object-cover object-center" src="https://images.unsplash.com/photo-1517841905240-472988babdf9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" alt="avatar"> <div class="flex items-center px-6 py-3 bg-gray-900"> <svg class="h-6 w-6 fill-current text-white" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M17 21C15.8954 21 15 20.1046 15 19V15C15 13.8954 15.8954 13 17 13H19V12C19 8.13401 15.866 5 12 5C8.13401 5 5 8.13401 5 12V13H7C8.10457 13 9 13.8954 9 15V19C9 20.1046 8.10457 21 7 21H3V12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12V21H17ZM19 15H17V19H19V15ZM7 15H5V19H7V15Z"/> </svg> <h1 class="mx-3 text-white font-semibold text-lg">{{lead.status}}</h1> </div> <div class="py-4 px-6"> <h1 class="text-xl font-semibold … -
Django - Group by Count of Foreign Key
I have two models like so: models.py class Subscription(...): is_active = models.BooleanField(...) class Order(...): subscription = models.ForeignKey('Subscription', related_name='orders', ...) ... I want to know: How many subscriptions have x number of orders (i.e. 7 subscriptions with 1 order, 5 subscriptions with 2 orders, etc.) The average number of orders across all of my subscriptions (i.e. 2.2 orders) I can susccesfully annotate the number of orders to a subscription queryset, but I am having trouble grouping the queryset by like 'number_of_orders' from there: views.py from django.db.models import Count queryset = Subscription.objects.filter(is_active=True).annotate(number_of_orders=Count('orders') queryset = queryset.values('number_of_orders') I've tried: queryset = queryset.order_by('number_of_orders').aggregate(count=Sum('number_of_orders')) which doesn't group my subscriptions correctly, and: queryset = queryset.order_by('number_of_orders').annotate(count=Sum('number_of_orders')) which fails with this error: Cannot compute Count('number_of_orders'): 'number_of_orders' is an aggregate Ideally, I am looking for the result to be in a form that I can pass to a bar chart in chart.js, something like: data = [ {"subscriptions_with_1_order" : 5}, {"subscriptions_with_2_orders" : 3}, {"subscriptions_with_3_orders" : 3}, ... ] or more preferably (where x is the number of orders and y is the count of subscriptions with that many orders): data = [ {"x" : 1, "y" : 5}, {"x" : 2, "y" : 3}, {"x" : 3, "y" : 3}, … -
<a> tag not opening popup
{% extends "base.html" %} {% block spotify %} <ul class="navbar-nav"> <li class="nav-item"> <a href="#" id="login" onclick= "openSignInWindow" class="nav-link">Login</a> </li> </ul> </nav> <script> let windowObjectReference = null; let previousUrl = null; var url = "{% url 'login' %}"; const openSignInWindow = (url, name) => { window.removeEventListener('message', receiveMessage); const strWindowFeatures = 'toolbar=no, menubar=no, width=600, height=700, top=100, left=100'; if (windowObjectReference === null || windowObjectReference.closed) { windowObjectReference = window.open(url, name, strWindowFeatures); } else if (previousUrl !== url) { windowObjectReference = window.open(url, name, strWindowFeatures); windowObjectReference.focus(); } else { windowObjectReference.focus(); } // add the listener for receiving a message from the popup window.addEventListener('message', receiveMessage, false); // assign the previous URL previousUrl = url; }; login = document.getElementById(login); login.addEventListener(onclick, openSignInWindow(url , spotify)); </script> {% endblock %} Aim is to open the {% url 'login' } when the link is clicked but I do not know how to pass the javascript function arguments into the <a> onclick. How do I achieve this? Is there a better way to do this instead of using an <a>? -
docker React, django(gunicorn), nginx reverse proxy with https give Bad request 400 on accessing backend APIs
I have containerized application with following containers working together with docker-compose Nginx - reverse proxy React - frontend Django served using gunicorn - backend When using http all works well with frontend and backend. I used letsencrypt certbot to generate ssl certificates. On switching to https, fronend seems to work fine however none of backend apis are working. Any request to backend such as login generates 'Bad Request 400' response. I have tried following options but none worked. a. Switching Django to production and adding ALLOWED_HOSTS=['*'] or specific domain b. Adding upstream in nginx.conf c. disableHostCheck: true in webpack devServer. Following are my docker-compose and nginx.conf respectively docker-compose.yml services: reverse_proxy: image: nginx:1.17.10 volumes: - ./reverse_proxy/nginx.conf:/etc/nginx/nginx.conf - ./reverse_proxy/certbot-etc:/etc/letsencrypt - ./reverse_proxy/certbot-var:/var/lib/letsencrypt ports: - 80:80 - 443:443 depends_on: - webapp - frontend webapp: build : ./backend/ command: gunicorn --bind 0.0.0.0:8000 ai.wsgi:application expose: - 8000 volumes: - ./backend/:/app ports: - 8000:8000 frontend: build: ./frontend/ai-web/ command: npm run ai ports: - 3000:3000 nginx.conf worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 1024; } http { fastcgi_read_timeout 3000; proxy_read_timeout 3000; client_max_body_size 1000M; upstream django { server webapp:8000; } server { listen 80; server_name localhost 127.0.0.1; location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For … -
Replace views functions for view class in Django
I would like to replace my views functions for a class. I'm new in Django and I try to send service object from user function to metrics function but I can´t do that with < a href="{% url 'metrics' %}">Metrics</a> in home.html. I don't know how to call a class instead a function too my code: def user(request): username = request.POST.get('username') password = request.POST.get('password') service = Service() service.start(username=username, password=password) return render( request, 'home.html', { 'service': service, } ) def metrics(request, service): metrics = service.get_metrics() return render(request, 'metrics.html', { 'metrics', metrics } the code I would like or something like it: class User(object): def __init__( self ): super(User, self).__init__() self.usernme = '' self.password = '' self.service = '' def get_service(self, request): self.username = request.POST.get('username') self.password = request.POST.get('password') self.service = Service() self.service.start(username=self.username, password=self.password) return render( request, 'home.html', {} ) def metrics(self, request): metrics = self.service.get_metrics() return render( request, 'metrics.html', { 'metrics': metrics, } )