Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a data migration with a overwrote ,save() method model
I am trying to upload some testing data to an app, using the option of the migrations.All the data is storaged in a .Yaml file in the app ans I have some other migrations that runs perfectly uploading all the data. But this one has a problem. In this model (Transactions) I created 3 self-writen, fields that are calculated when calling to the save() method. This process run perfectly when I sent the data through the View. But when I send it through the migration, fails as if the save method is not overwritten. I don't know what to do to accomplish the upload as a migration. The migration from django.db import migrations from django.core import serializers def transactions(apps, schema_editor): with open('fixtures/transactions.yaml') as trans: for obj in serializers.deserialize("yaml", trans): t=apps.get_model("acounts", "Transactions")() cat=apps.get_model("acounts","Category") .objects.get(pk=obj.object.category.pk) cuen=apps.get_model("acounts", "Acount").objects.get(pk=obj.object.acount.pk) print(obj) t.tipo=obj.object.tipo t.description=obj.object.description t.monto=obj.object.monto t.date=obj.object.date # t.category=obj.object.category t.category=cat # t.acount=obj.object.acount t.acount=cuen t.save() class Migration(migrations.Migration): dependencies = [ ('acounts', '0002_populate_acounts'), ] operations = [ (migrations.RunPython(transactions)) ] The Model class Transactions(models.Model): TYPE_CHOICES = ( ('GASTO', 'Gasto'), ('INGRESO', 'Ingreso'), ) tipo = models.CharField( choices=TYPE_CHOICES, max_length=20 ) description=models.CharField(max_length=100) monto=models.DecimalField(max_digits=25, decimal_places=2, null=False) category=models.ForeignKey('Category', on_delete=models.CASCADE, null=False) acount=models.ForeignKey('Acount', on_delete=models.CASCADE, null=False) date=models.DateField() total_USD=models.DecimalField( max_digits=25, decimal_places=2, editable=False); total_BTC=models.DecimalField( max_digits=25, decimal_places=9, editable=False); total_BSS=models.DecimalField( max_digits=25, decimal_places=2, … -
How to create a web UI that captures login details?
I have a web based tool (Like PowToons) with only 4 licenses. But the number of users are 12. Only 4 of them can use the tool simultaneously. I want to create a web UI that tracks the user login details to this tool “X” Along with following details: No. of hours the user needs to use “X” : Team Manager’s name: I want to know how can I go about this idea. -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03A69780>
I am currently undergoing a python course and learning how to use Django. I have just created mysite and am currently trying to test the Django server. I ran the command below in the cmd and the output is as follows. C:\Users\Win10\Desktop\Python\Newsite\mysite>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03A69780> Traceback (most recent call last): File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\contrib\admin\filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "C:\Users\Win10\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.11.2-py3.7.egg\django\contrib\admin\options.py", line 12, in <module> … -
sorl.thumbnail is not creating thumbnails in my views
I have installed sorl.thumbnail and added it to my installed_apps. In my view: {% extends 'base.html' %} {%block title%}{{user.get_full_name}}{% endblock %} {%block content%} {%load thumbnail %} <h1>{{user.get_full_name}}</h1> <div class="profile-info"> {% thumbnail user.profile.photo "180x180" crop="100%" as im %} <img src="{{im.url}}" class="user-detail"> {% endthumbnail %} </div> {% with total_followers=user.followers.count %} <span class="count"> {{total_followers}} </span> follower{{total_followers|pluralize}} <a href="#" data-id="user.id" data-action="{%if request.user in user.followers.all %}un{%endif%}follow" class="follow button"> {%if request.user not in user.followers.all %}Follow{%else%}Unfollow{%endif%} </a> <div id="image-list"> {%include 'images/image/list_ajax.html' with images=user.images_created.all %} </div> {% endwith %} {%endblock%} However, the thumbnail tag creates nothing in my view. am I missing something? -
Get all latitude and longitude of one kilometer distance
I want to get all the lat and long of the user with in 1 km distance. For example i have the user current location latitude and longitude i want to find all of his friends with in 1 km distance. User1 current Latitude : '25.276987' User1 current Longitude: '55.296249' Similarly I have all the other users lat and long with me. {'user2':{lat:'25.122212','long':'55.296249'},'user3':{lat:'25.222212','long':'55.396249'}} I want to find all the other users who are in 1 km distance of user1. i tried this but did not help me. Any help would be greatly appreciated. Thanks.. -
On incoming post request, execute a script
With Django, I set up api restful endpoint to accept incoming post data at url below. http://0.0.0.0:1010/api/data/ When someone posts data like shown below using api POST request, I'd like to run a script called test.py when api post is posted. I looked into it and it seems middleware is way to go. What's the best way to structure this? Providing sample code would be great. [ { "number": "1234", "id": "11", }, { "number": "12345", "id": "22" } ] -
How to get id attribute of related object
I have these two models related to each other. I need to create a sub folder to keep my attachment by qa id. but I'm struggling with getting id of the related objects id. Can someone please help? class Qa(models.Model): question_text = models.CharField(max_length=1000, verbose_name='Q') answer_text = models.TextField(blank=True, verbose_name='A') class Attachment(models.Model): qa = models.ForeignKey('Qa', blank=True, null=True, on_delete=models.CASCADE, related_name='files' ) attach_file = models.FileField(upload_to=f'qa_data/{qa_id}/', null=True, verbose_name='Attachment') -
Cannot import name 'update_contenttypes
manage.py runserver_plus 0.0.0.0.80 Traceback (most recent call last): File "manage.py", line 60, in execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/init.py", line 341, in execute django.setup() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/ubuntu/.local/lib/python3.6/site-packages/django/contrib/contenttypes/apps.py", line 7, in from .management import ( ImportError: cannot import name 'update_contenttypes' -
Ho to define vue-router components inside a html?
I'm using django + vue.js + vue-router.js to make my project. I'm trying to use vue-router in a single html page. I searched for a while, all examples are use .vue components, or define the component templates in js part simpely, just like this: <script> const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] ... </script> What I want is define the template outside the js part something like this: <body> <template id="Foo"> <div> this is Foo </div> </template> <template id="Bar"> <div> this is Bar </div> </template> <script> const Foo = { template: '#Foo' } const Bar = { template: '#Bar' } const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] const router = new VueRouter({ routes }) const app = new Vue({ router }).$mount('#app') </script> </body> I tried this, but not work. So how to define vue-router components inside a html? I'm new with vue.. -
QuerySet results being repeated when chaining queries
So I am attempting to chain queries together. This is what I am doing queryset_list = modelEmployee.objects.filter(stars__lte=3) A = len(queryset_list) #A=2 queryset_list = queryset_list.filter(skills__skill_description__in=skill_filter) A = len(queryset_list) #A=4 So with the above I am suppose to get two results but I am getting four. Seems like the results of first query are being duplicated in the second. Any suggestion on why the results are being duplicated and how I can fix this ? I was expecting to get only two items since it passes both the filters. -
How to proxy and stream file upload request via Django to Proxmox?
Let's say I have a Django WebUI to upload a large file (8G) which posts the file to proxmox via API. As far as I am aware Django only posts to the other service once the upload from browser is finished, which results doubling the time of the data transfer. Is there a way to stream the data from browser to proxmox via Django? I had a look at django-channel and presume some imaginary code would be like below but I don't think I will be able to call post with partial data received from websocket: from channels.generic.websocket import WebsocketConsumer import json class UploadConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, data): # how to write partial data block to proxmox via post? Any ideas would be great. -
Data table not populating data in django-datatable-view
I've started a new Django project with trying to test out django-datatable-view. I'm getting a JS error saying Uncaught TypeError: $$.each is not a function. Although following the code on the library's website jQuery is being loaded before datatableview.js. models.py from django.db import models class Post(models.Model): title= models.CharField(max_length=150) body = models.TextField() created = models.DateField() views.py from datatableview.views import DatatableView from .models import Post class MyView(DatatableView): model = Post datatable_options = { 'columns': [ 'title', 'body', 'created', ] } post_list.html {% load static %} <!-- myapp/mymodel_list.html --> <!-- Load dependencies --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <!-- Load js for initializing tables via their server-side options --> <script type="text/javascript" charset="utf8" src="{% static 'js/datatableview.js' %}"></script> <script type="text/javascript"> $(function(){ datatableview.initialize('.datatable'); }); </script> <!-- Render the table skeleton, includes the .datatable class for the on-ready initializer. --> {{ datatable }} Only the table header is being rendered without the data being populated. Any ideas as to what may be going on. As I said most of the answers on here are mentioning that jquery isn't being loaded first but this clearly isn't what is going on in the code above. -
while creating a login page using django I get this error
First I have urls.py inside template folder in users (my app) folder. `"""URLs for app=Users""" from django.urls import path from django.contrib.auth import login from . import views app_name = 'users' urlpatterns =[ # Login page path('login/', login, {'template_name':'users/login.html'}, name='login'), Then I get login() got an unexpected keyword argument 'template_name' this error. So I've been searching on internet for answer and changed it to: from django.urls import path from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns =[ # Login page path('login/', LoginView, {'template_name':'users/login.html'}, name='login'), however I am now getting this error: init() takes 1 positional argument but 2 were given. I have my login.html in a folder named users inside templates folder. Can someone help? Thanks! -
How do I print out ForeignKey models that are linked to a specific model in django?
I am using a django model to save user uploaded images. I want each image to be stored in the productimage model that is a foreign key model to the product model which is a foreign key model to the user model. What I mean is: User -----> Product ------> Productimage I am using for loops to print out all of a users products from the product model. Then for each product in the product model the productimage ForeignKey models linked to that particular product model should be printed out. However when I return the productimage model it returns all the productimage models instead of only the ones linked to that particular product model. To futher clarify my question what I mean is that let's say for ProductA, print out all the Productimages attatched to ProductA but instead of printing all of them out it's printing out all the Productimages regardless of which Product model they are linked to. models.py: class product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=100, blank=True) product_price = models.CharField(max_length=30, blank=True) product_description = models.CharField(max_length=1000, blank=True) class productimage(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) product_images = models.FileField(blank=True) views.py: def products(request): template = loader.get_template("main/products.html") products = request.user.product_set.all() for product in products: … -
Deleting object from table in the same view
I am trying remove a lesson object on my view by clicking a button associated with it called delete in my table. I understand I can do this by having a separate delete view and url where I pass the lesson.id to it. However, I was wondering how to delete an object using a button on the same page. I have attached my code below and would greatly appreciate any help. views.py def schedule(request, lesson_id): if request.method == 'POST': form = LessonForm(request.POST) lesson_gone = Lesson.objects.get(id=lesson_id) lesson_gone.delete() else: form = LessonForm() lessons = Lesson.objects.filter(user=request.user) form = LessonForm storage = messages.get_messages(request) context = {'form' : form, 'lessons' : lessons, 'lesson_gone' : lesson_gone, 'message' : storage} return render(request, 'teacher/schedule.html', context) HTML <tbody> {% for lesson in lessons %} <tr> <td>{{ lesson.lesson_instrument }}</td> <td>{{ lesson.lesson_level }}</td> <td>{{ lesson.lesson_length }}</td> <td>{{ lesson.lesson_date }}</td> <td> <form action="{% url 'teacher:schedule' lesson_id=lesson.id %}" method="POST"> {% csrf_token %} <button type="submit" name="submit" class="btn white_button">Delete</button> </form> </td> </tr> {% endfor %} </tbody> -
"Unexpected keyword argument 'instance' in constructor call" error while calling inlineformset_factory?
It shows error while creating modelformset object with kwargs instance in it. ExamDateFormSet = inlineformset_factory(Exam,ExamDate,form = ExamDateAddForm,extra = 1) and in views.py if request.POST: data ['formset'] = ExamDateFormSet(request.POST, instance = self.object) It gives an error "Unexpected keyword argument in constructor call " -
Pagination: how to set the number of pages?
I have a view for showing the list of news items: def index(request, page_number=1): news_list = get_list_or_404(NewsItem.objects.order_by('-pub_date')) news_paginator = Paginator(news_list, 10) return render(request, 'news/index.html', {'news_list': news_paginator.page(page_number)) As you can see, ten news items are displayed on every page. The template: <div class="paginator"> <ul> <!-- Left arrow --> {% if news_list.has_previous %} <li class="arrow"><a class="no_underline" href="{% url 'news:index' news_list.previous_page_number %}"><b>&larr;</b></a></li> {% else %} <li class="arrow unavailable"><b>&larr;</b></li> {% endif %} <!-- Page numbers --> {% for page in news_list.paginator.page_range %} {% if page == news_list.number %} <li class="current"><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li> {% else %} <li><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li> {% endif %} {% endfor %} <!-- Right arrow --> {% if news_list.has_next %} <li class="arrow"><a class="no_underline" href="{% url 'news:index' news_list.next_page_number %}"><b>&rarr;</b></a></li> {% else %} <li class="arrow unavailable"><b>&rarr;</b></li> {% endif %} </ul> </div> It looks like this: ← 1 2 3 4 5 6 7 8 → Let's imagine there are 217 news items, and I wouldn't like to have 21 page numbers at the bottom of the list. Instead, I'd prefer to set the limit: only 5 page numbers. But this limit has to be stable, there always should be 5 page numbers … -
Django Templates image doesn't display
I am currently having a problem when I upload an image through the admin page, it doesn't display on my templates. It seems like it doesn't recognise where to look for the uploaded image as the src in the images tag is blank when I checked the page source. models.py from django.db import models from django.utils import timezone class post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='blog_pics', null=True, blank=True) Keywords = models.CharField(max_length=100, default= "") def __str__(self): return self.title blogs.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <h2><a class="article-title">{{ post.title }}</a></h2> {% if post.image %} <img class="rounded-square blog-img" src="{{ blog_pics.image.url }}", align="top"> {% endif %} <p class="article-content">{{ post.content }}</p> <small class="text-muted">{{ post.date_posted }}</small> </div> </div> </article> {% endfor %} {% endblock content %} urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index, name='blog-index'), path('about/', views.about, name='blog-about'), path('blogs/', views.blogs, name='blog-blogs'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django restrict user access to related objects
I am writing an application which allows a user to authenticate and view objects only within their organisation. For a generic.ListView, I can restrict access with the code below: models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): organisation = models.ForeignKey('Organisation', null=True, on_delete=models.CASCADE) class Organisation(models.Model): name = models.CharField(max_length=255, unique=True, null=False, verbose_name="Name") views.py class OrganisationList(LoginRequiredMixin, generic.ListView): model = Organisation def get_queryset(self): return Organisation.objects.filter(id=self.request.user.organisation.id) In addition to this view the user will access forms, an API and the django admin interface that require this restriction. For example, user Brett belongs to Kids Incorporated. When he logs in to the admin panel he can currently also see ACME Corporation but should not be able to do so. I have looked at ModelManager interface but I am not sure how to get the user request and override Is there a way to run write one query for all views (DRY) that so that a user will only see their own organisation? -
Django add users as active even though user.is_active is set to False
I am trying to add new users as inactive, so they won't be able to login before confirming their email, but django adds new user as active (as seen through admin account) even though user.is_active is set to false def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() form_data = form.cleaned_data username = form_data.get('username') raw_password = form_data.get('password1') user = authenticate(username=username, password=raw_password) user.is_active = False if user.is_active == False: user.email_confirmed = False -
Install poppler onto Heroku Server django
I am trying to install poppler on my Heroku server because I am using pdf2image as a python package. However, I can't just run brew install poppler like I did on my mac. I have tried to add some heroku buildpacks off the internet but with no luck. Anytime pdf2image runs I get this error. pdf2image.exceptions.PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH? Is there something I can do on the command line to get poppler installed while keeping heroku/python as my buildpack? Thanks! -
Dictionary with nested list TypeError: string indices must be integers
My json response come back with this dictionary. data = {"offset": 0, "per-page": 1, "total": 548, "language": "en", "odds-type": "DECIMAL", "overall-staked-amount": 23428.63548, "profit-and-loss": 4439.61471, "events": [{"id": 1042867904480016, "name": "Gael Monfils vs Daniil Medvedev", "sport-id": 9, "sport- url": "tennis", "sport-name": "Tennis", "start-time": "2019-02- 16T14:29:00.000Z", "finished-dead-heat": false, "markets": [{"id": 1042867905130015, "name": "Moneyline", "commission": 0, "net-win- commission": 0, "profit-and-loss": -0.59999, "stake": 0.59999, "selections": [{"id": "1042867905220015_BACK", "runner-id": 1042867905220015, "name": "Daniil Medvedev", "side": "BACK", "odds": 3.0, "stake": 0.59999, "commission": 0, "profit-and-loss": -0.59999, "bets": [{"id": 1043769075060320, "offer-id": 1043764555430020, "matched-time": "2019-02-16T16:16:18.936Z", "settled-time": "2019- 02-16T16:26:01.878Z", "in-play": true, "odds": 3.0, "stake": 0.59999, "commission": 0, "commission-rate": 2.0, "profit-and-loss": -0.59999, "status": "PAID"}]}], "net-win-commission-rate": 0.02}]}]} I am unable to get the attribute overall-staked-amount and inside the events list I cannot get name from events list. using list comprehension or a for loop. Here's my code. list comp overall_staked = [d['overall-staked-amount'] for d in data] name = [d['name'] for d in data['events'] print(overall_staked,name) for loop for d in data: overall_staked = d['overall-staked-amount'] name = d['name'] print(overall_staked,name) I receive an error TypeError: string indices must be integers what am I doing wrong or need to do? -
django-celery-beat IntervalSchedule.DAYS Periodic Task Time
I have a question regarding the periodic execution time of IntervalSchedule.DAYS, For Example,We know that IntervalSchedule.HOURS executes every given hour from the time periodictask created. ex: if we create an IntervalSchedule.HOURS for every 4 hours at 6AM then it's first execution will be at 10AM . I Would like to know how IntervalSchedule.DAYS works, Does it executes based on the current time or executes at 12 AM in the DAY ? ex: if i create an periodicTask on IntervalSchedule.DAYS for 5 then at what time it will execute on 5th day ? https://django-celery-beat.readthedocs.io/en/latest/ -
How does multiple template rendering work
Trying to display query set in a template. Does not show the objects in my templates/home.html page but shows the objects in templates/posts.html if i set render to return render(request, "posts.html", context) which makes sense but I'm confused why it wouldn't work for return render(request, "home.html", context). Is it because I already render the home.html in my core/views.py? Is there some sort of restriction on multiple rendering of the same template? Does that make sense? my posts/views.py def posts_list(request): # return HttpResponse("<h1> List a posts. </h1>") queryset = Post.objects.all() context = { "object_list": queryset, "user": "username" } return render(request, "home.html", context) my core/views.py def home(request): return render(request, 'home.html') my template/home.html <html> <body> <h1>Homepage</h1> {% if user.is_authenticated %} <h1>What's on your mind, {{ user }}</h1> {% for obj in object_list %} {{ obj.user }} <br /> {{ obj.content }} <br /> {{ obj.timestamp }} <br /> {% endfor %} <a href="{% url 'logout' %}">Logout</a> {% if user.is_admin %} <p><a href="{% url 'administration' %}">Admin</a></p> {% endif %} {% else %} <p>Please <a href="{% url 'login' %}">login</a>.</p> {% endif %} </body> </html> -
Add incrementing integer to queryset each time an object is touched in Django
I'm trying to add an incrementing integer, in this case a unique sequence number ranging from [1,n] where n is the number of sequences in the given schedule. As the sequences will get updated regularly I am wondering what would be the most efficient way to loop through the following Sequence.objects.filter(schedule=schedule).order_by('start', 'id') and assign the incrementing number to each sequence. Also, where would be the ideal place to implement this method if I want it to run every time a new sequence is created, deleted or a sequence is updating the start field. I've been thinking about the save() and delete() method, however I dont wish to update when only other fields in the sequence is updated. This is my sequence model class Sequence(models.Model): number = models.PositiveIntegerField( verbose_name='sequence number', help_text='auto incrementing sequence number', ) schedule = models.ForeignKey( to=Schedule, verbose_name='schedule', on_delete=models.CASCADE, related_name='sequences', help_text='schedule primary key', ) start = models.DateTimeField( verbose_name='start date', help_text='sequence starting datetime', ) end = models.DateTimeField( verbose_name='end date', help_text='sequence ending datetime', )