Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running heroku local results in SyntaxError: invalid syntax
When I run heroku local in terminal it throws this error: 22:01:24 web.1 | File "manage.py", line 17 22:01:24 web.1 | ) from exc 22:01:24 web.1 | ^ 22:01:24 web.1 | SyntaxError: invalid syntax [DONE] Killing all processes with signal SIGINT 22:01:24 web.1 Exited with exit code null I am following this tutorial. Not sure if it helps but here is my Procfile contents: web: python manage.py runserver 0.0.0.0:$PORT My Python version is 3.9.9 -
How do i fix Exception Type:OperationalError Exception Value:no such table: home_user
from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils.html import escape, mark_safe from embed_video.fields import EmbedVideoField class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, password, **other_fields): other_fields.setdefault('is_teacher', True) other_fields.setdefault('is_learner', True) other_fields.setdefault('is_admin', True) if other_fields.get('is_teacher') is not True: raise ValueError( 'admin must be assigned to is_teacher=True.') if other_fields.get('is_learner') is not True: raise ValueError( 'admin must be assigned to is_learner=True.') return self.create_user(email, user_name, first_name, password, **other_fields) def create_user(self, email, user_name, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True,default="") first_name = models.CharField(max_length=150, blank=True) about = models.TextField(( 'about'), max_length=500, blank=True) is_learner = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] def str(self): return self.user_name Admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.forms import TextInput, Textarea from .models import User,Profile,Announcement,Course,Tutorial,Notes,Quiz,Answer,Learner,Instructor,TakenQuiz,LearnerAnswer class UserAdminConfig(UserAdmin): model = User search_fields = ('email', 'user_name', 'first_name',) list_filter = ('email', 'user_name', 'first_name', 'is_teacher', 'is_learner') ordering = ('-start_date',) list_display = ('email', 'user_name', 'first_name', 'is_teacher', 'is_learner') fieldsets = ( (None, {'fields': ('email', 'user_name', 'first_name',)}), … -
How can I do JavaScript ajax call on page onload and retrieve data from views in Django
I wish to pass localStorage data to Django views and display the return record on page template on page load. I think it can be done with Ajax, but I have no Idea how I can pass specific localStorage variable to Django views on specific pageload and display the record on template as regular templating(not ajax html return) For example: If I load abcd.com/test URL, I want to pass an array of ids or something of a Variable, and return views on template according to passed values. Is there any better way of achieving this ? I have tried this way but no luck: Javascript: <script> window.onload = function(){ var compare = localStorage.getItem("comparisionProducts"); var action_url =$this().window.location.href if (compare.value !== ''){ $.ajax({ url: action_url, type: "POST", data: {'compare_id': compare }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (result) { console.log("Success") }, error: function () { alert("Please login"); } }); } }; <script> and My Views: def compare(request): if request.is_ajax() and request.POST and 'compare_id' in request.POST: data = Products.objects.filter(product_id = int(request.POST['compare_id'])) context={ 'product':product, } return render (request, './ecommerce/compare.html', context) -
Temporary model instances referenced as foreign keys
Is there a way to keep a Django model instance, which is referenced by foreign keys, in memory without storing it to the database? The code is part of an _add_ overload, but the way it is implemented now is very ugly as it is hard to keep track of the new instances, and it also produces a lot of unnecessary DB accesses. Ideally I want to keep the new instances temporary as long as the user does not call the save() method on the returned instance. When I uncomment the save() calls like below, the annotation instances are not referenced in the returned Sequence instance. class Sequence(models.Model): ... def __add__(self, other:'Sequence'): """ This enables you to use the + operator when dealing with Sequence objects :param other: :return: """ # concatenate the actual sequences sum_seq.sequence = self.sequence + other.sequence #sum_seq.save() len_self_seq = len(self.sequence) # annotations annot: SequenceAnnotation # copy the own anntotations for annot in self.annotations.all(): new_annot = deepcopy(annot) new_annot.id = None # this is crucial to actually create a new instance new_annot.ref_sequence = sum_seq #new_annot.save() if other_is_bioseq: # copy the other annotations, adjust the start and end positions for annot in other.annotations.all(): new_annot = deepcopy(annot) new_annot.id = None … -
How can I get a object for a specific user?
I'm trying to display all the Books issued by a user. In my views im trying to get the IssueBook model's objects (only with the current user), The Book is just working fine, having trouble with IssueBook model- views.py def booksIssued(request): issued = IssueBook.objects.filter(user=request.user) books = Book.objects.filter(issued=True, user=request.user) print(issued, books) context = { "books" : books, "issued" : issued } return render(request, 'books_issued.html', context) models.py class IssueBook(models.Model): name = models.CharField(max_length=400) classSection = models.CharField(max_length=10) rollno = models.PositiveIntegerField() issued_date = models.DateTimeField(auto_now_add=True) date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f"{self.book} issued by {self.name}" forms.py class issueBook(ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('usr') super(ModelForm, self).__init__(*args, **kwargs) self.fields['book'] = forms.ModelChoiceField(queryset=Book.objects.filter(user = user)) date = forms.DateTimeField(widget=forms.DateInput(attrs={'type':'date'})) class Meta: model = IssueBook fields = ['name', 'classSection', 'book', 'rollno', 'date'] -
Django odd behaviour
Whenever I start a project in Django, independently of the name of the app or project, and irrespective of any urls or settings configuration, upon running python manage.py runserver and navigating to 127.0.0.1 I get the following error: Not Found: /ball/ [10/Jan/2022 11:32:32] "GET /ball/ HTTP/1.1" 404 2337 and this displays in th browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ball/ Using the URLconf defined in ornaments.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, ball/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Why is Django looking for a route called ball? Thanks. -
Mock async_task of Django-q
I'm using django-q and I'm currently working on adding tests using mock for my existing tasks. I could easily create tests for each task without depending on django-q but one of my task is calling another async_task. Here's an example: import requests from django_q.tasks import async_task task_a(): response = requests.get(url) # process response here if condition: async_task('task_b') task_b(): response = requests.get(another_url) And here's how I test them: import requests from .tasks import task_a from .mock_responses import task_a_response @mock.patch.object(requests, "get") @mock.patch("django_q.tasks.async_task") def test_async_task(self, mock_async_task, mock_task_a): mock_task_a.return_value.status_code = 200 mock_task_a.return_value.json.return_value = task_a_response mock_async_task.return_value = "12345" # execute the task task_a() self.assertTrue(mock_task_a.called) self.assertTrue(mock_async_task.called) I know for a fact that async_task returns the task ID, hence the line, mock_async_task.return_value = "12345". However, after running the test, mock_async_task returns False and the task is being added into the queue (I could see a bunch of 01:42:59 [Q] INFO Enqueued 1 from the server) which is what I'm trying to avoid. Is there any way to accomplish this? -
I am trying to register a staff in my database throuout the form But I get error
I have two models staff and UserAddress and I'm trying to add the staff through models. But I get this error: AttributeError at /accounts/signup/staff/ 'NoneType' object has no attribute 'add' What should I do now, Could some one help me? I wanted to register a staff but this thing happened. models.py: class UserAddress(models.Model): city = models.CharField(max_length=100) address = models.CharField(max_length=200) zip_code = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.id) class CustomUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE, null=True) class Staff(CustomUser): def save(self, *args, **kwargs): if not self.id: self.is_staff = True self.is_superuser = False return super(Staff, self).save(*args, **kwargs) class Meta: proxy = True forms.py: class StaffCreationForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) email = forms.EmailField(required=True) city = forms.CharField(max_length=100) address = forms.CharField(max_length=100) zip_code = forms.CharField(max_length=15, required=True) class Meta(UserCreationForm.Meta): model = CustomUser @transaction.atomic def save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get("first_name") user.last_name = self.cleaned_data.get("last_name") user.email = self.cleaned_data.get("email") user.is_staff = True user.save() address = UserAddress.objects.create(city=self.cleaned_data.get("city"), address=self.cleaned_data.get("address"), zip_code=self.cleaned_data.get("zip_code")) user.user_address.add(address) return user views.py: class StaffSignUpView(CreateView): model = CustomUser form_class = StaffCreationForm template_name = "accounts/signup_user.html" def get_context_data(self, **kwargs): kwargs["user_type"] = "staff" return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect("home") -
sync_to_async problem with scrapy-django-dashboard
i want to use scrapy and django for scrape some date and i implemented it with scrapy-django-dashboard document well but when i run this commant: scrapy crawl post_spider -a id=1 -a do_action=yes i get this error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. this is my model.py class in django : @python_2_unicode_compatible class NewsWebsite(models.Model): name = models.CharField(max_length=200) url = models.URLField() scraper = models.ForeignKey( Scraper, blank=True, null=True, on_delete=models.SET_NULL) scraper_runtime = models.ForeignKey( SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name @python_2_unicode_compatible class Article(models.Model): title = models.CharField(max_length=200) # https://stackoverflow.com/a/44026807 news_website = models.ForeignKey( NewsWebsite, blank=True, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True) url = models.URLField(blank=True) thumbnail = models.CharField(max_length=200, blank=True) checker_runtime = models.ForeignKey( SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.title class ArticleItem(DjangoItem): django_model = Article @receiver(pre_delete) def pre_delete_handler(sender, instance, using, **kwargs): if isinstance(instance, NewsWebsite): if instance.scraper_runtime: instance.scraper_runtime.delete() if isinstance(instance, Article): if instance.checker_runtime: instance.checker_runtime.delete() pre_delete.connect(pre_delete_handler) and this is my spider: class ArticleSpider(DjangoSpider): name = 'article_spider' def __init__(self, *args, **kwargs): self._set_ref_object(NewsWebsite, **kwargs) self.scraper = self.ref_object.scraper self.scrape_url = self.ref_object.url self.scheduler_runtime = self.ref_object.scraper_runtime self.scraped_obj_class = Article self.scraped_obj_item_class = ArticleItem super(ArticleSpider, self).__init__(self, *args, **kwargs) also this is my pipline: class DjangoWriterPipeline(object): def process_item(self, item, spider): if spider.conf['DO_ACTION']: try: item['news_website'] = spider.ref_object checker_rt = … -
"'str' object has no attribute 'get'" when passing slug to django form
I am attempting to pass a slug to a form, so that it can match user accounts with related groups (called 'events' in this project/context). The slug is an identifier for the event, which has several types of many-to-many connections to user-profiles (an extension to the standard django user model specifically made for connecting users to events). The form is supposed to create two drop-down choice fields to let an event manager set the permissions any other user has in the event, i.e. being a passive observer, an editor or a manager. However, as of now, django generates the error 'str' object has no attribute 'get' when rendering the page. The exception is located in django/forms/widgets.py in the function value_from_datadict, with the error being stated to be on line 0 in the base template base.dashboard.html, occurring during rendering. I've managed to avoid the error by removing both fields but leaving the slug and by removing both the candidate field and the slug, leaving the permissions field intact. I have also attempted to explicitly convert the passed value into a slug in the form (just in case some weird dynamic typing tripped the system up), but to no effect. What am … -
drf filter with related table count
Here is my model: class Artwork(models.Model): id = models.BigAutoField(primary_key = True) serial = models.IntegerField(choices=Serial.choices, default=100) title = models.CharField(max_length=255, blank=True, null=True) slug = models.CharField(max_length=255, blank=True, null=True) class Views(models.Model): id = models.BigAutoField(primary_key = True) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name="views") artwork = models.ForeignKey(Artwork, null=True, blank=True, on_delete=models.CASCADE, related_name="views") Here is my view class GetArtworkLiteView(viewsets.ModelViewSet): queryset = Artwork.objects.all() serializer_class = GetArtworkLiteSerializer filter_backends = [filters.OrderingFilter, DjangoFilterBackend] filterset_fields = ['slug'] ordering_fields = ["id", "serial"] Here i want to make ordering by count(views) in artwork model. How can i add logic to that so artwork model will sort by count of views i wants to implement this using django rest framework -
Django model second update statement not working
I am working on Django 3.2 and trying to make multiple updates to different records in the same function. The model that I have is as following class PlayerData(models.Model): id = models.AutoField(primary_key=True, blank=False, null=False) is_playing = models.IntegerField(blank=True, null=True) current_team_name = models.CharField(max_length=50, blank=True, null=True) current_team_id = models.IntegerField(blank=True, null=True) I need to set is_playing flag as false for everyone which belongs to certain team. Which I am doing like this PlayerData.player.filter(current_team_name__in=teamInfo).update(is_playing=0) This update works perfectly. Next I need to iterate a dictionary and get some values and update the records with those values which I am doing this way for player in playerObj: playerId = player['id'] playerTeamData = playerTeamInfo[playerId] PlayerData.player.filter(id=playerId)\ .update(current_team_name=playerTeamData.split(":::")[0], current_team_id=playerTeamData.split(":::")[1], is_playing=1) This update statement doesn't work, neither I get any error nor the DB is updated. I am not sure what I am doing wrong. Do I need add some sort of commit statement between two updates? -
Invalid HTTP_HOST header: 'subdomain.domain.com'. You may need to add 'subdomain.domain.com' to ALLOWED_HOSTS
after two days From deplyoing my application and working fine, I have decided to change the name of the subdomain so i have just rename it under the path: /etc/nginx/sites-available and then i have did again sudo certbot --nginx for the "https" , then adding this host in settings.py from my django application, I have did sudo systemctl restart nginx to restart nginx then: sudo systemctl restart gunicorn then python manage.py makemigrations -->No changes detected python manage.py migrate -->No changes detected and when i go to the browser to access to my application I got this error DisallowedHost at / Invalid HTTP_HOST header: 'subdomain.domain.com'. You may need to add 'subdomain.domain.com' to ALLOWED_HOSTS. , otherwise i Have added the host on "settings.py" Help please isn't there any other step i should do when i change the host ,Thanks in advance -
Can you import django-signal function to another django file?
I have imported a function in my Store Model to get some information after i save a file in django-admin. Looks like this: @receiver(post_save, sender=Store) def update_from_crawl(instance, **kwargs): import time import os info = { 'api_url': instance.api_url, 'access_key': instance.access_key, 'c_key': instance.consumer_key, 'c_secret': instance.consumer_secret, } time.sleep(2) os.system("python manage.py woocommerce") return info Now in my woocommerce.py (custom django-admin command script) after importing update_from_crawl update_from_crawl() shows update_from_crawl() missing 1 required positional argument: 'instance' In the woocommerce.py file i have this variable which checks for wcapi = API( url="", consumer_key="", consumer_secret="", version="wc/v3" ) And i would like to pass the info['api_url'], info['c_key'], info['c_secret'] into this file everytime a model is saved and automatically run it. Do you have any idea how to pass it? I've tried so many things but i cant figure it out:) Thanks in advance -
How to request.data multiple files from postman?
I am having a file field "documents" in which I want to add multiple files. But when I do documents = request.data('documents[]') I only get the last selected file. How can I get all the files as a list in documents variable. -
Should we use django authentication for all users of a site?
I have just started developing a bookstore site with Django and I have a question about user authentication. I want users to have a wallet, shopping cart and additional information for their account such as profile picture, phone number, address, etc. to buy books. And now I am faced with the dilemma of whether to change the User model itself, or create a Profiles model for each and link it to the User model, or create a separate model (in other words, the authentication system) and do everything from scratch. Now I have started building a separate authentication system. Everything was going well until I had problems in sending and receiving user data in the template contexets. Finally, in general, I want to know if Django authentication system is really suitable for all users of a site? -
Django, ImportError: cannot import name 'task' from 'celery'
I have Django application that was using Celery version 4.4.2, which was working fine. from celery import task import logging @task(ignore_result=True) def log_user_activity(user_id): try: logging.info(user_id) except Exception as e: logging.error(str(e)) As I tried to update the Celery version to v5.2.2 I get below error: ImportError: cannot import name 'task' from 'celery' Can someone help what is task been replaced with? they still have example here with same. https://github.com/celery/celery/blob/v5.2.2/examples/celery_http_gateway/tasks.py -
Filtering a Django model on an AutoField
I have a Django model that looks like this - class History(models.Model): testcaseidstring = models.AutoField(primary_key=True) # Field name made lowercase. I am storing String values in this field in the Database When I make a query on this field like - qs=qs.filter(testcaseidstring="tc123") I get an error saying "Field 'testcaseidstring' expected a number but got 'TC123'" How can I filter on this AutoField? Is converting that field to a TextField the only way to go? Any help would be highly appreciable Thanks!! -
You are trying to change the nullable field 'email' on customuser to non-nullable without a default
I have two models (UserAddress and CustomUser) in my models.py, the field user address in CustomUser was a many to many field but I decided to change it to a foreign key field. But when I ran python manage.py make migrations it asked me to choose a choice: what should I do: You are trying to change the nullable field 'email' on customuser to non-nullable without a default; we can't do that (the database needs something to populate exis ting rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous dat a migration) Quit, and let me add a default in models.py Here is my models.py file: class UserAddress(models.Model): city = models.CharField(max_length=100) address = models.CharField(max_length=200) zip_code = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.id) class CustomUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE) -
How AWS S3 requests are made/calculated?
I am new to AWS. I have created a S3 bucket a few days ago and I have noticed the number of requests made to it is already very high. Over the free tier limit for Put... I don't understand what is going on. I did connect a django heroku hosted app to the bucket but I am the only one having access to it and I only made a dozens of requests in the past few days. Can you please help me understand what is going on, is this normal behaviour? I didn't find my answer on Amazon forum and to access the technical support I need to upgrade my plan... Thank you -
How to pass django-simple-history model in Graphene-Django?
I have created an instance of simple_history.models.HistoricalRecords in my Notification model models.py class Notification(models.Model): title = models.CharField(max_length=500) content = RichTextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) history = HistoricalRecords() class Attachment(models.Model): title = models.CharField(max_length=500) attachement = models.FileField(upload_to = user_directory_path) notifiaction = models.ForeignKey(Notification, on_delete=models.SET_NULL, null= True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) schema.py class AttachmentNode(DjangoObjectType): class Meta: model = Attachment filter_fields = ['title'] interfaces = (relay.Node, ) class NotificationNode(DjangoObjectType): class Meta: model = Notification filter_fields = { 'id': ['exact'], 'title': ['exact', 'icontains', 'istartswith'], } interfaces = (relay.Node, ) class Query(graphene.ObjectType): notifications = relay.Node.Field(NotificationNode) all_notifications = DjangoFilterConnectionField(NotificationNode) This is working fine but I want all the records in the graphql endpoint of HistoricalRecords() as well. How can I do this? -
Regarding Database is locked in Azure Django
I have an App service running django app on free service on linux. it is resetting my db.sqlite3 file again and again and i can not afford to use postgresql as it is not in free services (I don't have azure free credit). How can i make db.sqlite3 file persistent? Things I have tried :- tried adding db.sqlite3 in /home/site/wwwroot/ but django is showing that database is locked. created dbfiles directory in /tmp folder and added db.sqlite3 in /tmp/dbfiles but django is showing that unable to open database file. AS I NEED IT URGENT PLEASE HELP -
Django and Tox testing
I have a django package that I like to test against different versions of django using tox and with the python manage.py test command. On the newer versions, django has from django.urls import reverse available, but this doesnt exist on e.g. Django 1.8, because its in a diff path, but this version I am trying to test against, too. Can someone point me to resources to find out how I can still make the tox testing pass? Whats the correct way of testing this? Is there some sort of conditional import I can do based on django version? Or maybe sth like try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse Im just not sure if this is the standard and safest way :) Thanks! tox config [tox] envlist = {py27,py35}-django18, {py27,py35}-django19, {py27,py35}-django110, {py27,py35,py36,py37}-django111, {py35,py36,py37}-django20, {py35,py36,py37}-django21, {py35,py36,py37}-django22, {py35,py36,py37,py38}-django30, {py38,py39,py310}-django40, [testenv] commands = python manage.py test deps = django18: django==1.8.* django19: django==1.9.* django110: django==1.10.* django111: django==1.11.* django20: django==2.0.* django21: django==2.1.* django22: django==2.2.* django30: django>=3.0a1,<3.1 django40: django==4.0.* -
unable to get the data from url to do predictions in django rest api
I was trying to do predictions in drf and celery and my tasks.py file is @shared_task(bind=True) @api_view(['GET']) def predictions(self): solute = request.GET.get('solute') solvent = request.GET.get('solvent') mol = Chem.MolFromSmiles(solute) mol = Chem.AddHs(mol) solute = Chem.MolToSmiles(mol) solute_graph = get_graph_from_smile(solute) mol = Chem.MolFromSmiles(solvent) mol = Chem.AddHs(mol) solvent = Chem.MolToSmiles(mol) solvent_graph = get_graph_from_smile(solvent) delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)]) return delta_g.detach(), torch.trunc(interaction_map).detach() and my views.py file is @api_view(['GET']) def result(request): response = {} results = predictions.apply_async() # response["interaction_map"] = (results[1].numpy()).tolist() # final_results = results.get() print(results.get(propagate=False)) # response["predictions"] = results[0].item() return Response({'result': results.get(propagate=False)}, status=200) I am getting error @api_view(['GET']) NameError: name 'api_view' is not defined. I know that loading the solute and solvent in the views.py file rectifies the problem. but I want to get them directly in the tasks.py file. If not possible I want to bring the solute and solvent to the tasks.py file. How can i do it? solute = request.GET.get('solute') solvent = request.GET.get('solvent') -
How to implement a hotel room pickup app?
I'm working on a Django app which would take data on the numbers of rooms sold in a hotel for each (future) date, on any given date, and use that data to determine pickup rate. For example, this is what the data for 12/22/2021 might look like: Date Rooms Sold Days Prior 12/23/2021 34 1 12/24/2021 19 2 12/25/2021 11 3 12/26/2021 10 4 12/27/2021 3 5 So on 12/22, the hotel had 34 rooms sold for the night of 12/23, 10 rooms sold for the night of 12/26, and so on. My goal for this app is to compare how the numbers are changing to determine the pickup rate for a given date. For example, if on 12/25 the hotel had 20 rooms sold for the night of 12/26, then I would be able to see that the pickup for that date/night was 10 rooms over the course of 3 days (because there was 10 rooms sold on 12/22). I would want dates to get flagged if there was a sudden pickup in rooms sold on that date, signaling a possible event and increase in demand for rooms that day. I'm just having trouble figuring out how I should …