Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ConnectionAbortedError
So I am trying to solve api issue. I am making request to django backend using axios from my frontend application. They are running on seperate domains. My django app is running in a virtual environment. If I make a request using postman I will get my response no problem but if I make request using my front end application I get the following error. Traceback (most recent call last): File "c:\laragon\bin\python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\laragon\bin\python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\laragon\bin\python\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Thomas\.virtualenvs\qb_project-vSd1QFH0\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Thomas\.virtualenvs\qb_project-vSd1QFH0\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\laragon\bin\python\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine This is the axios method axios.get('http://mybackend/api/oauth') .then(response => { context.commit('CONNECTION', response) console.log(response) resolve(response) }).catch(error => { console.log(error) reject(error) }) and this is my method for returning my response urls.py urlpatterns = [ path('api/oauth', oauth, name='oauth') ] api.py @api_view(['GET']) def oauth(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT ) data = auth_client.get_authorization_url([Scopes.ACCOUNTING]) request.session['state'] = auth_client.state_token return Response(data) So for some reason the connection is being closed, before the … -
Unable to save my admin.py changes in my model
I am pretty new to django. I am trying to save my admin.py list_editable changes in my model. I am using 'def clean(self):' in my model for validationError and if there is no validation i need to save my changes. class DashBoard(models.Model): """Dashboard to be used to upload all my items""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length = 255, null = True) tranScription = models.CharField(max_length = 255, null = True) videoUrl = models.CharField(max_length = 255, null = True) audioUrl = models.CharField(max_length = 255, null = True) imageUrl = models.CharField(max_length = 255, null = True) foodQuality = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) ambience = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) cleanliness = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) mediaType = models.CharField(max_length = 255, default ='mp4') date = models.CharField(max_length = 255, default= datetime.today().strftime("%Y-%m-%d")) isUploaded = models.BooleanField(max_length = 255, default = False) def clean(self): if value < 0 or value > 1: raise ValidationError(u'%s is not between 0 and 1' % value) def __str__(self): return self.title -
How to loop through millions of Django model objects without getting an out of range or other error
I have millions of objects in a Postgres database and I need to send data from 200 of them at a time to an API, which will give me additional information (the API can only deal with up to 200 elements at a time). I've tried several strategies. The first strategy ended up with my script getting killed because it used too much memory. This attempt below worked better, but I got the following error: django.db.utils.DataError: bigint out of range. This error happened around when the "start" variable reached 42,000. What is a more efficient way to accomplish this task? Thank you. articles_to_process = Article.objects.all() # This will be in the millions dois = articles_to_process.values_list('doi', flat=True) # These are IDs of articles start = 0 end = 200 # The API to which I will send IDs can only return up to 200 records at a time. number_of_dois = dois.count() times_to_loop = (number_of_dois / 200) + 1 while times_to_loop > 0: times_to_loop = times_to_loop - 1 chunk = dois[start:end] doi_string = ', '.join(chunk) start = start + 200 end = end + 200 [DO API CALL, GET DATA FOR EACH ARTICLE, SAVE THAT DATA TO ARTICLE] -
Exception Type: NoReverseMatch - Django
after researching for hours I cannot get rid of this error, I hope someone can help me. Models: class Puja(models.Model): seller = models.OneToOneField(Seller, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True) title = models.CharField(max_length=100) video = models.FileField(blank=True) photo = models.ImageField(blank=True) published_date = models.DateTimeField("Published: ",default=timezone.now()) bidding_end = models.DateTimeField() starting_price = models.IntegerField(default=1) #slug = models.SlugField(null=True) def __str__(self): return str(self.title) #def get_absolute_url(self): # return reverse('bidding_list_detail', args=[str(self.id)]) #slug time def get_absolute_url(self): return reverse('bidding_list_detail',args={'id': self.id}) Views: class bidding_list(ListView): model = Puja template_name = 'bidding_templates/bidding_list.html' """return render(request= request, template_name='bidding_templates/bidding_list.html', context = {"Pujas": Puja.objects.all})""" class bidding_list_detail(DetailView): model = Puja template_name = 'bidding_templates/bidding_list_detail.html' urls: path('admin/', admin.site.urls), path("bidding_list/", bidding_list.as_view(), name="bidding_list"), path('<int:pk>', bidding_list_detail.as_view(), name='bidding_list_detail'), admin: class PujaAdmin(admin.ModelAdmin): list_display = ('seller','title','video','photo','published_date','bidding_end','starting_price') admin.site.register(Puja,PujaAdmin) template 1: {% extends 'header.html' %} {% block content %} <h1>Pujas</h1> {% for Puja in object_list %} <!--object_list--> <ul> <li><a href="{{ Puja.get_absolute_url }}"> {{ Puja.title }} </a></li> </ul> {% endfor %} {% endblock %} template 2: {% extends 'header.html' %} {% block content %} <div> <h2>{{ object.title }}</h2> <p>{{ object.seller }}</p> </div> {% endblock %} Note that, whenever I remove <a href="{{ Puja.get_absolute_url }}"> from the first template, the objects "puja" in the model get properly displayed on the template, but I cannot access them. They normally exist on the admin … -
Django/DRF - Serialize Queryset avoiding N+1 problem with SerializerMethodField
I am using this model configuration. class Project(models.Model): name = models.CharField(max_length=64) class Platform(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_platforms") is_deleted = models.BooleanField(default=False) Now, I am getting my queryset using this code. queryset = Project.objects.prefetch_related("project_platforms") I want to serialize this queryset using the following Serializer. class ProjectSerializer(serializers.ModelSerializer): platforms = serializers.SerializerMethodField("_platforms") class Meta: model = Project fields = ["id", "name", "platforms"] def _platforms(self, obj: Project) -> list: platforms = PlatformSerializer(obj.project_platforms.filter(is_deleted=False), many=True).data return platforms Now, even though I have used prefetch_related, when I call the serializer on my queryset, it still causes one query for each project in fetching the platforms for each project. I cannot use platforms = PlatformSerializer(read_only=True, many=True) since the PlatformSerializer is declared below ProjectSerializer. Is there any solution to this? Am I doing something wrong? -
How to preload a video in Django
This is an online experiment program in Django. In the playing page I got: Playing.html <video height="50%" autoplay id="video" {{video_muted|safe}}> <source src="{% static path %}" type="video/mp4"> </video> The videos are just 1-5MB, however, some users' Internet speed is so slow. Sometimes it takes them 2 minutes to load/download a video. Any method I can transfer the videos to users browser first and then in the playing.html, it gets the video from "cache in local browser" instead of the server directly. Thanks in advance. -
Checking in def clean to see if image field has been cleared
Within my def clean function, I've built a check to see if a user has an image, but no body, which is an invalid combination. forms.py def clean(self): cleaned_data = super(ServicesForm, self).clean() body = cleaned_data.get('body ') image = cleaned_data.get('image') if body != None and image == None : self.add_error('image', "You must provide an image if you want to save the post.") This works well upon the creation of the post. The error shows up if the user enters text in the body, but doesn't provide an image. However, if a user goes back to a post where both a body and image have been provided and clicks on 'clear' on the image widget, they are able to save the form with no error being thrown. Due to other reasons, I do not want to set image as a required field on this form. (There is other business logic that controls whether or not an image is required or not). How can I check in def clean() to see if the user has cleared the image? Thanks! -
How to disable loggin in pyppeteer
I'm using pyppeteer to take screenshots of images to a make a pdf but pyppeteer auto logs everything I take a screenshot at and because of server limitations and the logs is written to a file the logs are crashing my server. Is there any way to completely disable loggin? I tried this already: 'logLevel': logging.NOTSET, 'env': {'DEBUG': 'puppeteer:*,-not_this'}, I also tried to disable loggin like this: logging.getLogger('pyppeteer').setLevel(logging.NOTSET) And nothing seems to work. -
Puzzling Warning With FileField In Django Admin
I created the below model to associate a file with another object type called Organization. The _path() function sets the path of the file to {MEDIA_ROOT}/orgs/{NAME OF ASSOCIATED ORG}/{FILENAME}. It also replaces any spaces in the path with underscores. So if I upload the file "Draft1.doc" and associate it with the org named "My High School", the full path should be uploads/orgs/My_High_School/Draft1.doc This is in my settings.py file MEDIA_ROOT ='uploads/' class OrgFile(models.Model): def _path(instance, filename): return F"orgs/{instance.org.name.replace(' ', '_')}/{filename}" file = models.FileField(upload_to=_path) org = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.file.name.split('/')[-1] When I use the Admin to upload and associate a file, the file is created in the correct place on disk and appears to have the correct path and associations in the admin. However when I navigate to the file object in the admin and click on the path labeled currently the "uploads/" portion is not included in the path (which may be OK) but I also get the warning: Org file with ID “9/change/orgs/My_High_School/Draft1.doc” doesn’t exist. Perhaps it was deleted? I have no idea why this happens since everything else looks OK. I assume that the link is supposed to take me to the file. -
Keyboard shortcut for {% %} in VSCode using Django HTML
I am building my first Django app and using the Django templating engine in my html files. I have the html and Django html plugin in VSCode. So far, it autocompletes html elements and colorizes the Django templates. Is there a way to autocomplete {% %} when using the Django HTML language mode in VSCode? -
I want to use my admin part rather then given by django default admin panel how i add my admin in django and also connect with db. its my admin panel
I have two part one of alumni section and another secton is admin section, this is my admin section image. -
Django - urls.py issue
I am developing this platform where a user can log in and take a quiz. The issue is that when I go on "localhost/quiz/quiz/" and then a click on my "choice", for example "data science" it gives me this error: sing the URLconf defined in piattaforma.urls, Django tried these URL patterns, in this order: admin/ [name='homepage'] users/ [name='user_list'] user/<username>/ [name='user_profile'] accounts/ accounts/ quiz/ quiz/ [name='quiz'] quiz/ questions/<choice>/ [name='questions'] quiz/ result/ [name='result'] The current path, quiz/datascience, didn't match any of these. I think the problem is on my urls.py on the questions path but I can't solve it quiz/questions.html {% extends "base.html" %} {% block title%} QUIZ {% endblock %} {% block content%} <form action="./result" method="post"> {% for que in ques %} <div class="row"> <div class="col-md-10"> <h3>{{ forloop.counter }}. {{ que.question }}</h3> </div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3"> <h4> <input type="radio" name="{{ que.id }}" value="{{ que.optiona }}"> {{ que.optiona }} </h4> </div> <div class="col-md-3"> <h4> <input type="radio" name="{{ que.id }}" value="{{ que.optionb }}"> {{ que.optionb }} </h4> </div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3"> <h4> <input type="radio" name="{{ que.id }}" value="{{ que.optionc }}"> {{ que.optionc }} </h4> </div> <div class="col-md-3"> <h4> <input class="form_control" type="radio" name="{{ que.id }}" value="{{ … -
django: drowning in login form/view
I am struggling a lot with my login system. At this point, I have watched so many different things about the topic that I got a bit lost. I have tried using the built-in authentication system but I failed to make it work with django-tenant. At this point, my login view "works" but does not do its job. I am unable to figure out what is going on. Ideally I would like to integrate what I have with Django built in User for a safe and secure authentication system. Model.py class Client(TenantMixin): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, default='') email = models.EmailField(default='') company = models.CharField(max_length=100, default='') password = models.CharField(max_length=100, default='') created_on = models.DateField(auto_now_add=True) class Domain(DomainMixin): pass forms.py class UserLoginForm(forms.Form): email = forms.CharField() password = forms.CharField(widget = forms.PasswordInput) company = forms.CharField() def cleaned_data(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') company = self.cleaned_data.get('company') try: tenant = Client.objects.get(email=email, password=password, company=company) except Client.DoesNotExist: raise forms.ValidationError("User does not exist") if email and password: user = authenticate(username= email, password= password) if not user: raise forms.ValidationError('THIS USER DOES NOT EXIST') if not user.check_password(password): raise forms.ValidationError('incorrect password') if not user.is_active: raise forms.ValidationError('this user is not active') return super(UserLoginForm, self).clean() views.py def login_view(request): form = UserLoginForm(request.POST or None) if … -
Heroku Deployment With MongoDB Error: Connection Refused
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused Hello their, I am having a little bit of trouble trying to deploy my Django site in python. I am getting this error(shown above) when trying to connect with my MongoDB atlas database. I read that I have to whitelist my IP, but when I did it did not work. Here is my views.py file: class Initialize(): def __init__(self, name): self.name = name myclient = pymongo.MongoClient('mongodb+srv://<MY Username>:<My Password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority') global mydb mydb = myclient[f"{self.name}"] global userData userData = mydb["userData"] global authData authData = mydb["auth_user"] global storesCollection storesCollection = mydb["stores"] global mycolPostalCodes mycolPostalCodes = mydb["postalCodes"] When I was running my code before I tried deploying it, the code worked fine. Also, here is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'cluster0', 'HOST' : 'mongodb+srv://<my username>:<my password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority', 'USER': '<my username>', 'PASSWORD': '<my password>', } } Any help would be much appreciated. Thanks. Please message me for more information if needed. -
What is the use of Celery in python?
I am confused in celery.Example i want to load a data file and it takes 10 seconds to load without celery.With celery how will the user be benefited? Will it take same time to load data? -
Refused to display iframe or embed tag in django 3.0 and chrome
I had a django app that used an iframe to display a pdf stored in my local machine, something like this: <embed src="path_to_file.pdf" type="application/pdf"> Everything worked just fine in all supported browsers... Until today. The app suddenly stopped working on Chrome and the console displays the message Refused to display 'path_to_file.pdf' in a frame because it set 'X-Frame-Options' to 'deny'. In other browsers it's still working as usual. I don't know if Chrome just made an update or what changed but it is not working anymore. ¡Any help would be appreciated! -
Django static files are not accesible
I have created a django project and tried to use an HTML template; however, I get an error while accessing files in static folder. Here is my configuration: #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') I have added static variable at the top of the HTML file as: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %}"> .....(cont'd) The following is my folder configuration: -my_project --assets --my_project --static --templates --travello My problem is that: I cannot access images in static folder from browser, that is, when I type http://127.0.0.1:8000/static/images/about_1.jpg, I get an error like Page not found (404) When I type http://127.0.0.1:8000 in order to see the index.html main page, I get the page with lots of errors saying Failed to load resource: the server responded with a status … -
Django Messages framework for default login system (contrib.auth)
I am using Django's default authentication system and I was wondering if there is a way to use Django's messages framework with it to display error messages such as incorrect login details etc. All the posts I have searched through here suggest to override the login system, but is there any easier way to do it? I already have a form which is subclassing the AuthenticationForm to use form_valid method, is there anything I could do there? Any help would be really appreciated. -
Can't find django-html in "Select Language Mode" in VS Code
I'm trying to set django-html as the language for my *.html files so that I can use the snippets for python template literals but I can't find it anywhere. When I look for django html by clicking on "Select Language Mode" in the lower right corner I don't get any result: Here's is a screenshot of the search, Another screenshot However, I've seen in a video that this should be possible: screenshot with the search from the video I'm using VS Code 1.44.1 and Windows 10 -
Update django-dash dashboard with new dataframe data in a Django app
Our Aim We're creating a time series plot in a Django app using dash/plotly. The data being plotted is read from a pandas dataframe which is first pre-processed written to a file, and then sent to the next page via POST request for the interactive dashboard. On updating the dataframe the new plot should be plotted on the dashboard. Problem Even though the data is changed the dashboard doesn't updates. It still shows the plot for the previous dataframe saved in the file. Until or unless the django server is restarted it doesn't updates. dcc.interval() doesn't do the trick, it also requires the server to be restarted even though you can see the dash app reply in the console log plus it removes the zoom in capability for a graph since, it refreshes the plot. The Django version in use is 2.2.9 Here is the django-dash app code: import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output,State import plotly.graph_objs as go from django_plotly_dash import DjangoDash import pandas as pd import dash_table from datetime import datetime app = DjangoDash('chalao') selected_df=pd.read_pickle(r'static/selected_df.pkl') actual_df=pd.read_pickle(r'static/actual_prediction.pkl') datatable_df=actual_df datatable_df.reset_index(inplace=True) datatable_df['START_DATETIME'] = datatable_df['START_DATETIME'].astype(str) datatable_df['Transaction'] = datatable_df['Transaction'].round(decimals=-3) datatable_df['Prediction'] = datatable_df['Prediction'] + 500 datatable_df['Prediction'] = datatable_df['Prediction'].round(decimals=-3) … -
Show data from API on Django tempalte
I'm trying to show the fetched data on an API to the Django template. Here's what I've tried on home.html <h1>Title: {{data.title}}</h1> Here's my views.py which gets the data from services.py class IndexData(TemplateView): def get(self, request): article_data = services.get_data() return render(request, 'pages/home.html', article_data) Here's the services.py def get_data(title, url, description, body, datePublished): url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI' params = {"autoCorrect": "true", "pageNumber": "1", "pageSize": "10", "q": "police", "safeSearch": "true" } headers = {...} r = requests.get(url, headers=headers, params=params) data = r.json() article_data = {'data': data['value']} return article_data The returned json is { "_type":"all", "didUMean":"", "totalCount":2923, "relatedSearch":[ "coronavirus", "new york", "post", "getty", "times", "china", "council", "shares", "americans", "pandemics", "prime", "19 crisis" ], "value":[ { "title":"COVID-19 And The Failure Of Populism", "url":"https://www.forbes.com/sites/riskmap/2020/04/02/covid-19-and-the-failure-of-populism/", "description":"Populist presidents, reliant on their need to constantly convey positive messaging that bolsters their support, have struggled to take the decisive, forward-looking action that the coronavirus crisis demands.", "body":").\nHow will the pandemic play out in these countries?\nSteering countries through the pandemic and an eventual recovery will then be the responsibility of leaders who will have lost credibility, as well as the veneer of their all is well message. The narrative that allowed people in certain countries to latch on to something they … -
Django Login: I'm entering the correct credentials but can't log in
I have a problem while trying to log in with Django. I'm putting the right username and password but I'm still getting the error in Postman: { "non_field_errors": [ "Incorrect username or password." ] } Here is my serializer: from django.contrib.auth import authenticate from rest_framework import serializers from ..models.model_user import * class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): user = authenticate(username=attrs['username'], password=attrs['password']) if not user: raise serializers.ValidationError('Incorrect username or password.') if not user.is_active: raise serializers.ValidationError('User is disabled.') return {'user': user} My views: from django.conf import settings from django.contrib.auth import login, logout from rest_framework import views, generics, response, permissions, authentication from ..serializers.serializers_user import * from ..serializers.serializers_login import * class LoginView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return response.Response(UserDetailsSerializer(user).data) class LogoutView(views.APIView): def post(self, request): logout(request) return response.Response() My urls: from django.contrib import admin from django.urls import include, path from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from rest_framework import routers from ea.views import * from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('', include('eao.urls')), path(r'', include(router.urls)), path('admin/', admin.site.urls), path(r'login/', LoginView.as_view(), name='user-login'), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), … -
DRF Form Rendered in SPA
I'm trying to wrap my head around the workings of DRF and I just cannot understand how to achieve this or even where to start with understanding the flow of things. I'm trying to render an HTML form out of DRF to an SPA or static HTML page with JQuery. I have a page /page/ I have a serializer: `class StudentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Student fields = ('firstName', 'lastName')` Now I need to have a form rendered that has the initial data and allows to POST/PUT. I can do this very successfully with an APIView and HTMLrenderer, but I’m trying to see if I can have multiple rendered forms on a single page without a single APIView page. If the general approach is to hand-code the forms on a SPA front-end then that’s great, I just want to know if that’s the required approach. -
Cloud Build env variables not passed to Django app on GAE
I have a Django app running on Google AppEngine Standard environment. I've set up a cloud build trigger from my master branch in Github to run the following steps: steps: - name: 'python:3.7' entrypoint: python3 args: ['-m', 'pip', 'install', '--target', '.', '--requirement', 'requirements.txt'] - name: 'python:3.7' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: 'gcr.io/cloud-builders/gcloud' args: ['app', 'deploy', 'app.yaml'] env: - 'SHORT_SHA=$SHORT_SHA' - 'TAG_NAME=$TAG_NAME' I can see under the Execution Details tab on Cloud Build that the variables were actually set. The problem is, SHORT_SHA and TAG_NAME aren't accessible from my Django app (followed instructions at https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values#using_user-defined_substitutions)! But if I set them in my app.yaml file with hardcoded values under env_variables, then my Django app can access those hardcoded values (and the values set in my build don't overwrite those hardcoded in app.yaml). Why is this? Am I accessing them/setting them incorrectly? Should I be setting them in app.yaml somehow? I even printed the whole os.environ dictionary in one of my views to see if they were just there with different names or something, but they're not present in there. -
Error when serializing foreign key object with django-rest-framework-gis to geojson
I am trying to serialize into geojson a model with a foreign key that has a geometry field. I am using the django-rest-framework-gis. I am using django 2.2 I'm really stuck on this and none of the other related answers on stackoverflow work for me. e.g. I have tried versions of this: How can I flatten a foreignkey object with django-rest-framework-(gis) Set serializer geo_field as PointField from another model - Django I would be very grateful for help as been literally stuck on this for days. Thank you, kind people. The problem is I get this error: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'statements.models.Response'> Models: from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Hexgrid_10km2(models.Model): lng = models.FloatField() lat = models.FloatField() polygon = models.MultiPolygonField(srid=4326) centroid = models.PointField(default=Point(0,0), srid=4326) def __str__(self): return f'lng: { self.lng } lat: {self.lat }' class Response(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) statement = models.ForeignKey(Statement, on_delete=models.CASCADE) hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, on_delete=models.CASCADE, null=True, blank=True) @property def polygon(self): return self.hexgrid_10km2.polygon Views class ResponseHeatmapAPIView(APIView): #ReadOnly def get(self, request, pk): final = Response.objects.all() serializer = ResponseHeatmapSerializer(final, many=True) return Response(serializer.data) Serializers class ResponseHeatmapSerializer(GeoFeatureModelSerializer): """ A class to serialize hex polygons as GeoJSON compatible data …