Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uncaught TypeError: Cannot read property 'weight' of undefined [D3.js jquery-3.2.1.slim.min.js]
I am using Django framework and D3.Js to render some svg graphs. Everything works fine when i test in my local system. But while I deploy to the production server, the "Uncaught TypeError", pops in and fails to render. Following are the things I have tried, 1. commented the google analytics to get more detail bug report [no luck] 2. disabled the force in JS, the figures renders but the graph messed up. [do not want to do this] 3. Tried changing the name of property, but the error still persists for property like "name". Is there any permission issue I should check? Any help to get the bug will be very helpful. -
Django - filtering queryset with optional FormFields
Let's say I have a model: class House(models.Model): (...) price = models.DecimalField(decimal_places=2, max_digits=8) area = models.DecimalField(decimal_places=2, max_digits=6) And I have a Form for searching of Houses: class SearchHouseForm(forms.Form): price_min = forms.DecimalField(required=False, initial=0, decimal_places=2, max_digits=8) price_max = forms.DecimalField(required=False, initial=999999, decimal_places=2, max_digits=6) And the view function: def search_for_houses(request): queryset = House.objects.all() if request.method == 'GET' and 'search-submit-button' in request.GET: form = SearchHouseForm(request.GET) if form.is_valid(): queryset = queryset.filter( price__lte = form.cleaned_data['price_max'], price__gte = form.cleaned_data['price_min'] ) else: (...) return render(request, template, {'house_list': queryset, 'form': form}) I have a problem with the .filter()-ing. I want to apply the filter if and only if the user provides any value in the form field. If the price_max field is left blank, only the price__gte = form.cleaned_data['price_min'] should be applied. If both price_max and price_min are left blank, all House objects should be returned. Currently I get ValueError Cannot use None as a query value Is there a clean way to do that? The only thing I can think of is a long list of if statements for all such optional fields: if form.cleaned_data['price_max'] is not None: queryset = queryset.filter((...)) if form.cleaned_data['price_min'] is not None: queryset = queryset.filter((...)) (...) This does not seem as a good idea, especially … -
Paginator Number of Pages does not update in HTML after filtering results - Django
Paginator Number of Pages does not update in HTML after filtering with django_filter. html file <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</span> The page_obj.paginator.num_pages is the initial number (without any filters) of all results in the table (example: I got 12 results and showing 3 results/page => 4 pages) views class SearchBookView(ListView): template_name = "booksearch.html" paginate_by = 3 model = Book def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) book_qs = Book.objects.all() book_filter = BookFilter(self.request.GET, queryset=book_qs) paginator = Paginator(book_filter.qs, self.paginate_by) print(paginator.num_pages) ### Prints the correct num pages everytime even after filtering page = self.request.GET.get('page') try: book_list = paginator.page(page) except PageNotAnInteger: book_list = paginator.page(1) except EmptyPage: book_list = paginator.page(paginator.num_pages) context['book_list'] = book_list context['book_filter'] = book_filter return context After adding a filter (let's say after filtering it shows 5 results) page_obj.paginator.num_pages should be 2 in my HTML, right? Although in my view in print(paginator.num_pages) it shows 2, in the HTML it stays the original 4 pages. How can I pass this to the HTML file? WORKAROUND I did a workaround but it is kind of ugly: in my view I added a context['num_pages'] = paginator.num_pages and pass it my HTML: <span>Page {{ page_obj.number }} of {{ num_pages }}.</span> Any suggestions on how to … -
How to encrypt the Django website?
Our company has developed a website system using Django, and we can sell to other merchants (set up the website on the merchant's servers), the merchants can show the website to their users. But our company does not want to let merchants see the website source code, is there some way to encrypt the Django website? Or some other way that the merchants cannot access the website source code? -
MultipleObjectsReturned: get() returned more than one Feed -- it returned 2
I'm writing some simple test for an django-model and I'm just using assertEqual and assertNotEqual for it. Now I'm not fully grasping how to test BooleanField in this case. I have a model field like this: duplicate = models.BooleanField(default=False) and I'm writing this test for it, just to check is it equal ` def test_feed_duplicate_create(self): stefan_feed_duplicate = Feed.objects.get(duplicate='False') milan_feed_duplicate = Feed.objects.get(duplicate='False') self.assertEqual( stefan_feed_duplicate.duplicate, 'False') self.assertEqual( milan_feed_duplicate.duplicate, 'False')` But the error that I'm facing is: (venv) vagrant@jessie:/var/www/vhosts/bspotted.net/app$ ./manage.py test --keepdb socialmedia nosetests socialmedia --verbosity=1 Using existing test database for alias 'default'... ............E.................... ====================================================================== ERROR: test_feed_duplicate_create (app.socialmedia.tests.test_feed_model.CommentsTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/var/www/vhosts/bspotted.net/app/socialmedia/tests/test_feed_model.py", line 225, in test_feed_duplicate_create stefan_feed_duplicate = Feed.objects.get(duplicate='False') File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/query.py", line 338, in get (self.model._meta.object_name, num) socialmedia.models.feed.MultipleObjectsReturned: get() returned more than one Feed -- it returned 2! ---------------------------------------------------------------------- Ran 33 tests in 0.159s Can someone explain me what is the proper way of testing BooleanField in this case. Thanks. -
Django - Is this possible that the add default values when model is creating?
I want to add some default values in my database when the related model is creating with makemigrations command. For example I have this as model; class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created Date') modified_at = models.DateTimeField(auto_now=True, verbose_name='Update Date') is_deleted = models.BooleanField(default=False, verbose_name='Deleted') class Meta: abstract = True class ModelType(BaseModel): description = models.CharField(verbose_name='Name', max_length=225 ) and as I said before I want to add some default values ("value1", "value2", "value3", "value4") for my ModelType table. Is that possible? -
How to get data from a Formdata object in my views?
My AJAX call sends a FormData object with an uploaded image data inside it: $(document).on('submit', '#profileImageForm', function(e){ e.preventDefault(); var form_data = new FormData(); var image = document.getElementById('id_banner_image').files[0].name; form_data.append('file', image); $.ajax({ type:'POST', url: '/change_banner_image/', data : { form_data: form_data, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, traditional: true, cache: false, success: function(response){ console.log('Success'); }, }); }); and I succesfully receive the call in my views: def change_banner_image(request): if request.is_ajax(): data = request.POST.get('form_data') profile = get_object_or_404(Profile, user=request.user) profile.image = data profile.save() print(data) return HttpResponse() print(data) prints: [object FormData]. So how would I get the uploaded image from this FormData object? Which will then be the value of profile.image (which is a FileField). -
Django: return old data
I deleted the database - to update the new version of the data psql -U postgres - drop my_db created new with same name 'my_db' added new data: psql -U postgres -d my_db < my_db.sql after it in admin page i see new data - my_site/admin but on client side - i see data which i saw before drop database I clean cache, all data for this site what could it be? did anyone come across this? -
Django how to merge query results
I have an ArrayField with choices and i'm trying to filter the choices: PAYMENT_CASH = '0' PAYMENT_CARD = '1' PAYMENT_BANK = '2' PAYMENT_ONLINE = '3' PAYMENT = ( (PAYMENT_CASH, _('Cash')), (PAYMENT_CARD, _('Card')), (PAYMENT_BANK, _('Bank')), (PAYMENT_ONLINE, _('Online')), ) options = ArrayField(models.CharField(max_length=1, choices=PAYMENT, default='0'), size=4) When i use Location.objects.filter(city__id='683506').values_list('options', flat=True) it returns me <QuerySet [['0'], ['0', '1', '2', '3'], ['0', '1', '2'], ['0', '1'], ['0', '1', '2', '3']]> I wish to get all the options that are used. How can i merge the query or make them into a list and merge them? This is what i wish to get ['0', '1', '2', '3'] -
StreamBlock instance throws exception "AttributeError: 'str' object has no attribute 'block'"
I am using the example project provided by Wagtail. The StreamField gets as argument A DemoStreamBlock class DemoStreamBlock(StreamBlock): h2 = CharBlock(icon="title", classname="title") h3 = CharBlock(icon="title", classname="title") h4 = CharBlock(icon="title", classname="title") intro = RichTextBlock(icon="pilcrow") paragraph = RichTextBlock(icon="pilcrow") aligned_image = ImageBlock(label="Aligned image", icon="image") pullquote = PullQuoteBlock() aligned_html = AlignedHTMLBlock(icon="code", label='Raw HTML') document = DocumentChooserBlock(icon="doc-full-inverse") Then in the Page class I'm instantiating a variable e.g. class BlogPost(Page): blog_text = StreamField(DemoStreamBlock()) content_panels = Page.content_panels + [ StreamFieldPanel('blog_text') ] The first time I run the migrations Django doesn't want me to put a default value because of the non-nullable field that I am adding. However, if I want to add another StreamField field I am prompted to add a default value: class BlogPost(Page): blog_text = StreamField(DemoStreamBlock()) blog_short_text = StreamField(DemoStreamBlock()) content_panels = Page.content_panels + [ StreamFieldPanel('blog_text'), StreamFieldPanel('blog_short_text'), ] You are trying to add a non-nullable field 'blog_short_text' to blogpost without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a > null value for this column) 2) Quit, and let me add a default in models.py I am choosing 1 and then enter … -
Ubuntu service Upstart or SystemD, Django development server as Service
I've been working around with Python & Django Framework for a while with Ubuntu 16.01. Since I used Django with Q system (Celery) and some others Enhancement Apps. When I try to run all the apps each time, I need to run development server "{python manage.py runserver}", then running Celery Worker "{celery -A filename worker -l info}". Each time I working, it takes me minutes to enter the directory and start it up. I surf around and come up with the idea of setup it as service. Example, service name: "pyd". I just need to run "{sudo pyd start}" -> then Django Development Server and Celery will start, and if I run "{sudo pyd stop}" -> then Django & Celery will stop. I try to search around, and things start to confuse me between "Upstart" and "Systemd". Could any one suggest, me how to make both Django and Celery as Service run in Ubuntu ? between "Upstart" & "Systemd" which one is better ?? Source code to indicate sample is appreciated. Thank -
Nested serializer with custom queryset
I am trying to display the custom query values to the nested serializer . But its not displaying serializer.py class TueRangeSerializer(serializers.ModelSerializer): class Meta: model = SubnetRange fields = ('type', 'id', 'begin', 'end') class TueSubnetSerializer(serializers.ModelSerializer): range = TueRangeSerializer(required=False,read_only=False,many=True) class Meta: model = Subnet fields = ('name','base_address','bits','range') def create(self,validated_data): print(validated_data) And in the api file api.py class SubnetList(APIView): def get(self, request, format=None): query = 'SELECT ss.id ,ssr.id, ssp.id , ' \ ' ss.name as name, ss.bits as bits, ssr.begin as begin FROM subnets_subnet ss' \ ' inner join subnets_subnetphysical ssp on ssp.subnet_id = ss.id' \ ' inner join subnets_subnetrange ssr on ssr.subnet_physical_id = ssp.id' subnets = Subnet.objects.raw(query) serializer = TueSubnetSerializer(subnets,many=True) return Response(serializer.data) SQL query is correct. But on the response of the serializer its displaying only the data from subnets table Result [ { "name": "First subnet", "base_address": "192.100.30.0", "bits": 24 }, { "name": "Second subnet", "base_address": "192.100.30.0", "bits": 24 } ] Its not displaying the range output -
unable to access django website from URL but accessible from IP address
I have installed django on Amazon lightsail, I can access my website through the static server IP address. My domain is hosted on Godaddy. I change the Name Server in GoDaddy. But still when I try to access my website through domain name it shows me Nignx welcome page. Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. In my django settings.py I have given only the IP address ALLOWED_HOSTS = ['YOUR_AMAZON_LIGHTSAIL_IP'] And in Nginx file, I also added only the IP address. server { listen 80; server_name YOUR_AMAZON_LIGHTSAIL_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/django_project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/django_project/django_project.sock; } } I am using Gunicorn and Nginx on my hosting server. -
Django deadline alert
I am building a management application for a company. One of the things the application can do is start new projects. The model here for is: ` class Project(models.Model): employees = models.ManyToManyField(settings.AUTH_USER_MODEL) division = models.ForeignKey(Division) client = models.ForeignKey(Company) description = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) deadline = models.DateField(blank=True) active = models.BooleanField(default=True) ` As you can see in the model a employee can set a deadline for their project. I need to able to send the user notifications if they are close to their deadline. For example, if the deadline is in two days, the user will get a notification like "Your deadline for projectname is over two days". So basically what I need is a deadline timer. What is the logic for this? I don't really know where to start with this? -
NameError: name 'base' is not defined(haystack search)
I wanted to include full text search in my django application. I am using whoosh-haystack for this.When I include whoosh and haystack in my installed apps,and execute the command ./manage.py, I am getting an import error. Can anyone sort this out. settings.py INSTALLED_APPS = { 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', 'whoosh', 'haystack', } when I make migration in my model the error which I got is: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python \Python36\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\Samad Talukder\Desktop\django-env\search\search\settings.py", line 80, in <module> 'PATH': os.path.join(base(), 'whoosh_index') NameError: name 'base' is not defined my haystack connection: HAYSTACK_CONNECTIONS = { … -
How to record the operation logs that influenced by update methods with django-auditlog?
Recently, i have been dedicated to accomplishing the log logging function in the background. However, there exists a problem that i failed to figure out. Concretely, when it comes to record soft delete, as we all kown, the moment the field 'is_delete' transforms from False to True, the interface that including save methods can record relevant change, but this situation is not holding true for update methods. What i want to konw is that how to solve this problem without creating some corrlative tables. In terms of code, for example, if the current operation is 'save', model.is_delete=True,model.save() that is to say, After model.is_delete equals to constant 'True' and the save method of model is invoked, a new record will be inserted into the table called auditlog_logentry. Nevertheless, if update methods are conducted,i.e., model.update(is_delete=True), no records will be recorded in auditlog_logentry. I will be very appreciated if you can give me some hints or solutions. Looking forward to making progress together with you. Thanks a lot. -
Connection errors due to webpage navigation
I am having some trouble with connection errors in my Django app when a user navigates to different page before AJAX call is finished. So, when the client-side sends several AJAX calls for save/load/retrieve data etc., and when a user navigates to a different page - say when an AJAX call was just made from the client side to save the content, the content is saved and the functionally everything is fine, but I keep getting this error: Exception happened during processing of request from ('127.0.0.1', 50646) Traceback (most recent call last): File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\socket.py", line 594, in write return self._sock.send(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_error super(ServerHandler, self).handle_error() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", … -
Trying to add a django app to heroku
So,i've synced a django app from github to heroku,and i was trying to deploy from their web interface,but in the log it says Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed I understand that you can use heroku CLI to disable collectstatic,but i couldn't find a way to sync my github/heroku app with heroku CLI,any inputs would be helpful -
Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL. I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with... File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module> 'Did you install mysqlclient or MySQL-python?' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts. Thank you in advance. -
Trying to override an Oscar Model
I want to override an oscar partner model to OnetoOne but I'm receiving a conflict error. Conflicting "partner_users" models in application "partner": <class 'oscar.apps.partner.models.Partner_users'> and <class 'myapp.partner.models.Partner_users'>. I overwrite whatever I forked, why does it still take oscar's model? I've also included in settings.py under INSTALLED_APP=+ get_core_apps(['myapp.partner']) Not sure what else I missed? myapp/myoscar/partner/models.py from django.contrib.auth import get_user_model from django.db import models from oscar.apps.partner.abstract_models import AbstractPartner User = get_user_model() class Partner(AbstractPartner): user = models.OneToOneField(User, related_name='partner_user') from oscar.apps.partner.models import * -
CSRF verification failed. Request aborted - Shopping cart configuration
I'm trying to enable Payment module for courses and when I'm clicking checkout, I'm getting "CSRF verification failed. Request aborted." . I've tried adding my domain to "Home › Cors_Csrf › X domain proxy configurations › XDomainProxyConfiguration()" in Django admin panel. Even modified lms.env.json to add "ENABLE_CROSS_DOMAIN_CSRF_COOKIE": true, " ... still facing the issue. Can anyone please help. Google group message link : https://groups.google.com/d/msg/edx-code/4VnLJG-raPE/llF1PDG9AQAJ -
How to create a download button for image/filefield in Django
Download option is Working fine. But whenever i am hitting the file download link download option appears but after i download the file it's no longer the same file that i have uploaded. rather it becomes 9 bytes small file and can't be opened. views.py def download_file(request, path): response = HttpResponse('image/png') response['Content- Type']='image/png' response['Content-Disposition'] = "attachment; filename="+path response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path)) return response urls.py url(r'^get\/(?P<path>.*)$', download_file), index.html <a href="get/{{file_name}}">Download File</a> -
matplotlib legend at the bottom of the plot
Im trying to replicate a chart the was done in AmCharts but so far Im confused in the way to make the legend be outside and at the bottom of the plot right now im using this django view to render the plot def my_view(request) import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas colors = ["#FF9800", "#00E676", "#03A9F4", "#1A237E", "#AD1457", "#F44336", "#1DE9B6", "#01579B", "#CFD8DC", "#90A4AE", "#263238", "#B71C1C", "#FFEB3B"] data=('serv1','Aplicaiones','serv3','serv4','servi5','serv1','serv2','serv3','serv4','servi5',) datos=[99.3,99,23,100,99.3,99,23,100,99.3,99] figure=plt.Figure() pos=np.arange(len(datos)) ax = figure.add_subplot(111) b=ax.bar(pos, datos,color=colors) ax.legend(b,data,loc='upper center', bbox_to_anchor=(0,-.05, 1,0), ncol=5,mode="expand") ax.axis('off') # response = HttpResponse(content_type='image/png') figure.bbox_inches='tight' canvas = FigureCanvas(figure) canvas.print_png(response) return response the parameter bbox_to_anchor looks like the way to go, but chart has a limit and the label ends too close to the bars, my goal is to put the label (1 for each bar) leave space for axis description what I want https://d26dzxoao6i3hh.cloudfront.net/items/2U113d3m0O3Z0o053L3F/Captura%20de%20pantalla%202017-10-23%20a%20la(s)%2023.45.00.png?v=16e23ee7 right now this is what I got https://d26dzxoao6i3hh.cloudfront.net/items/0l0v2P2N3h1M15022V43/Captura%20de%20pantalla%202017-10-23%20a%20la(s)%2023.47.05.png?v=a36b97c9 -
Distance query for arbitary points with GeoDjango not working as expected - distance calculation seem off
I'm building a world-map and want users to be able to look-up locations and have them be sorted by distance from anywhere in the world. I'm using GeoDjango to calculate distances, however the distances returned seemed wrong so I checked them against geopy's calculations. The distances differ significantly to the point that if the results are sorted by the DB vs geopy values they would not be in the same order. I'm assuming the geopy values are correct so I'm wondering, is there something wrong with the way I implemented GeoDjango? Is it working as it should? Does this have something to do with trying to calculate distances for the entire world and not just a specific area which could have a srid? views.py pnt = GEOSGeometry('POINT({} {})'.format(latitude, longitude), srid=4326) qs = Place.filter(point__distance_lte=(pnt, D(km=radius*2))).annotate(distance=Distance('point', pnt)).order_by('distance') settings.py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'USER': '', 'NAME': 'places', 'HOST': '127.0.0.1', 'PORT': '5432', } } models.py: from django.contrib.gis.db import models from geopy.distance import vincenty class Place(models.Model): latitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True) longitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True) point = models.PointField(null=True, geography=True) def distance_from_target(self, target_lat, target_lon): if not target_lat or not target_lon: return None instance_point = (self.latitude, self.longitude) target_point = (target_lat, target_lon) … -
Implement a 'trending' algorithm to sort a queryset of Posts
I have a Post model for user posts, and also a PostScore model to track the score of that Post in order to sort the queryset by trending, similar to reddit's 'hot': class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) How would I go about sorting these posts? Would I make a custom method under in PostScore: @property def trending(self): score = self.upvotes - self.downvotes time = self.post.date print('TIME:', time) return score or would I sort it in my views?: posts = Post.objects.all().filter(entered_category=category).annotate( score_diff=F('score__upvotes') - F('score__downvotes'))\ .order_by('score_diff')