Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django celery,something wrong with shared_task
i use django-rest-framework and celery this ims my views.py # GET /server/test/<para>/ class Testcelery(APIView): def test(self): print(celery_test()) def get(self, request, para, format=None): print('test') self.test() # result = add.delay(4, 4) # print(result.id) result = OrderedDict() result['result'] = 'taskid' result['code'] = status.HTTP_200_OK result['message'] = 'success' return Response(result, status=status.HTTP_200_OK) this is a simple celery task @shared_task() def celery_test(): print('celerytest') return True i debug the django it can goes to the test method but the program stuck at the next step in call in local.py where the error happens the debug stops there,and shows like this debug result -
Pycharm Import Error
guys. I'm trying to develop a program to create excel file with using xlwt. I have used pip install xlwt to install it. In Terminal, it can be imported with no error. And the Django project could be run correctly. But in pycharm, it shows import error when running the Django project. The error code shows below: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/motion/Documents/GitHub/motion-op/motion/urls.py", line 4, in <module> from product.views import home File "/Users/motion/Documents/GitHub/motion-op/product/views.py", line 22, in <module> from .ProductService import ProductService File "/Users/motion/Documents/GitHub/motion-op/product/ProductService.py", line 13, in <module> from method import ProductServicePO,send_email, SaveImg, create_excel_file File "/Users/motion/Documents/GitHub/motion-op/product/method/create_excel_file.py", line 2, in <module> import xlwt ImportError: … -
Django chain multiple queries in view
I have three models: Course Assignment Term A course has a ManyToManyField which accesses Django's default User in a field called student, and a ForeignKey with term An assignment has a ForeignKey with course When a user logs in to the page, I would like to show them something like this bootstrap collapse card where I can display each term and the corresponding classes with which the student is enrolled. I am able to access all of the courses in which the student is enrolled, I'm just having difficulty with figuring out the query to select the terms. I've tried using 'select_related' with no luck although I may be using it incorrectly. So far I've got course_list = Course.objects.filter(students = request.user).select_related('term'). Is there a way to acquire all of the terms and their corresponding courses so that I can display them in the way I'd like? If not, should I be modeling my database in a different way? -
Database not storing JSON variable
I have an django app in which I am trying to store the gridster widget configuration in the form of JSON variable to database.But when I click"Update" button on my webpage my database does not stores any value. My JS Code which sends serial value to database var gridster; var $color_picker = $('#color_picker'); var URL = "{% url 'save-grid' %}"; gridster = $(".gridster ul").gridster({ widget_base_dimensions: [80, 80], widget_margins: [5, 5], helper: 'clone', resize: { enabled: true } }).data('gridster'); $(".add-button").on("click", function() { $('#test').click(); $('#test').on('change', function(e) { var test = document.getElementById('test'); if (!test) { alert("Um, couldn't find the fileinput element."); } else if (!test.files) { alert("This browser doesn't seem to support the `files` property of file inputs."); } else if (!test.files[0]) { alert("Please select a file before clicking 'Load'"); } else { file = test.files[0]; console.log(file); fr = new FileReader(); fr.readAsDataURL(file); fr.onload = function() { var data = fr.result; // data <-- in this var you have the file data in Base64 format callbackAddButton(data); test.value = ''; $('#test').replaceWith($('#test').clone()) }; } }) }); function callbackAddButton(file) { // get selected color value var color = $color_picker.val(); // build the widget, including a class for the selected color value var $widget = $('<li>', { 'class': … -
HTML in django widgets?
I'm creating a project in Django. I use ModelForms quite a bit to get user data. I'd like to add help text to each of my fields. How I'd like those to appear is like this: A tiny "?" image to the right of the input, then a popup that appears when the "?" is hovered over. I have this working in CSS and HTML. What I need to do is put in an tag before every instance of help_text being displayed, along with some other HTML. From my understanding I can do this by subclassing widgets, but I've seen in several places that I shouldn't add HTML to widgets? It seems much less elegant to stop using the ModelForm auto-rendering in all my templates and instead re-write it using loops and then put the HTML in there. The help_text is never going to be controlled by anyone except me, so I don't believe XSS is a concern. Am I missing something? Is there an easier/better way to do this? Also, if someone could point me to a guide on this with an explanation, it would be much appreciated. -
Why do I get an operational error, saying a database is read-only?
I'm using SQLite with Django, have been for a few months. Today I was about to do replace a table with an updated version, which I regarded as tricky so I took a full backup of my entire project. At a certain point, I started getting this error -- with subtext "attempt to write a readonly database." This made no sense to me, but after trying and failing to fix it, I renamed the entire directory and restored the morning backup. No help. I tried a different browser. No help. I logged in with an incognito session. No help. I logged in with an incognito session and a different Django user account. No help. In all cases, it's the login that fails. And it fails just after I enter the password. The site is still in debug mode, and I've pasted the error info to http://dpaste.com/2NS9ZMJ.txt I have no idea how to get my site working again, if a complete restore of the project directory won't do it. -
Modifying a field in serializers.ModelSerializer Class imported from an external library
I'm trying to override/modify a class XXXSerializer(serializers.ModelSerializer) object defined in an external library that I am including in the installed_apps configuration of my settings.py. class XXXSerializer(serializers.ModelSerializer): username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())],default='') class Meta: model = User exclude = [ 'is_superuser', 'is_staff', 'is_active', 'content_type', 'groups', 'user_permissions', 'account_id', ] As shown above, the email is required to be unique in their definition. However, I do not want to require it to be unique. My question is therefore, what is the best way to override this field? Some thoughts/attempts: Copy the entire library directly into my project, and take out the validator there. I think this would definitely work but may not be an optimal solution? Somehow override it by defining another YYYSerializer with my desired property, and use import external_library sys.module['external_library.XXXSerializer'] = YYYSerializer. However, I'm not exactly sure about 1. where to put this piece of code, 2. the proper syntax, 3. whether this would even work in an ideal situation. When I put it in settings.py or some __init__ files, it returns Apps aren't loaded yet error - probably because the external_library hasn't been loaded yet. Any suggestions would be appreciated! -
How do I change the url back to mysite.com in django after loging in the user?
I have two apps in my django project. After loging the user in through "visit" app I redirect to "mainapp". How ever my url patter becomes something like this : mysite/accounts/profile/ If I try specifying in urls.py I get redirected to "visit" app. How do I reset my url visit/views.py def profile(request): return HttpResponseRedirect(reverse("main:home")) main/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'accounts/profile', views.home, name='home'), ] main/views.py def home(request): return render(request, 'main/home.html') -
django import csv in several related models
For a web application of naturalistic data for the study of bats (http://www.dbchiro.org), I need to be able to propose a view allowing to import files from spreadsheets (csv, ods files , xls) into database. To import this data into a single table, no problem, several extensions exist (django-import-export or django-csvimport in particular). On the other hand, my need is more particular because my naturalistic data is distributed in several distinct tables (not counting the tables of dictionaries). Here is the schematic diagram: Model Place Place (a locality is a site with unique x / y coordinates as a building). 1-n Model Session (one data = one date and one inventory method by locality) 1-n Model Sighting (one data = one species per session) 1-n Model CountDetail (one data = 1 detail for a species: eg number of males, number of females, etc.) What I would like to get is the ability to import the data of a session with a single csv file that would populate the last two models: Observations (Sighting) and for each observation (each species observed), its detailed data (CountDetail). Is there one or more simple solutions (I'm doing well but I'm not a great python … -
Django save rows of html table selected by checkbox in the database
I have a table in my models which the stocks are saving in it and its name is Stocks this table is desplayed in a template and i want to put a checkbox beside each row to save the checked row in another table of the model here ismy model.py : class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) brand=models.CharField(max_length=64, validators=[ RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)] ,verbose_name=_('brand')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.id) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) class SellerDesktop(models.Model): seller=models.OneToOneField(User, related_name='seller', blank=True, null=True) buyer=models.OneToOneField(User, related_name='buyer', blank=True, null=True) stock=models.ForeignKey(Stocks, related_name='stocktoseller', blank=True, null=True) def __str__(self): return str(self.seller) + '-' + str(self.buyer) class Meta: verbose_name=_('SellerDesktop') verbose_name_plural=_('SellerDesktop') and the Template : <form method="post"> {% csrf_token %} <table id="example" class="table table-list-search table-responsive table-hover table-striped" width="100%"> {% for item in myst %} <td><input type="checkbox" name="sendtoseller" value="{{ item.id }}"></td> <td>{{ item.user.profile.companyname}}</td> <td>{{ item.name }}</td> <td>{{ item.brand }}</td> <td>{{ item.number }}</td> <td>{{ item.pasvand }}</td> <td>{{ item.comment }}</td> <td>{{ item.price }}</td> <td>{{ item.date|timesince }}</td> </tr> {% endfor %} </table> <div style="text-align: center; margin-top:0.5cm; margin-bottom:1cm;"> <input type="submit" name="toseller" value="Submit to seller " style="color:red; width:100%;"/> </div> </form> and the view : def allstocks_view(request): if request.method=='POST': tosave = request.POST.getlist('sendtoseller') stockid=Stocks.objects.filter(id=tosave) SellerDesktop.objects.create(buyer=request.user,stock=stockid) stocks_list=Stocks.objects.all().filter(confirm=_('approved') ).order_by('-date') … -
How to redirect to another app directory after loging in django?
I have two app directories in my django project named "visit" and "main". After Loging the user in through visit app, how do I change the app directory to another main i;e how to display templates from another app (excuse my english) ? visit/views.py : from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django import forms from .forms import UserRegistrationForm def index(request): return render(request, 'visit/index.html', context=None) def profile(request): # I need to change directory form here return render(request, 'main/templates/main/profile.html') def registration(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): formObj = form.cleaned_data username = formObj["username"] name = formObj["name"] email = formObj["email"] password = formObj["password"] if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username=username, name=name, password=password) login(request, user) return HttpResponseRedirect('/profile/') else: form = UserRegistrationForm() return render(request, 'visit/registration/register.html', {'form': form}) -
No module named 'django.urls'
I'm trying to set up django-registration-redux, but when I set up the url (r '^ accounts /', include ('registration.backends.default.urls')) in the urls.py file and I try to access any page I get the following error message: ModuleNotFoundError No module named 'django.urls' I have checked the manual several times and everything is in order. What is missing? Where is my mistake? urls.py file """p110 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include, url from django.contrib import admin from boletin import views from .views import about urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.index, name='index'), url(r'^contact/$', views.contact, name='contact'), url(r'^about/$', about, name='about'), url(r'^accounts/', include('registration.backends.default.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Django queryset result is wrong for the test
My model is: class AndroidOffer(models.Model): name = models.CharField(max_length=128, db_index=True) # ... countries = models.ManyToManyField(Country) And the following code (I skipped previous filtering): active_offers = active_offers.filter(countries__in=[country]) It generates this SQL query: SELECT "offers_androidoffer"."id", "offers_androidoffer"."name", "offers_androidoffer"."title", "offers_androidoffer"."is_for_android", "offers_androidoffer"."is_for_ios", "offers_androidoffer"."url", "offers_androidoffer"."icon", "offers_androidoffer"."cost", "offers_androidoffer"."quantity", "offers_androidoffer"."hourly_completions", "offers_androidoffer"."is_active", "offers_androidoffer"."description", "offers_androidoffer"."comment", "offers_androidoffer"."priority", "offers_androidoffer"."offer_type", "offers_androidoffer"."package_name", "offers_androidoffer"."is_search_install", "offers_androidoffer"."search_query", "offers_androidoffer"."launches" FROM "offers_androidoffer" INNER JOIN "offers_androidoffer_platform_versions" ON ("offers_androidoffer"."id" = "offers_androidoffer_platform_versions"."androidoffer_id") INNER JOIN "offers_androidoffer_countries" ON ("offers_androidoffer"."id" = "offers_androidoffer_countries"."androidoffer_id") WHERE ("offers_androidoffer"."is_active" = True AND "offers_androidoffer"."quantity" > 0 AND NOT ("offers_androidoffer"."id" IN (SELECT U0."offer_id" FROM "offers_androidofferstate" U0 WHERE (U0."device_id" = 1 AND (U0."state" = 3 OR U0."state" = 4)))) AND NOT ("offers_androidoffer"."package_name" IN (SELECT V0."package_name" FROM "applications_app" V0 INNER JOIN "applications_deviceapp" V1 ON (V0."id" = V1."app_id") WHERE (V1."device_id" IN (SELECT U0."device_id" FROM "users_userdevice" U0 WHERE U0."user_id" = 2) AND NOT (V0."package_name" IN (SELECT U2."package_name" FROM "offers_androidofferstate" U0 INNER JOIN "offers_androidoffer" U2 ON (U0."offer_id" = U2."id") WHERE (U0."device_id" = 1 AND (U0."state" = 0 OR U0."state" = 1 OR U0."state" = 2))))))) AND "offers_androidoffer_platform_versions"."platformversion_id" IN (14) AND "offers_androidoffer_countries"."country_id" IN (6252001)) ORDER BY "offers_androidoffer"."priority" DESC; If I run this query in Postgresql console, it will return 0 rows, but active_offers has 4 results (all rows in table), like if I remove AND "offers_androidoffer_countries"."country_id" IN (6252001) statement. … -
How to pull a html template on a $.post call, and include data?
I have the following code on one Django HTML template that when it runs it pulls the html from another template and loads it into the #container element. $.get('/form/', function(form){ $('#container').html(form); }); So if I was to follow the same thought process I have this code on another page in which I need to use a POST request instead of GET. $.post( '/form/results/', {item: $('#item-selector').val(), csrfmiddlewaretoken: csrftoken}, function(data){ $('#container').html(data) } ) So what I'm trying to get the post request to do is to pull the html from the url and insert it into the #container element but I can't get it to work. If you need any more information just comment below and I will add it. -
What is an example use case of using primaryfieldserializer in django rest framework?
I had a goal, to link cities and their neighborhoods together in a request response in a nested serializer. Neighborhoods have a Foriegn key to cities. for clarity here are my models and serializer originally used. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') but that returned only the neighborhood primary keys with the cities not a full city object. This: city: "Chicago" searchneighborhood_set: 0: 5 1: 4 2: 3 city: "New York" searchneighborhood_set: 0: 8 1: 7 2: 6 instead of what it should be, this: city: Chicago searchneighborhood_set: 0: {pk: 5, neighborhood: 'River North} .... I got the above request, not by using primarykeyrelatedserializer but by using the serializer used for seralizing neighborhood objects which looks like this: class SearchNeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = SearchNeighborhood fields = ('pk','neighborhood') so now replace the primarykeyrealatedserializer with my neighborhood one and the proper nested serailzer is this: class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') so this begs the question, what is an actual use case for the primarykeyrelated … -
relation "django_admin_log" already exists
when i try to run python manage.py migrate i run into following error Upon running python manage.py run migrations it says no changes detected. and when i runserver it gives me warning that i have unapplied migrations as well.i have been searching internet for two hours but got not solution. Someone knowing the solution please share :) -
How to add django Group field to a Customer User Register
i used this Code in serializer.py group = Group.objects.get() group.user_set.add(self.object) it work fine when the Group Field have just one item and added in DB with no problem. But when i add more than one item in The Group List Field i am getting an Error: get() returned more than one Group -- it returned 2! what can i do ? Image:For one item Work Fine Image:With More than one i am getting This Error This is My Full Code: from rest_framework import serializers from . import models from django.contrib.auth import get_user_model from django.contrib.auth.models import Group User = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) def validate(self, data): if not data.get('password') or not data.get('confirm_password'): raise serializers.ValidationError("Please enter a password and ""confirm it.") if data.get('password') != data.get('confirm_password'): raise serializers.ValidationError("Those passwords don't match.") return data def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'] ) group = Group.objects.get() group.user_set.add(self.object) user.set_password(validated_data['password']) user.save() return user class Meta: model = get_user_model() fields = ( 'username', 'password', 'confirm_password', 'first_name', 'last_name', 'email', 'groups', ) -
Django middleware for consuming an external api
Here's the deal, I need to consume an API and every time I perform a request a header needs to be appended, I've checked the middleware documentation but this is only working for incoming requests, is there anything that can be used in this situation. -
What is main use of queryset.in_bulk in Django framework?
I'm curious, what is use cases for queryset's in_bulk method? -
django/python logging with gunicorn: how does django logging work with gunicorn
I have a Django/Python application deployed(using gunicorn) with 9 workers with 5 thread each. Let's say if on a given time 45 requests are getting processed, Each thread is writing a lot of logs. How Django avoids writing logs for multiple threads at the same time? And how the file open and close works for each request(does this happen at each request, if yes, any other efficient way of logging)? -
How to manually create tags using Bootstrap Tags Input
I am using Bootstrap Tags Input for introducing tagging mechanism in my project. So far I can easily load predefined tags using add method as described in the documentation, But I am unable to create tags manually. Say I type some text and press space or comma button then a new tag should be created, Just like we add tags while writing Stack overflow question. Is it possible to add this behaviour, any help would be appreciated. -
'update_grid' object has no attribute 'title'
I have written model.py and views.py.When I add the json variable from Admin it gives following error 'update_grid' object has no attribute 'title' My views.py def save_grid(request): if request.method == 'POST': data = json.loads(request.body) grid = update_grid(data=data) grid.save() return HttpResponse('success') # if everything is OK My models.py from django.db import models from django.utils import timezone from jsonfield import JSONField class update_grid(models.Model): data = JSONField() def __str__(self): return self.title My JSON variable is of the form [{"col":1,"row":1,"size_x":1,"size_y":1},{"col":2,"row":1,"size_x":1,"size_y":1},{"col":3,"row":1,"size_x":1,"size_y":1},{"col":4,"row":1,"size_x":1,"size_y":1},{"col":1,"row":2,"size_x":1,"size_y":1},{"col":2,"row":2,"size_x":1,"size_y":1},{"col":3,"row":2,"size_x":1,"size_y":1},{"col":4,"row":2,"size_x":1,"size_y":1},{"col":1,"row":3,"size_x":1,"size_y":1},{"col":2,"row":3,"size_x":1,"size_y":1},{"col":3,"row":3,"size_x":1,"size_y":1},{"col":4,"row":3,"size_x":1,"size_y":1},{"col":5,"row":1,"size_x":1,"size_y":1},{"col":6,"row":1,"size_x":1,"size_y":1}] -
Django querying user_auth with each request
When I login and visit any page, Django will proceed to do this query everytime: SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '1' How can I stop it? I am already saving the session in cache, I have also deleted all tags that use request and nothing happens, django will still make the query, only time it does not make the query is when I am an AnonymousUser. Version of django is: 2.0.2 -
how to get all values of primary key related field nested serializer django rest framework
I have the following models: class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) and then the following nested serializer: class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') paired with the view: class CityNeighborhoodView(ListAPIView): queryset = SearchCity.objects.all() serializer_class = CityNeighborhoodReadOnlySerializer when I make the api call I get this: city: "Chicago" searchneighborhood_set: 0: 5 1: 4 2: 3 city: "New York" searchneighborhood_set: 0: 8 1: 7 2: 6 Im just getting the primary keys of the objects related. Which is good I need that, but I also want the neighborhood name how do I get that? -
How to get all coordinates under a boundary in Google maps API and django
I've Coordinate data associated with a post what I want is that, let's say someone posted a post with coordinated of some coffee shop Manhattan, I wanna get that post while querying New York. One way I can think of to tackle this problem is to get all coordinates under New York and search it that way I know it's very stupid but I can't think of any other way.