Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use google maps api to get user location in django?
I am working on a django project and need to get the user location, what I trying is either user can enter his city manually or click on locate button that will automatically finds it location and fill the city. I tried GeoIP but it is not sufficient, is it possible with Google maps api ? If not then how some websites automatically fills my location like - movie ticket booking, hotel booking websites ? If you can tell me a feasible solution of what I want to achieve is ? -
django reusable apps or decomposition
I am wondering how to make all django apps in my project reusable and self tested as separate unit.So the main idea is that I can take each app and tests for it will be successful. The main problem is that some applications tied with other. For example I have app users it has it's own models, views, serializers... When it's time to write business logic it turns out that this app need to be tied with another app etc. As for example I have endpoint where I change user's status and then create instance from another app, also other endpoints can have logic with another app. So in conclusion my project has some possibly reusable apps and some apps with business logic which are tied with that reusable apps. Is there a way to simplify project and move business logic to specific modules etc? -
Django Channels - Background update override not firing
Started of this question, and github repo, wanted to expand a little bit on it. I was looking for a way to run a task in background, and update some model fields as the process was running. I managed to do that, but wanted to send an email as the process finished (and setting import_finished = True), but when the second QuerySet update method runs, my overriden update method is not firing (although the model is correctly updated). I have all 3 separate terminals running django-server, django-worker and the redis-server, with no errors. I cannot figure out why is this happening, and why the second time the object is updated, the overriden QuerySet method doesn't run. starttasks/models.py from django.db import models from django.db.models.query import QuerySet class FileQuerySet(QuerySet): def update(self, *args, **kwargs): print('updating..') ### only prints once! obj = self.first() if obj.id: before = File.objects.get(pk=obj.id) if before.import_started == True and obj.import_finished == True: # send_email() print('Complete!') super(FileQuerySet, self).update(*args, **kwargs) class File(models.Model): objects = FileQuerySet.as_manager() name = models.CharField(max_length=100) import_started = models.BooleanField(default=False) import_finished = models.BooleanField(default=False) def __str__(self): return str(self.id) starttasks/views.py from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.http import HttpResponse from starttasks.models import File channel_layer = get_channel_layer() def start_task_c(request, file_id): qs … -
Output ASCII art to console on succesfull pytest run
I'm using pytest to run tests in Django project. I'm using pytest.ini where DJANGO_SETTINGS_MODULE is defined, so I run tests with just: pytest Now, I want to add some ASCII art to the console output if the test run is successful. I know I can do: pytest && cat ascii_art.txt But I want to hide the ASCII art to config or somewhere else so that I keep running tests with just pytest. I don't see any pytest config option I can use. Any other ideas how this could be done? -
Django Serializer not showing related fields
I can't get the State field to appear in the result. Don't know why. My model: class City(models.Model): city_id = models.AutoField(primary_key=True) city = models.CharField(max_length=100, blank=True, null=True) state = models.ForeignKey('State', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'city' def __str__(self): return self.city class State(models.Model): state_id = models.AutoField(primary_key=True) state = models.CharField(max_length = 10, blank=True, null=True) class Meta: managed = False db_table = 'state' My serializer: class StateSerializer(serializers.ModelSerializer): class Meta: model = State fields = ('state_id', 'state') class CitySerializer(serializers.ModelSerializer): state = StateSerializer(source='state_set', many=False, read_only = True) class Meta: model = City fields = ('city_id', 'city', 'state') My Views: class CityList(APIView): # Return all the cities def get(self, request): cities = City.objects.all() serializer = CitySerializer(cities, many=True) return Response(serializer.data) def post(self): pass My result JSON: [ { "city_id": 242, "city": null }, { "city_id": 754, "city": "CARY" }, { "city_id": 2085, "city": "FROM YOUR" },... How can I get the state field to appear in the JSON result? Can someone help? I got several tables like this. -
Create model using Abstract model with approve system
I'm going to use https://github.com/ghdpro/animesuki/tree/master/animesuki/history and modify it under myself, but I stopped at one point which I am not able to jump with my skills .. The point is that if I am a superuser, or I have the permissions given in this model, it adds to my main model Movie record, and if it adds without permissions, it is added only to ChangeRequest, my question is how to do that after the approved added to the main Movie model, and when accepting and changing the field, updated the data in the given object. It works more or less as I want, but I can not jump this step .. I do not need the whole solution, but only tips, or some source code from which I can learn how to do that -
How to add Custom Django widget that adds jQuery Grid Manager drag and drop editing feature to a Django TextArea
How can I create a custom Django widget that adds jQuery Grid Manager drag and drop editing feature to a Django TextArea saves html to TextArea field upon save. Something similar to http://neokoenig.github.io/jQuery-gridmanager/demo/foundation.html. -
Django - No such table: main.auth_user__old
I was following the first app tutorial from the official Django docs and got this error when trying to save some changes made through the admin page. I did some research on it, but the possible solutions I was able to find, such as migrating the db, simply won't work. Just let me know if you want to see some specific part of my code. Following is error: OperationalError at /admin/polls/question/1/change/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/polls/question/1/change/ Django Version: 2.1.4 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: /Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /Users/gfioravante/Projects/test_app/ta_env/bin/python3 Python Version: 3.7.1 Python Path: ['/Users/gfioravante/Projects/test_app/test_app', '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages'] Server time: Wed, 5 Dec 2018 16:45:00 +0000 and the traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/polls/question/1/change/ Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response … -
update checkout log without leaving the page
my check in is as automatic and my checkout as None, and I wanted the page to update register inside the html, I put a button checked and when I click on it that the checkout was updated with the current time and it was already filled in the form, without needing leave the page I tried and I can not make the mistake Model.py PAGO_CHOICES = ( ('Não', 'Não Pago'), ('Sim', 'Pago') ) class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=True, blank=False, null=False,) checkout = models.DateTimeField(default=None, null=True, blank=True) email = models.EmailField(blank=False) placa = models.CharField(max_length=7, blank=False) modelo = models.CharField(max_length=15, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) views.py @login_required def movrotativos_update(request, id): data = {} mov_rotativo = MovRotativo.objects.get(id=id) form = MovRotativoForm(request.POST or None, instance=mov_rotativo) data['mov_rotativo'] = mov_rotativo data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() return redirect('core_lista_movrotativos') else: return render(request, 'core/update_movrotativos.html', data) html. {%extends 'basenew.html' %} {% load bootstrap %} {% block main %} <main role="main" class="col-md-12 ml-sm-auto col-lg-10 px-50"> <br> <br><br> <div class="row"> <div class="col"> <h2>UpDating MovRotativos: {{ mov_rotativo}}</h2> <form action="{% url 'core_movrotativos_update' mov_rotativo.id %}" method="POST"> {% csrf_token %} {{form|bootstrap}} <table class="table table-bordered sortable" > <thead class="p-3 mb-2 bg-primary text-white"> <tr> <th scope="col">Horas</th> <th scope="col">Pagar</th> </tr> … -
Redis: Background saving error with default configuration
I have a Django app in a Docker container; there is also a Redis container. Redis is being used for caching, nothing else. docker-compose.yml: redis: image: "redis:4.0.6-alpine" ports: - "6379:6379" volumes: - redis_data:/data volumes: redis_data: As you can see, there is no redis.conf file, so it uses the default Redis config. I am getting errors in my Docker container: 1 changes in 3600 seconds. Saving... Background saving started by pid 169 Failed opening the RDB file root (in server root dir /etc/crontabs) for saving: Permission denied Background saving error After this my gunicorn process times out and I get a 502 Bad Gateway error. Since I am using Redis only for caching, not for any scheduled tasks, I'm not sure why this task is running. Is it safe to disable it, and if so, how? -
Return Uploaded File after processing it back to user in Django
Hello I am new to Django. I have made a form via which I upload a file to the server. This form also calls a function using the action={% url app:viewfunctionurl %}. I want to process the file (Encrypt) then return that encrypted file without storing it in the DB. How do I do that ? -
Django - update field whose name given dynamically
I am creating an API in Django to update a table. I have a table in following format with time field as string. time P_1 P_2 P_3 ---- --- --- --- 22:00 1 0 0 05:34 0 1 1 The input field will be "entry_time" = {"P_1":["22:10","04:34"], "P_2":["04:34"] } How can I achieve this? I tried many places but I dint find solution to pick the field name of model in runtime and update that field or create new entry if it is not there. Please help. -
Django multiple primary keys for table error
My Django application is working just fine on localhost, but when I try to push it to Heroku I get the following error: remote: django.db.utils.ProgrammingError: multiple primary keys for table "Clientes_productlist" are not allowed My models.py file is: class ProductList(models.Model): id_new = models.IntegerField(primary_key=True) sku = models.CharField(max_length=200) client = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) class Meta: unique_together = (('sku', 'client'),) I am using django-import-export package as well. Therefore, my resources.py is: class ProductListResource(resources.ModelResource): class Meta: model = ProductList skip_unchanged = True report_skipped = True exclude = ('id',) import_id_fields = ('sku', 'client',) fields = ('sku', 'client', 'name', 'description', 'storage', 'cost_price', 'sell_price', 'ncm', 'inventory',) What is causing that error and how can I solve it? -
Django CreateView: automatically set two foreign key fields in a form
I have a model called "Booking" where events are booked between a user and an expert. I'm trying to set the booking CreateView to automatically know the current user and the expert who's profile the user was visiting so that these two users do not need to be selected from dropdown menus in the booking form. I am able to do this successfully for the current user by overriding the form_valid method, but not sure how to do this for the expert. models.py: class Booking(models.Model): user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE) expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings') title = models.CharField(max_length=200, default='Video call with ..', null=True) start_time = models.DateTimeField('Start time', null=True) end_time = models.DateTimeField('End time', null=True) notes = models.TextField('Notes', help_text='Please provide some detail on what you would like to learn or discuss', blank=True, null=True) views.py: class BookingView(CreateView): model = Booking form_class = BookingForm def form_valid(self, form): form.instance.user = self.request.user return super(BookingView, self).form_valid(form) urls.py: urlpatterns = [ #path('', include('booking.urls')), path('signup/', views.SignUp.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(), {'authentication_form': LoginForm}, name='login'), path('profile/', views.view_profile, name='profile'), path('profile/<int:pk>/', views.view_profile, name='profile_with_pk'), path('profile/<int:pk>/booking/', BookingView.as_view(), name='user_booking_new'), path('profile/edit/', views.EditProfileView, name='edit_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've tried setting "form.instance.expert" to the form_valid method, but it didn't work. Thanks. -
running Django migrations via Fabric gives different results
We run makemigrations and migrate on deploy, via Fabric (migration files aren't committed to the codebase). However, this doesn't seem to be creating migrations for some apps. Running the same migration commands manually, SSH'd directly onto the server myself, results in different (correct) output. For example, Fabric runs the following: ./manage.py showmigrations --plan --settings=project.settings.dev_en Which results in the following output (I've truncated it a bit for brevity): [X] contenttypes.0001_initial [X] auth.0001_initial [X] admin.0001_initial If I SSH into the server (using the same user Fabric does) and run it manually, the exact same command produces (again, snipped a bit to keep it short): [X] contenttypes.0001_initial [X] auth.0001_initial [X] accounts.0001_initial [X] accounts.0002_userprofile_gq_questions_user_type [X] accounts.0003_auto_20170720_0742 [X] admin.0001_initial The migrations for the accounts app have been omitted (several other apps have the same issue). Similarly - and more significantly - running makemigrations via Fabric results in "No changes detected" but running it manually results in a migration file being correctly created for the affected app/s. Some stuff I've checked: The affected apps are in INSTALLED_APPS. They contain a migrations directory that's writable by the user that Fabric connects as. The django_migrations table correctly reflects the contents of the various migrations folders. Fabric is cding … -
No module named 'django.db.backends.mysql.compiler'
I have this strange error since we upgrade from Django 1.11.5 to Django 2.1.3 (python 3.5.2). We use MySQL 5.7.24. The latest packages installed are: django-mysql==2.4.1 mysqlclient==1.3.14 We also use Celery: celery==4.2.1 django-celery-beat==1.3.0 django-celery-results==1.0.4 The bug occurred only when we execute a celery task (perform_display_ads_check). It works if we ran the function without .delay(). Here is code for this task: @shared_task def perform_display_ads_check(): try: checker = DisplayAdsCheck() checker.check_all() except Exception as e: logger.exception(str(e)) message = 'Cannot check display ads. Reason: {}'.format(str(e)) send_slack_message.delay(message=message) raise Reject(requeue=False) send_slack_message.delay(message=message) works. There is no database involved for this one. Here is the log: [2018-12-05 09:51:47,626: WARNING/ForkPoolWorker-1] Task clients.tasks.display_ads_check.perform_display_ads_check[535c8b34-5cf4-48e0-a16d-a22b5979f38b] reject requeue=False: None Traceback (most recent call last): File "/home/tool/www/project/clients/tasks/display_ads_check.py", line 26, in perform_display_ads_check checker.check_all() File "/home/tool/www/project/clients/tasks/display_ads_check.py", line 38, in check_all clients = self.process() File "/home/tool/www/project/clients/tasks/display_ads_check.py", line 81, in process for client in clients_qs.iterator(): File "/home/tool/.virtualenvs/tool_py3/local/lib/python3.5/dist-packages/django/db/models/query.py", line 50, in __iter__ File "/home/tool/.virtualenvs/tool_py3/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 256, in get_compiler File "/home/tool/.virtualenvs/tool_py3/local/lib/python3.5/dist-packages/django/db/backends/base/operations.py", line 316, in compiler File "/home/tool/.virtualenvs/tool_py3/lib64/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked ImportError: No module named 'django.db.backends.mysql.compiler' During handling of the above exception, another exception occurred: … -
Django: download dynamic website to pdf by pdfkit
in my project I need to download converted html website to pdf. Site is generated for special id of my object I want. On index site there is a table with objects I have in database and after I click on view button it's moving me to generated website for my object I chose. And this is my generated site for this object Here is my url.py from django.urls import path from . import views app_name = 'kolos' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('view/<int:pk>/', views.EgzamView.as_view(), name='view'), ] Views.py from django.views import generic from django.http import HttpResponse from django.template import loader from django.template.loader import get_template from .models import Question,Egzam,Answer import pdfkit class IndexView(generic.ListView): template_name = 'kolos/index.html' context_object_name = 'egzam_list' def get_queryset(self): return Egzam.objects.all() class EgzamView(generic.DetailView): model = Egzam template_name = 'kolos/egzam.html' def pdf(request, id): projectUrl = request.get_host() + '/kolos/view/'+id pdf = pdfkit.from_url(projectUrl, False) If someone would tell me what should I do because im stuck at this moment with this and don't know how to make this :( -
Read xlsx upload via Django
I'm uploading files (xlsx) via my website and I think the files are being correctly uploaded. def upload_file(request): print('here',request,request.method,request.FILES) if request.method == 'POST': file_json= convert_xlsx_to_json(request.FILES['file_query']) return render(request, 'drax_internal_dbs/drax_success_reactions.html', {'xlsx_file':file_json}) return render(request, 'drax_internal_dbs/no_results.html') This is my file: <WSGIRequest: POST '/drax_output.html'> POST <MultiValueDict: {'file_query': [<InMemoryUploadedFile: calcitriol_2.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}> When I try to read the file, I'm running into lots of issues. I'm using .read() to get the data and would like to convert it into a dataframe. The issues appear here, I don't know how to convert the data? I've been googling all day and still can't find a solution. Here's what I've tried so far: Convert file into StringIO and use openpyxl.load_workbook Convert file into BytesIO and use openpyxl.load_workbook Use pandas.read_csv(file_contents=file.read()) And possibly other ways that I can't remember right now. I don't want to save the file, as I will just use it to generate a table in HTML. Thanks! -
paramiko SSH failing when run as web server
I am trying to use Paramiko to make an SSH communication between 2 servers on a private network. The client server is a web server and the host server is going to be a "worker" server. The idea was to not open up the worker server to HTTP connections. The only communication that needs to happen, is the web server needs to pass strings to a script on the worker server. For this I was hoping to use paramiko and pass the information to the script via SSH. I set up a new user and created a test script in Python 3, which works when I run it from the command line from my own user's SSH session. I put the same code into my Django web app, thinking that it should work, since it tests OK from the command line, and I get the following error: Server 'worker-server' not found in known_hosts Now, I think I understand this error. When performing the test script, I was using a certain user to access the server, and the known hosts information is saved to ~/.ssh/known_hosts even though the user is actually a 3rd party user created just for this one job. … -
How to add custom constraints to ForeignKey relationships in django
Say I wanted to add an extra attribute to the ForeignKey relationship in django to allow further customization. Say for instance I want to add an attribute which when enabled will not allow repetitions ( I realize this particular use case already has a fix but it's just an example). How would I approach such a thing? -
How to set a value according to another one selected in django admin
I need to save in Artigo table a sequence value according to the Lei associated like in this picture: If lei_id is 1, so for each Artigo added it must be add in sequence from 0 in id_artigo_lei field. If lei_id is 2, so for each Artigo added it must be add in sequence from 0 in id_artigo_lei and so forth.. Those data are inserted in django admin. That's my model: class Lei(models.Model): name = models.CharField('Nome', max_length=100) class Artigo(models.Model): artigo = models.TextField('Artigo') id_artigo_lei = models.IntegerField('Artigo Lei', blank=True, null=True) lei = models.ForeignKey(Lei, on_delete=models.CASCADE, verbose_name='Lei', related_name='artigos') ps: I remove some columns from Artigo table just to simplify.. -
redirect problems for views on the same page
I have a refresh registration page, but I want it when I click the checkout button it saves this option and reloads the same page to update values for billing. When I am clicking checkout it saves, but it goes to the page 'core/update_movrotativos.html' e not to 'core_movrotativos_checkout' even when I switch to the two options as 'core/movrotativos_checkout.html' even so it goes only to the 'core/update_movrotativos.html' @login_required def movrotativos_update(request, id): data = {} mov_rotativo = MovRotativo.objects.get(id=id) form = MovRotativoForm(request.POST or None, instance=mov_rotativo) data['mov_rotativo'] = mov_rotativo data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() return redirect('core_lista_movrotativos') else: return render(request, 'core/update_movrotativos.html', data) @login_required def movrotativos_checkout(request, id): data = {} mov_rotativo = MovRotativo.objects.get(id=id) form = MovRotativoForm(request.POST or None, instance=mov_rotativo) data['mov_rotativo'] = mov_rotativo data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() return return redirect('core_movrotativos_checkout') else: return render(request, 'core/update_movrotativos.html', data) htlm <form action="{% url 'core_movrotativos_checkout' mov_rotativo.id %}" method="POST"> <button type="submit" class="btn btn-primary">Checkout</button> </form> -
i cannot login to the page
iam trying to create a login page for users whom i have created using django admin can login. But by the below code i cannot login i.e after clicking login button im not being redirected to the page i have given. forms1.py from django import forms class UserForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'placeholder': 'Password'})) fields = ['username', 'password'] views.py def Userform(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] password = userObj['password'] user = authenticate(Username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/user/') else: form = UserForm() return render(request, 'index.html', {'form' : form}) urls urlpatterns = [ path('admin/', admin.site.urls), path('user/',user), path('login/',Userform), ] index.html <form class="login-form" method="post" action=""> {% csrf_token %} {{ form.as_p }} <button type="submit">login</button> </form> -
Creating a Staff Tracker Webapp - initial ideas
I am starting a new project where I am building a staff tracker tool that keeps track of where employees are when they are at a client or bench. I will be using Django as my framework and Postgresql as my database. I have some experience with coding using Django building a search tool but not with calendars. This is the first design we have: How to implement a calendar like that When a date is chosen(clicked), two drop down lists appear to select "Client" and "Location" How to implement a range of dates so i can do a bulk update e.g. start: 01/01/2019 end: 01/05/2019, and whatever client and location has been selected would be saved across those dates -
Annotate a LineString onto a GeoDjango queryset
For a given user, I'm trying to find out the other users who drive closest to them. For carpooling. Here are my abbriviated models: class Office(models.Model): location = PointField(srid=4326, geography=True) class User(models.Model): office = fk(Office) home_location = PointField(srid=4326, geography=True) In my head, I need to do a few things: Annotate on a LineStringField of F('home_location')→F('office__location') to represent an as-the-crow-flies route to work. Annotate on the shortest distance for each route from the given user's home_location. Sort by that distance, desc. It looks simple on paper but I'm stumbling at the first hurdle. How do I annotate on a LineStringField? This seems like it would be a very common problem for anybody using GIS in Django.