Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django AutoSlug in Custom Form
I am working on a project and using the django-autoslug package to auto generate slugs for me. The package does its job perfectly well and I like it. So far, I can edit slugs from the admin panel when I added editable=True which works well from the admin panel. Now I want a working system where users can easily edit there slug from an UpdateForm in the UpdateView. I tried the official docs but I think it is limited to the admin panel and no support for the regular custom forms. Is there any better solution that can solve this for me? A solution that can auto generate forms, and also allow my users update their slug uniquely. I'll be very grateful if I get a solution on this. Warm Regards. slug = AutoSlugField(populate_from='name', unique=True, editable=True) -
Unable to make websocket connection in django
I am trying to make a websocket connection I am using the django's channels API. For some reason the handshaking is not taking place. Maybe it has something to do with the url? This is my main routing.py file from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket':AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) This is my chat app routing.py from django.urls import re_path,path # from django.conf.urls import url from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/room/(?P<room_name>\w+)/(?P<username>\w+)/$',consumers.ChatRoomConsumer.as_asgi()), ] This is my chat app consumers.py file # import pytest from accounts.models import Account from .models import ChatRoom, Message from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async import string import random # from asgiref.sync import sync_to_async class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name= 'chat_%s'%self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self,close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] room_name = text_data_json['room_name'] # print("[RECIEVED] "+room_name) print("[receiving....]"+message) await self.channel_layer.group_send( self.room_group_name, { 'type':'chatroom_message', 'message':message, 'username':username, 'room_name':room_name, } ) async def chatroom_message(self,event): message = event['message'] username = event['username'] room_name = event['room_name'] print("[SENDING....]"+message) room_obj = ChatRoom.objects.get(room_name=room_name) sender = Account.objects.get(username=username) await self.save_message(message=message,sender=sender,room_name=room_obj) await self.send(text_data=json.dumps({ 'message':message, 'username':username, … -
This is a django project . I am trying to fetch carousel image from database but it's ,only one image showing and slider not changing
00 I am trying to make a carousel slider. The picture comes from the database and is then rendered on the frontend slider. But the picture is rendering but it is creating a new slider and when I change to the next slide then it shows the same picture. What to do?? I am trying to make a carousel slider. The picture comes from the database and is then rendered on the frontend slider. But the picture is rendering but it is creating a new slider and when I change to the next slide then it shows the same picture. What to do?? my Url.py from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), ] views.py from django.shortcuts import render from .models import Products, About, Slider, Team # Create your views here. def home(request): slider = Slider.objects.all() return render(request, 'index.html', {'slider':slider}) index.html <!-- slider --> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> **{% for s in slider %} <div class="carousel-item active"> <img src="{{ s.image.url }}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5 class="fw-bolder fs-2">{{ s.Title }}</h5> <p class="fw-bolder … -
Remove option with certain text from dropdown menu
In my Django app (using {% load crispy_forms_tags %}) I have a following dropdown menu: <div id="div_id_report_division" class="form-group"> <label for="id_report_division" class=" requiredField">Test<span class="asteriskField"></span</label> <div class=""> <select name="report_division" class="select form-control" required="" id="id_report_division"> <option value="" selected="">---------</option> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> <option value="4">D</option> <option value="5">E</option> </select> </div> </div> I wish to remove option number 5 on page load. My Javascript on post.html with everything is: <script type="text/javascript"> function on_load(){ /* option 1.: document.querySelector('id_report_division option[value=5]').remove(); option 2.: var x = document.getElementById('id_report_division'); x.remove(5); option 3.: document.querySelector('#id_report_division option[value=5]').remove(); const first = document.querySelector("[id='id_report_division']"); */ document.querySelector("[id='id_report_division' option[value=5]]").remove(); } on_load(); </script> How can I easly remove this option? It would be better if I could remove option where text is E, in case that value changes. But there will always be only one text 'E', no need to itterate. -
how to solve Direct assignment to the forward side of a many-to-many set is prohibited error?
In my code cart is a model class where products are ForeignKey and in OrderItem model class where cart is ManyToManyField. When I want to save the OrderItemForm the above error occurs. models.py class OrderItem(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) cart = models.ManyToManyField(Cart, blank=True) name = models.CharField(max_length=200) district = models.ForeignKey(District, on_delete=models.CASCADE) city = models.CharField(max_length=200) postal_code = models.SmallIntegerField() area = models.TextField() phone = models.CharField(max_length=12) status = models.CharField(max_length=20, choices=STATUS_CHOICE, default="accepted",blank=True, null=True) email = models.EmailField() def __str__(self): return self.user.email Views.py def checkout(request): context={} subtotal =0 forms = OrderItemForm() context['forms'] = forms if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user).order_by('-id') for product in cart: subtotal += product.total_cost context['subtotal'] = subtotal customer = Customer.objects.get(user=user) if request.POST: form = OrderItemForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] district = form.cleaned_data['district'] city = form.cleaned_data['city'] postal_code = form.cleaned_data['postal_code'] area = form.cleaned_data['area'] phone = form.cleaned_data['phone'] email = form.cleaned_data['email'] for c in cart: instance = OrderItem(user=user, cart=cart, customer=customer, name=name, district=district, city=city, postal_code=postal_code, area=area, phone=phone, email=email).save() # instance.cart_for_help.add(cart) c.delete() else: messages.warning(request, form.error) return render(request, 'checkout.html', context) -
ModuleNotFoundError: No module named 'django' the commands pip install django doesn't working
The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ACER\Dropbox\Мой ПК (LAPTOP-CEPJ3MP0)\Desktop\Platform\manage.py", line 21, in <module> main() File "C:\Users\ACER\Dropbox\Мой ПК (LAPTOP-CEPJ3MP0)\Desktop\Platform\manage.py", line 12, in main raise ImportError( 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? Python 3.9.9 pip 21.2.4 C:\Users\ACER\AppData\Local\Programs\Python\Python39\python39.zip C:\Users\ACER\AppData\Local\Programs\Python\Python39\DLLs C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib C:\Users\ACER\AppData\Local\Programs\Python\Python39 C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\site-packages the commands pip install django and pip install django==0 do not working WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861177880>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861177610>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000208611776D0>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861177190>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861186190>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ ERROR: Could not find a … -
add a column under a condition in django
This is my model class User_quiz_logs(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False) user_quiz_id = models.AutoField(primary_key=True) response = models.CharField('response ', max_length=300, null=False) points = models.IntegerField('points', null=True) state_quiz = models.BooleanField('state', default=False) tiene un atributo puntos que quiero sumar si corresponde a un mismo persona Example 1 A 1 true 141 2 A 1 true 141 3 A 1 true 141 4 B 5 true 165 5 C 1 true 165 The person with id 141 the total sum of his points would be 3 and id 165 would be 6 total points. -
How to show only the value as text without reflecting the series on the stacked bar chart (apexchart)
I'm creating a stacked bar chart using apexchart in django. There are 5 data series, and the number of ongoing series is significantly larger than the data of other series(data type=digit), so when viewed as a stacked bar graph, the data of series except ongoing does not look thin. So, I want to output only the data value as "ongoing: value" above each bar without reflecting the ongoing series on the chart. There are very few cases like mine. I've been looking for a workaround for days, but I can't get it to work. [dashboard.html] <script> var options3 = { series: [ { name: 'I', data: {{ I | safe }} }, { name: 'S', data: {{ S | safe }} }, { name: 'P', data: {{ P | safe }} }, { name: 'E', data: {{ E | safe }} }, { name: 'ongoing', data: {{ ongoing | safe }} }, ], chart: { type: 'bar', height: 550, stacked: true, }, plotOptions: { bar: { dataLabels: { position: 'center', }, } }, dataLabels: { style: { fontSize: '10px', colors: ["#304758"] } }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'I-S-P-E chart', offsetY: 0, align: 'center', }, … -
Modified Output Data in to_representation method in django drf
can I return a list in the to_representation method in Django Rest Framework I need to modify the output in the serializer here is a recent output { "id": 1, "display_sequence": 2 } I need to modify the recent output to [ { "id": 1 "display_sequence": 2 }, { "id" : 2 "display_sequence": 1 } ] so the second data I got from the query filter based on the container id and target_container_id instance = Container.objects.filter(id__in=[self.container_id, self.target_container_id]) if I return to serializer I got this error Got AttributeError when attempting to get a value for field `display_sequence` on serializer `ContainerSequenceSwapSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `list` instance. Original exception text was: 'list' object has no attribute 'display_sequence'. how to I can return yo expected output? here are my views Views class ContainerViewSet(viewsets.ModelViewSet): """Container ViewSet for CRUD operations.""" queryset = Container.objects.all() def get_serializer_class(self): return ContainerSerializerV1 @action(methods=["patch"], detail=True, url_path="swap-sequence") def swap_sequence(self, request, pk): # serializer = ContainerSequenceSwapSerializer(data=request.data) container = self.get_object() serializer = ContainerSequenceSwapSerializer(container, data=request.data, context={'container': container}) if serializer.is_valid(raise_exception=True): # display data here content = serializer.data return Response(data=content, status=status.HTTP_200_OK) Serializer class ContainerSequenceSwapSerializer(serializers.ModelSerializer): """Serializer for Container sequence swap detail action.""" display_sequence = serializers.IntegerField() … -
Django cannot set domain name
I want to set domain name from cloudflare to django. I set settings.py like this. ALLOWED_HOSTS = ["10.x.x.x","20.x.x.x","myweb.com"] which 10.x.x.x is private ip address and 20.x.x.x is public ip address. The public ip is in Firewall NAT. I run Django server by use command python manage.py runserver myweb.com:8000 It show error like this. Error: [Errno 11001] getaddrinfo failed If I run with public ip like this command. python manage.py runserver 20.x.x.x:8000 It show error like this. Error: That IP address can't be assigned to. If I run with private ip it have no error. python manage.py runserver 10.x.x.x:8000 I set domain in cloudflare myweb.com to public ip 20.x.x.x. when open http://myweb.com:8000 it not found my website. How to set domian for Django? -
Query working in development but not in production Django
I have a query which is something like that: log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft)) log_entry_dual = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft) & Q(solo_flight=False)) and the view part which is: start_date = request.GET.get('start_date') if not start_date: start_date = dt.now().date() end_date = request.GET.get('end_date') if not end_date: end_date = dt.now().date() student = request.GET.get('student') if not student: student = '' instructor = request.GET.get('instructor') if not instructor: instructor = '' aircraft = request.GET.get('aircraft') if not aircraft: aircraft = '' Now, the weird part is that this query and view works perfectly in development environment (it filters the results based on my input, so an empty field shows all the data based on the other filters) but in production (I am on heroku) doesn't work. I mean, it works ONLY if I choose ALL the fields of the query and I don't leave any blank input. I have postgresql in both development and production. Any clue about what I am doing wrong? -
Possible to filter a queryset by its ForeignKey related_name objects?
I have a simple model: class Object(models.Model): name = CharField() root = ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL) I create a few objects: parent1 = Object.create(name="parent1") o1 = Object.create(name="1", root=parent1") parent1.object_set.all() # Returns queryset with o1 Is it possible to filter a queryset by its ForeignKey's related_name objects (i.e. object_set)? Something like: Object.objects.filter(object_set__name="1") # To return parent1 I get the following error: Cannot resolve keyword 'object_set' into field. I understand I could do Object.object.get(name="1").root but that results in additional queries which could really add up in my specific use case. -
Mac OS python django commands not working
I am getting blank output for all commands like runserver, migrate, makemigrations. Unable to find anything on google. -
how can i use uwsgi listen 80 port directly while deploying the django?
I am learning django, and now i have some trouble here. django cant receive the http packet but uwsgi packet from uwsgi server when i write the configure file like this, it works. [uwsgi] http = xxx.xxx.xxx.xxx:9999 chdir = /home/ZoroGH/code/django/mysite1 wsgi-file = mysite1/wsgi.py process=4 threads=2 pidfile=uwsgi.pid daemonize=uwsgi.log master=true i can visit the IP:9999. however, i cant change the port to 80, the log file says Permission Denied. then i enter sudo -i . in this mode ,the bash can't konw the uwsgi command.so i am here looking for help. how can i use uwsgi listen 80 port directly? i have made some search that some solutions are to use the nginx to pass the http to uwsgi service, but now i just want to only use the uwsgi to test my site. can it work? i looked the document of uwsgi, it says never to use root mode to execute the uwsgi service, but to use the uid & gid ? sadly, i konw nothing about the uid & gid. help me please -
Can I separate the model file into multiple files in Django? [duplicate]
I am new to Django, as I understand that the model file contains all model classes that are related to the component. But over time when the project becomes more complex, the model file is too huge and not readable, like this: class A(models.Model): title = models.CharField(max_length=255) class F(models.Model): title = models.CharField(max_length=255) class B(models.Model): title = models.CharField(max_length=255) class C(models.Model): title = models.CharField(max_length=255) class D(models.Model): title = models.CharField(max_length=255) class E(models.Model): title = models.CharField(max_length=255) ... Can I divide these classes into multiple files? like: File1 class A(models.Model): title = models.CharField(max_length=255) class F(models.Model): title = models.CharField(max_length=255) class B(models.Model): title = models.CharField(max_length=255) File2 class C(models.Model): title = models.CharField(max_length=255) class D(models.Model): title = models.CharField(max_length=255) class E(models.Model): title = models.CharField(max_length=255) Same question for views and serializers files. -
How to run a single unit test in Django
I run my tests with command "python3 manage.py test" it works fine, but it run all tests. When I try to run test by pushing a button "Run Test"(green triangle) there is an error: Error ImportError: Failed to import test module: app_shop Traceback (most recent call last): File "/usr/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named 'djcaching.app_shop' How can I solve this problem? My structure: djcaching app_shop tests app_users tests djcaching settings -
Template won't render each field in MultiValueField
In attempting to construct a subclass of MultiValueField called TagField, I'm not sure how to go about rendering each widget of the form field. There are suppose to be 4 x TextInput elements. I tried {{ field }} in the template initially, but it only renders the first TextInput widget. When that didn't render all four inputs, I tried {% for input in field %}, and that still only renders the first input element. What else must be done to get all four input elmenets rendered in the template? class TagField(MultiValueField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.require_all_fields = False self.help_text = kwargs["help_text"] for i in range(4): field = CharField(**{ "min_length": 1, "max_length": 25, "widget": TextInput( attrs={"class": "question_input_field"} ), "validators":[ RegexValidator("[<>`':;,.\"]", inverse_match=True) ] }) if i == 0: field.attrs.update({ 'required': True, "error_messages": { 'incomplete': "Provide at least 1 tag for your question" } }) else: field.required = False self.fields.append(field) def compress(self, data_list): data_list = set([tag.lower().strip() for tag in data_list]) return data_list -
django cant connect to tablespace
I want to make a website with the help of which it will be possible to change, watch, add entries to an already made database. I chose django for this. Previously i successfully connected to this tablespace Error application: django.db.utils.ProgrammingError: ERROR: tablespace "AAA" does not exist Frist models.py class svod_lic(models.Model): bot=models.CharField(max_length=255) def __str__(self): return {self.bot} class Meta: db_table='prim' db_tablespace="AAA" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'AAA': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'AAA', 'USER': '****', 'PASSWORD': '****', 'HOST': '192.168.0.30', 'PORT': '5432', } } Second models.py with error class ksg_npp(models.Model): id=models.IntegerField(), name=models.CharField(max_length=1000), c_prof=models.IntegerField(), smj_prof=ArrayField( models.IntegerField() ) KSG=models.CharField(max_length=1000) class Meta: db_tablespace = "AAA" db_table = 'ksg_npp' honeslty i dnot even know why it`s happening pls help i am desperate -
Any benefit breaking down fields into their own tables?
These are my models: class Organism(models.Model): genbank = models.CharField(max_length = 10, primary_key=True, unique=True) genus = models.CharField(max_length = 50) species = models.CharField(max_length = 50) strain = models.CharField(max_length = 50) organism_sequence = models.TextField() created_at = models.DateTimeField(auto_now_add = True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET_NULL, null=True) class Motif(models.Model): organism = models.ForeignKey( 'Organism', on_delete = models.CASCADE, related_name= "motifs", ) region_name = models.CharField(max_length = 15, choices = MOTIF_CHOICES) motif_sequence = models.CharField(max_length = 600) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET_NULL, null=True, ) created_at = models.DateTimeField(auto_now_add = True) It's basically a library. Each Organism has motifs as child objects. Would I benefit from making Genus, Strain and Species their own table? The reason I ask is because I saw something similar in an MDN tutorial of a library where language and genre were broken down into their own tables. If I were to follow the same logic for my project, I would break down the Genus, Species and Strain fields into their own tables. Does this help later with filtering or something like that? Thanks -
Can I use the same backend of a website to build a mobile application?
I am developing a website using Python (Django) and JavaScript to back-end. In the future I am thinking of using this same backend to build a mobile application. I would like to know what technologies I can apply to use the backend of my website to make a mobile application. -
Templates only displaying related objects
I am only able to view the related fields of the model objects in my templates. I was trying my hands on having templates in the root directory and had thought that was the issue, but the challenge still persists when I move my templates directory into apps folder Here's a sample of an object I am trying to access in my templates class Apartment(models.Model): rent = models.PositiveSmallIntegerField() address = models.ForeignKey('Address', on_delete=models.CASCADE) occupied = models.BooleanField() ... settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', '../../lib/site-packages/django/contrib/admin/templates' ], 'APP_DIRS': False, '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', 'django.template.context_processors.media', ], }, }, ] views.py class ApartmentDetailView(DetailView): model = Apartment context_object_name = 'apartment' sample template: Apartment-detail.html {% extends '../base.html' %} {% block title %} {{ apartment.address }} {% endblock %} {% block content %} <div> {{ apartment.address }} </div> <section> {{ apartment.address }} <p><em>Number of rent</em> : {{ apartment.rent }}</p> <p><em>Number of occupied</em> : {{ apartment.occupied }}</p> ... </section> {% endblock %} for the template above, I am able to see {{apartment.address}} but neither {{apartment.rent}} nor {{apartment.occupied}} I checked the page source to be double sure I am not making any mistakes with my templating and have tried without success to replicate … -
How do Django migrations works with updated code?
I'm currently changing a field on the model for which I want to add an intermideary model. For example, I have a Game model which I get from a 3rd party API and I keep their ID on my model as well. However I would want to extend this to get the data from other APIs as well. Current State: class Game(models.Model) api_id = models.IntegerField() Updated State: class Provider(models.Model): api_id = models.IntegerField() class Game(models.Model) provider = models.OneToOne... @property def api_id(self): return ... However, everywhere in my code I reference api_id on my Game model so I've also added a property that retrieves it from the Provider model. I've created the necessay migration and the migration command, however, my question is: Will the migration take the field api_id from the Game model even though it won't be present there once or would it take the newest property I've created? -
How do I retrieve data from a Django DB before sending off Celery task to remote worker?
I have a celery shared_task that is scheduled to run at certain intervals. Every time this task is run, it needs to first retrieve data from the Django DB in order to complete the calculation. This task may or may not be sent to a celery worker that is on a separate machine, so in the celery task I can't make any queries to a local celery database. So far I have tried using signals to accomplish it, since I know that functions with the wrapper @before_task_publish are executed before the task is even published in the message queue. However, I don't know how I can actually get the data to the task. @shared_task def run_computation(data): perform_computation(data) @before_task_publish.connect def receiver_before_task_publish(sender=None, headers=None, body=None, **kwargs): data = create_data() # How do I get the data to the task from here? Is this the right way to approach this in the first place? Or would I be better off making an API route that the celery task can get to retrieve the data? -
Ngrok Falied to complete Tunnel connection
I am working on my first Django project. Trying to connect to the auto-grader for my course through ngrok.I ran python manage.py runserver. I can see the website at http://127.0.0.1/8000 and it is working. I tried the command ngrok http 80 and got a forwarding URL. When I try to see the Http://xxxxxxxngrok.io/127.0.0.1/8000 I get the following error: "The connection to http://444e-2600-1700-5egb-70c0-c843-879c-12ad-2b03.ngrok.io was successfully tunneled to your ngrok client, but the client failed to establish a connection to the local address localhost:80. Make sure that a web service is running on localhost:80 and that it is a valid address. The error encountered was: dial tcp [::1]:80: connectex: No connection could be made because the target machine actively refused it. I typed netstat after running the runserver command. It shows 127.0.0.1/8000 with a state "listening" How can I resolve this?" -
Firebase private key set as a config variable in Heroku not recognised - Django app
this is driving me mad. I have .env set up in my Django project and my firebase private key in the .env file. It works fine locally but when I move it to Heroku, set the config variable it does not recognise the key start -----BEGIN PRIVATE KEY----- I have tried loads of different solutions suggested on here, adding "", stringify the os.env variable but nothing works. Im bored now does anyone have an answer?