Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery Beat Task Hangs With Out Any Errors
I have a Django app, and I'm using Celery Beat to run a task periodically. If I call the task when running Celery, it runs without errors: app/tasks.py ... @task(name='task1') def func(): # Some code func.run() ... If I then start Celery celery -A project worker -l info, the task runs without errors. The issue comes when I try to run that same task with Celery Beat, imagine I have this schedule: app.conf.beat_schedule = { 'some_task': { 'task': 'task1', 'schedule': crontab(minute=30, hour='22') } } This task should run every day on 22:30, and it does, the task starts but then hangs without logging anything, I cannot figure out the root of the issue, this is not a memory error, I have already checked that, and the task runs fine on my local machine using Celery Beat. I have also tried to use Celery Beat Daemon, but the task keeps hanging whenever it starts. I can't figure out what is happening, any suggestions? -
CSS SVG BackGround image in Django
i used en template who use bootstrap 5, in the css i can find : background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'/><path fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/></svg>"); it seems django don't find this url The bootstrap 5.0 css for select form didn't work and show a standard select box not a bootstrap 5 look . thx for help -
Heroku not actually copying static files over?
I recently changed the directory structure of my django app, which has forced me to set DISABLE_COLLECTSTATIC and specify collectstatic to run on release. Looking at the deployment logs- I see nothing wrong: /app/.heroku/python/lib/python3.8/site-packages/environ/environ.py:637: UserWarning: Error reading /app/.env - if you're not configuring your environment separately, check this. warnings.warn( Adding $DATABASE_URL to default DATABASE Django setting. Adding $DATABASE_URL to TEST default DATABASE Django setting. Applying Heroku ALLOWED_HOSTS configuration to Django settings. Applying Heroku logging configuration to Django settings. Adding $SECRET_KEY to SECRET_KEY Django setting. 548 static files copied to '/app/static', 1574 post-processed. However, when I try to go to my site, I am unable to access any static files. Additionally, if I open a shell into heroku with heroku run bash, the static directory (I have an empty static directory committed to git) is completely empty. So heroku says that it copied over the static files, but as far as I can tell- it did not. Does anyone have an ideas on how this could be happening? I am using webpack and whitenoise to serve the static files. -
App not compatible with buildpack , django heroku
Using buildpack: heroku/python but still it says not compatible Please Help i am a beginner in django Here is build log : -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed And here is the project :https://github.com/Shadow-Knight503/Meme_Site -
when i install wagtailtrans it shows error
Moving to c:\users\hp\appdata\local\programs\python\python39\lib\site-packages\pil from C:\Users\hp\AppData\Local\Programs\Python\Python39\Lib\site-packages~il Moving to c:\users\hp\appdata\local\programs\python\python39\lib\site-packages\pillow-8.3.2.dist-info from C:\Users\hp\AppData\Local\Programs\Python\Python39\Lib\site-packages~illow-8.3.2.dist-info ERROR: Command errored out with exit status 1: 'c:\users\hp\appdata\local\programs\python\python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\hp\AppData\Local\Temp\pip-install-r132d9vs\pillow_2201a7b052fc4b8aa3f08901eaf540e4\setup.py'"'"'; file='"'"'C:\Users\hp\AppData\Local\Temp\pip-install-r132d9vs\pillow_2201a7b052fc4b8aa3f08901eaf540e4\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\hp\AppData\Local\Temp\pip-record-ll058sa9\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\hp\appdata\local\programs\python\python39\Include\Pillow' Check the logs for full command output. -
Django ORM bulk create_or_update + delete not updated
class Item(Model): article = CharField owner = ForeignKey(User) price = IntegerField stock = IntegerField Hello, pls me help with bulk create_or_update_or_delete logic. I have an Items in db. Then I have a new list of items. items = (Item, Item, Item...) but without price field i want to bulk create items that already not in DB (using article and owner) with price = Null bulk update existing items(but not update price) bulk delete those items, that previously existed in db, but not updated in step 2. I know how to bulk create_or_update but idk how to add in step 3 and make all of that efficient. I cant just delete all owner's items and then bulk_create cuz I lost price data. -
Undesired/wrong URL using Django Paginator
I'm trying to use Django Paginator in my webpage but the generated URL is wrong Here is my code: <div class="row"> <div class="col-auto"> <ul class="pagination"> {% if tickets.has_previous %} <li class="page-item"><a class="page-link" href="{{current_uri}}?p=1">&lt;&lt;</a></li> <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{ tickets.previous_page_number }}">&lt;</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="">&lt;&lt;</a></li> <li class="page-item disabled"><a class="page-link" href="">&lt;</a></li> {% endif %} {% for page_number in tickets.paginator.page_range|pagination_limit:tickets.number %} {% ifequal tickets.number page_number %} <li class="page-item active"><a class="page-link" href="{{current_uri}}?p={{page_number}}">{{page_number}}</a></li> {% else %} <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{page_number}}">{{page_number}}</a></li> {% endifequal %} {% empty %} No pages {% endfor %} {% if tickets.has_next %} <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{ tickets.next_page_number }}">&gt;</a></li> <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{ tickets.paginator.num_pages }}">&gt;&gt;</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="">&gt;</a></li> <li class="page-item disabled"><a class="page-link" href="">&gt;&gt;</a></li> {% endif %} </ul> </div> <!-- .col-auto --> </div> <!-- .row --> And this is what happened: Let's say I visit my webpage, example.com and by default the pagination page is 1. If I click on page 2, I'll get this url: https://example.com/tasks/?p=2 If I click on page 3, this is the generated url: https://example.com/tasks/?p=2?p=3 Which is wrong, and it should be: https://example.com/tasks/?p=3 Also if I click back to page 1, I'm getting this url: https://example.com/tasks/?p=2?p=3?p=1 I would like to know how … -
How to assign specific groups to users on Registration in Django
I am new to Django. I am developing a school online app. I have few user groups like sectional-head, teacher, subject-leader, class-monitor, etc. I need to let the user to choose their group and assign each user to these groups at the time of registration. I don't know-how. Please help me to learn this. Thanks. This is my view. def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user_group = Group.objects.get(name='group_name') user.groups.add(group) username = form.cleaned_data.get('username') messages.success(request, f'Profile details updated {username}.') return redirect ('login') else: print(form.errors) # return redirect ('login') group = Group.objects.all() context = { 'group': group, 'form':form } return render (request, 'register.html', context) this is my form from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] My template <form method="POST" action=""> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <select name="user-group" > {% for group in group %} <option value="1">{{group.name}}</option> {% endfor %} </select> {{group.name}} </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> {{form.username}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> {{form.password1}} … -
<built-in function imread> returned NULL without setting an error in django views
i want to create a qr scanner in django.for that i have a model with a field call "image" and a form views.py: @login_required def scan_qr(request): if request.method == 'POST': form = QrScannerForm(request.POST,request.FILES) if form.is_valid(): scanner = form.save(commit=False) scanner.save() image = scanner.image print(scanner) print(image) img=cv2.imread(image) det=cv2.QRCodeDetector() val, pts, st_code=det.detectAndDecode(img) print(val) return HttpResponseRedirect(val) else: form = QrScannerForm() return render(request,'profile/scan_qr.html',{'form':form}) i am getting the image but the line is not working "img=cv2.imread(image)" it is throwing error " returned NULL without setting an error" how can i fix this ? -
image upload works locally, but the deployed version on heroku crashes, paartial credentials messing
i have a python/django project deployed on heroku with aws s3 image upload, I can upload the image and post them on the website locally, but the deployed version on heroku is givinig me that error PartialCredentialsError at /teams/1/add_photo Partial credentials found in env, missing: AWS_SECRET_ACCESS_KEY I have the configuration file on my computer and it works locally with both aws_Secret_id & AWS_SECRET_ACCESS_KEY any help with that?! -
Why does django cache.set() store weird characters
When I save the string via django's cache framework from django.core.cache import cache cache.set('host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13', ""brown.example.com:8006") And try to get the value out: 127.0.0.1:6379> get :1:host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13 "\x80\x05\x95&\x00\x00\x00\x00\x00\x00\x00\x8c\"brown.example.com:8006\x94." I get some weird characters around it, why is that and how to make it not do it? -
Django set formset with current user
Django 3.2.7 I have a form that contains multiple inlineformset_factory formset. For all my models, they all have a meta field call created_by. Only the main form Person's created_by is filled by current user. For all the formsets (emailfs, imagefs), it did not set their created_by with current user. How can I do that? Here is my views and my 7 different failed approaches. # views.py class PersonCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): ... model = Person form_class = PersonForm def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) if self.request.POST: context["emailfs"] = PersonEmailFormSet( self.request.POST, self.request.FILES ) context["imagefs"] = PersonImageFormSet( self.request.POST, self.request.FILES ) # Method 6 # context["imagefs"] = PersonImageFormSet( # self.request.POST, self.request.FILES, user=self.request.user # ) # Method 7 # context["imagefs"] = PersonImageFormSet( # self.request.POST, self.request.FILES, form_kwarg={'created_by': self.request.user} # ) else: context["emailfs"] = PersonEmailFormSet() context["imagefs"] = PersonImageFormSet() return context def form_valid(self, form): form.instance.created_by = self.request.user context = self.get_context_data() emailfs = context["emailfs"] imagefs = context["imagefs"] personfs = [emailfs, imagefs] if ( form.is_valid() and all(fs.is_valid() for fs in personfs) ): self.object = form.save() for fs in personfs: # Method 1 # fs.created_by = self.request.user # Method 2 # self.created_by = self.request.user fs.instance = self.object # Method 3 # fs.created_by = self.request.user # Method 4 # fs.instance.created_by = … -
how can I get the id of the object from Subjects model?
I want to associate a post for that certain object in the subject's model but I can't figure it out (error in views.py). Your help is appreciated for a beginner like me. models.py class Subjects(models.Model): title = models.CharField(max_length=200) slug = AutoSlugField(populate_from=['title'], max_length=250, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.title}" @property def posts(self): return Post.objects.filter(subject=self) class Post(models.Model): subject = models.ForeignKey( Subjects, on_delete=models.CASCADE, related_name='subject_model') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views.py class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'post/post_create.html' model = Post fields = ['body'] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user form.instance.subject_id = self.kwargs['id'] # error here form.save() return super(PostCreateView, self).form_valid(form) urls.py urlpatterns = [ path('', views.CourseList.as_view(), name='course_list'), path('create_subject', views.SubjectCreateView.as_view(), name='create_subject'), # register path('register/', views.register, name='register'), # detailview path('<int:id>/', views.SubjectDetailView.as_view(), name='subject-detail'), # post create view path('post/new/', views.PostCreateView.as_view(), name='post-create') ] error KeyError at /post/new/ 'id' -
How can I pass a page param in Django url template tag?
I'm creating a simple search application. I have a model with some data, and the index page is just a search bar that search results of that model. I'm creating the form using just HTML, not a proper Django Form. index.html: <form method="get" action="{% url 'core:search' %}?page=1&q={{ request.GET.q }}"> <div class="form-floating mb-3"> <input type="search" class="form-control" id="floatingInput" name="q" value="{{ request.GET.q }}"> <label for="floatingInput">Type your search</label> </div> <button class="w-100 btn btn-lg btn-primary" type="submit">Search</button> </form> The results are paginated, so I need that the url requested by the form is http://127.0.0.1:8000/search/?page=1&q=query, query being the search term typed in the input. But what I wrote in the action parameter in the form doesn't work as I expected: even though it's writen action="{% url 'core:search' %}?page=1&q={{ request.GET.q }}, the URL requested is just http://127.0.0.1:8000/search/?q=query. The page param simply doesn't show up. I wrote page=1 because, as is the search result, the first one requested is always the first page. The view that process this request is the search_view. I'm putting it below just as more info, but I think the problem is my misunderstanding of url template tag in the action form parameter. search_view: def search_view(request): posts = Post.objects.all() query = request.GET.get('q') page_num = request.GET.get('page') … -
How to know when testing? Django
i'm writing tests for a django app and i need to know whether a view is in a test. # views.py class SomeClass(View): def get(self, request): # how to know if this view is called by test? Thank you! -
getting specific errors type message from HTTPError while working django +firebase
i was trying to make signup page using django and while using the ff code user = auth_.create_user_with_email_and_password(email, password) while reaching this point it throws different errors depending on user input like if user input short password less than 6 characters and also if email is already registered .... with same code error 400 and i need that message to to identify the specific error and display the error back here is the message : [Errno 400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyBmnhaFGTVelDMkPQ3pjvdPMQc28c-JrTs] { "error": { "code": 400, "message": "WEAK_PASSWORD : Password should be at least 6 characters", "errors": [ { "message": "WEAK_PASSWORD : Password should be at least 6 characters", "domain": "global", "reason": "invalid" } ] } } -
How to remove buttons from CKeditor 4 in Django using settings.py
I am trying to remove buttons from CKeditor 4 toolbar from Django's settings.py file I added the following line to CKEDITOR_CONFIGS but it didn't work 'removeButtons' : ['Underline,JustifyCenter'], The CKEDITOR_CONFIGS lines: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here 'toolbarGroups': [ # { 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }, # { 'name': 'clipboard', 'groups': [ 'clipboard', 'undo' ] }, # { 'name': 'editing', 'groups': [ 'find', 'selection', 'spellchecker' ] }, # { 'name': 'forms' }, { 'name': 'basicstyles', 'groups': [ 'basicstyles', 'cleanup' ] }, { 'name': 'paragraph', 'groups': [ 'list', 'indent','align' ] }, { 'name': 'links' }, { 'name': 'insert' }, { 'name': 'styles'}, # { 'name': 'colors' }, # { 'name': 'tools' }, # { 'name': 'others' }, # { 'name': 'about' } ], # 'removeButtons' : ['Underline,JustifyCenter'], # 'height': 291, # 'width': '100%', # 'filebrowserWindowHeight': 725, # 'filebrowserWindowWidth': 940, # 'toolbarCanCollapse': True, # 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML', 'tabSpaces': 4, 'extraPlugins': ','.join([ 'uploadimage', # the upload image feature # your extra plugins here 'div', 'autolink', 'autoembed', 'embedsemantic', 'autogrow', # 'devtools', 'widget', 'lineutils', 'clipboard', 'dialog', 'dialogui', 'elementspath' ]), } } -
Djano annotate with subtract operation returns None when the subtrahend is None
My objective is to get the balance for a billing instance by subtracting the payments posted within the period. In my Billing model, I have a backlog field that contains the backlogs from previous period. The Billing model has m2m relationship with Payment model through PaidBills model. In my queryset: ''' qs = Billing.objects.filter( bill_batch=prev_batch, balance__gt=0).annotate( payment=Sum('paidbills__amount_paid', filter=Q( paidbills__pay_period=batch.period))).order_by( 'reservation__tenant__name', 'reservation__apt_unit').only( 'id', 'bill_batch', 'reservation') qs = qs.annotate(new_bal=F('backlog') - F('payment')) ''' The result is correct when the expression F('payment') contains a value, but will give a result None when F('payment') returns None. I have tried to replace the expression F('payment') with any fixed value, say 5000, and it worked as expected. How to go about this? (Django 3.2.7, Python 3.9.5) -
error: Table <name_table> dosen't exist in mysql (The Django)
I have created successfully a database and data table in MySQL by command line, but until retrieving the table then It's doesn't exist (I using the Django framework), and when checking in the database, the data table doesn't. Can anyone help me, please, thanks in advance enter image description here enter image description here enter image description here -
Python - Invalid Syntax - Why is this error being thrown?
I already know that this is going to be a trashy question, as per the SO question guidelines, but I have to keep details down to a minimum. I have a traceback, but I don't know why its throwing an error. Traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "...USER...\threading.py", line 954, in _bootstrap_inner self.run() File "...USER...\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "...USER...\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "...USER...\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "...USER...\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "...USER...\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "...USER...\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "...USER...\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "...USER...\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "...USER...\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "...USER...\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "...USER...\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen … -
How can I do a multi file upload in Django, allowing user to remove file upload before form submission?
I am trying to do a fairly common user requirement, allowing the user to upload multiple files in Django, and giving them the option to remove files that they may have accidentally uploaded. As far as I can tell, even if the user remove the uploaded files from the DOM prior to the user submitting the form via Javascript code as shown here...Multiple file upload - with 'remove file' link, the uploaded files remain in the request.FILES.getlist(''). I have spent most of today researching this. I have in fact determined that when the uploaded files are deleted via Javascript from the DOM they are in fact still present in the request.FILES.getlist(''). I verified this by printing out the contents of the getlist file in my CreateView as shown below... list=[] #myfile is the key of a multi value dictionary, values are the uploaded files for f in request.FILES.getlist('files1'): #myfile is the name of your html file button filename = f.name print(filename) My question is how can I get the contents of the DOM and compare it to what's in request.FILES.getlist? I surmise that's how I'll be able to tell Django what's real and what's not. Thanks in advance for any … -
How to make 2 way access verification in django?
I would like to improve security for access, making a 2 way access verification using a code to send to whatsapp or by using a qrcode. Is there any program or library with such a function? -
Django: Why does database login every query?
In my settings.py, I have a database configured. I have a page that issues a sql query against the database defined in settings.py every 10 seconds. I have been using it for 1 year now and never had any issues with it. My database admin ran a login audit on our database. As it turns out, each individual single sql query has a unique login to the database. His audit took 5 minutes to run just today and it is because of my django application logging in. I was pretty surprised to find out that every query that is issues has a unique login attempt to the database. Is there anyway to create a "session" for the backend database in settings.py. I really feel that the application should have a single login and use that session to issue commands. Did I miss a setting to do this? Sql login audit: -
Amazon RDS: OperationalError: (2003, "Can't connect to MySQL server on rds.amazonaws.com (110)"
I have set up a MySQL database and I'm trying to connect it with my application. But I'm getting the above error. My database settings in settings.py are as follows: DATABASES = { 'default': { 'ENGINE': config('db_engine'), 'NAME': config('db_name'), 'USER': config('db_user'), 'PASSWORD': config('db_password'), 'HOST': config('db_host'), 'PORT': config('db_port') } } and my database environment variables are these: db_engine=django.db.backends.mysql db_name=stagingdatabase db_user=staginguser db_password=stagingpassword db_host=somestagingname.somestagingid.us-east-2.rds.amazonaws.com db_port=3306 I know the port is correct, which is the solution for most cases of these types of errors. All other variables are correct as well. I can't ping somestagingname.somestagingid.us-east-2.rds.amazonaws.com even though it's status is available, so there must be an issue in this: -
calculate difference between consecutive numbers in rows af the same model
I am trying to calculate the difference between consecutive numeric values in the odometer_reading field of my model. My Models.py has fields like below: class Refuel(models.Model): vehicle = models.ForeignKey(Vehicle, blank=True, null=True, on_delete=models.SET_NULL) gaz_station = models.ForeignKey( GazStation, related_name=_("Station"), blank=True, null=True, on_delete=models.SET_NULL ) odometer_reading = models.PositiveIntegerField(_("Compteur KM"), blank=True, null=True) snitch = models.PositiveIntegerField(_("Mouchard KM"), blank=True, null=True) fuel_quantity = models.DecimalField(_("Quantitée en Litres"), max_digits=5, decimal_places=1) fuel_unit_price = models.DecimalField(_("Prix en DH"), max_digits=6, decimal_places=2) note = models.CharField(_("Remarque"), max_length=255, blank=True, null=True) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) is_active = models.BooleanField(default=True) @property def total_price(self): total_price = self.fuel_quantity * self.fuel_unit_price return total_price class Meta: ordering = ["gaz_station", "-created_at"] def __str__(self): return self.vehicle.serie I want to use a CBV to get the distance between every two refuel for the same vehicle so I can calculate fuel consumption per km. is there a way to do it?