Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse Queryset Order in Django for pagination
I have some technique to share with reverse queryset and pagination import your_model from django.core.paginator import Paginator array = your_model.objects.order_by('id').values().reverse() or array = your_model.objects.order_by('create_at').values().reverse() p = Paginator(array, 15) => 15 is number of data in pagination p.num_pages => check number of page p.get_page(page).object_list => get data each page -
Fail to pass dict data to jquery. Error display as: Uncaught SyntaxError: missing ) after argument list)
I have issue on reading data that pass from a Django template in jquery .js file. The data in my Django view: print({0}, {1}\n'.format(init_data[1], type(init_data[1])))) // this will print: 'Counter({'pass': 15, 'fail': 2}), <class 'collections.Counter'> context = {"data":init_data[1].items()} return HttpResponse(template.render(context, request)) In my index.html template I'm able to read the data out as such {% block content %} <h3> {{data}} </h3> // this printed dict_items([('pass', 15), ('fail', 2)]) <div class="tab"> <button class="tablinks" onclick="openResult(event, 'TabForm')" id="defaultOpen">Form</button> <button class="tablinks" onclick="openResult(event, 'TabChart', {{data}}')">Statistic</button> </div> <div id="TabChart" class="tabcontent"> {% include 'result/tab_statistic.html' %} </div> {% endblock %} In result/tab_statistic.html, I want to use the 'data' as dynamic data for a chart in jquery, but the 'data' seem not readable in jquery script as I get bug complaining: (index):18 Uncaught SyntaxError: missing ) after argument list Here is my simple jquery script just to show the data is not readable when called from function openResult() above function openSummary(evt, tabName, a ) { if (typeof(a)==="undefined") a = "None"; console.log('CHECK a=' + a); return It seems to be it don't allow 'data' to be passed directly as the way I do because if I replaced the {{data}} with any argument 'abc' , it just working. Pls gives me … -
Python - Access a model, with a name that is dependant on a variable value
I'm trying to access a model, with a name that is dependant on a variable value. If have a series of models based on a country identifier. e.g. Student_??? where ??? is the country identifier. If I want to print out details of each student for each country, is there a way of looping through the code to access each model dynamically. I could perform the task through an if statement, but that would require hardcoding each country code into the program, which I want to avoid. As an example. My views.py looks like: mystudentcountry = {'AU', 'US', 'UK', 'EU'} for country in mystudentcountry: mystudent = Student_AU.objects.all() for student in mystudent: print(f'{student.name} is {student.age} years old and studies in {country}') On the third line of code "mystudent = Student_AU.objects.all()" is it possible to replace the "AU" with each country as identified in the loop. Thank You for your support. -
Why indentation of Retun statement is not under form here?
the code below is correct, however, I want to know why the return statement is not functioning when indented under form? def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('websitehome') else: form = UserCreationForm() return render(request, 'user/register.html', {'form': form}) -
How do I handle this error : __init__() got an unexpected keyword argument 'book_category'
I am trying to input some book data and save it to my database using django(trying to make a web library) But I encounter this kind of error: init() got an unexpected keyword argument 'book_category' The error seems to be in this line of code : form = CategoryForm(book_category= book_category) This is the code of my views.py class AddBook(View): def post(self, request): form = BooksForm(request.POST, request.FILES) if form.is_valid() book_category = request.POST.get('book_category') firstname = request.POST.get('Firstname') lastname = request.POST.get('Lastname') author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname)) if author: print(author) else: form = AuthorForm(firstname=firstname, lastname=lastname) form.save() category = Category.objects.filter(Q(book_category__icontains = book_category)) if category: print(category) else: form = CategoryForm(book_category= book_category) form.save() author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname)) for a in author: print(a.book_author_id) for c in category: print(c.book_category_no) book_title = request.POST.get('book_title') book_cover = request.FILES.get('book_cover') book_file = request.FILES.get('book_file') book_year = request.POST.get('book_year') book_tags = request.POST.get('book_tags') book_summary = request.POST.get('book_summary') form = Books(book_title = book_title, book_author_id = Author.objects.get(book_author_id = a.book_author_id), book_cover = book_cover, book_file = book_file, book_year = book_year, book_summary = book_summary, book_category_no = Category.objects.get(book_category_no = c.book_category_no), is_bookmarked = 0, is_downloaded = 0, is_read = 0, is_deleted = 0) form.save() return HttpResponse('Book Saved!') else: print(form.errors) return HttpResponse('Not Valid') And here is my models.py: class … -
Django with sqlalchemy + alembic + django.contrib.auth
How can I customize auth user with SQLAlchemy, instead of Django ORM? Django built-in auth features are so useful but it assumes built-in User or one extended with Django ORM. There's no instruction how to do it with SQLAlchemy AFAIK. I'm newbie of Django but found some articles/blogs pointing out that Django ORM is not good from data analysis standpoint. Therefore I'm thinking of fully using SQLAlchemy instead of Django ORM.To make things simpler, I don't like to use both of them. I've investigated tutorials/articles/blogs regarding Django + SQLAlchemy but most of them seem obsolete(like 5 - 10 years ago). Perhaps it's standard to use Django ORM even for apps of data analysis in recent days? -
How should I avoid this race condition?
I have a piece of code like below: bargained_count = BargainLog.objects.filter(bargain_start_log=bargain_start_log).count() total_bargain_count = 10 # money = '%.2f' % (goods_price / 10) # TODO:接入砍价算法 money = calc_single_bargain_money( bargain_start_log=bargain_start_log.id, total_bargain_money=round(float(goods_price), 2), leftover_bargain_money=round(float(goods_price) - float(total_bargain_money), 2), total_bargain_count=total_bargain_count, leftover_bargain_count=total_bargain_count - bargained_count, is_new_user=False ) print('money', money) ... BargainLog.objects.create(bargain_start_log=bargain_start_log, money=money, ...) bargain_count is a parameter of func calc_single_bargain_money. But, because of the race condition. I am not sure if this is one kind of race condition. I may get bargain_count as same values which will affect the result of calc_single_bargaiN_money. So, how should I avoid it, please give me some advice. -
TypeError: entry() missing 1 required positional argument: 'title' (Django Help)
With Django I'm creating an encyclopedia website similar to Wikipedia, for a class. I've played around with this for quite a while but still cannot solve this - I keep getting the error: entry() missing 1 required positional argument: 'title' The error occurred when I clicked to create a new page on the site. This pertains to the function 'newpage' but I think the issue might be in the function 'entry.' I did the exact steps (but using 'title') from this Stack Overflow suggestion but it did not work: TypeError at /edit : edit() missing 1 required positional argument: 'entry' In urls.py I've tried both: path("wiki/<str:entry>", views.entry, name="entry"), path("wiki/<str:title>", views.entry, name="entry"), Just can't figure out how to get past the error. Any info is appreciated, as I'm new to Django. urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("newpage", views.entry, name="newpage"), ] views.py file: class CreateForm(forms.Form): title = forms.CharField(label='title') text = forms.CharField(label='text') def index(request): """Homepage for website""" return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): """ Displays the requested entry page, if it exists """ entry_md = util.get_entry(title) if entry_md != None: # Title exists, convert md to HTML and return rendered template … -
OperationalError, No such table: accounts_user
I'm working on a Django backend for a simple to-do list website. The website authenticates users by asking them to put in their email, sending them a link with a token, then using that token to log them in when they click on the link, redirecting them back to the homepage. When I try and run the development server, I always get a debug screen saying OperationalError at / no such table: accounts_user. I have two apps that are part of the overall project, lists and accounts. Solutions to similar errors I've come across on StackOverflow haven't worked for me. Both apps are listed in INSTALLED_APPS under core.settings. I tried deleting my sqlite database, all my __pycache__ and migrations folders, and running makemigrations and migrate again, to no avail. I even ran it for the accounts app, and ran it using --run-syncdb, and that still didn't work. The error is thrown during template rendering, on line 17 of my base.py, specifically the one that says, {% if user.email %}. I'm using Django 1.11.29 and Python 3.6.8. The database is a simple sqlite file in the project directory. Here's my models and views, along with the website's base template: lists/models.py from … -
why cv2.imread returns none when using django python?
i use opencv-python in django, but when i use cv2.imread, it just returns nonetype. How can i solve this problem? Exception Value: bad argument type for built-in operation -
Celery revoke old task if new one is created with same arguments
I'm having trouble understanding the Celery queue and revokes. My main question is how to revoke (stop from executing) tasks that are already in the queue if a new task with the same name and arguments is created. so in pseudo-code new_task_to_be_added = some_task(1,2) if exists some_task in queue where some_task.args = (1,2): remove such task from queue new_task_to_be_added.add_to_queue() this is connected to password reset mechanism - User clicks 'create temporary password' and has 5 minutes to use this password to create a new - permanent - password. If the new password is not set in this time the account should be locked. But if after lets say 4 minutes user creates a new temporary password he should again have 5 minutes to change it but the "lock account" task will trigger in 1 minute - I want to stop that and always only use the newest task (with the same parameters) this is not a copy of: Revoke celery tasks with same args/kwargs this is actually reversed problem -
Save django variable using ajax
I'm trying to do a multistep form using Django 3. The context of this form it is to make a schedule for a exam. The user shall choose a day and time. But when day is chosen, a filter is applied to show the number of vacant seats. Here starts the problem. The way I've been planed to make this possible is using AJAX to collect a value from DATE option and send to back-end to filter. But, the value on back-end is not changing. Here is the code: model are: Day, Time and scheduling(day and time foreignkey) {% extends "base_restrictedArea.html" %} {% load filter_agenda %} {% block main%} <div class="container"> <div class="row"> <h2>Sscheduling</h2> <form id="multistep_form" action="{% url 'my_url' %}" method="post"> {% csrf_token %} <fieldset> {% for dates in date %} <input type="radio" id="model_date" value="{{ dates.id }}" name="model_date" onclick="myFunJs( '{{ datas.date|date:'d' }}' );">{{ datas.data }} {% endfor %} <input type="button" name="previous" class="previous action-button-previous" value="Previous"/> <input type="button" name="next" class="next action-button" value="Next"/> </fieldset> <!--time--> <fieldset> <table> <tr> <th>Time</th> <th>seats</th> <th>schedule</th> </tr> {% for times in time %} <tr> <td>{{ times.time}}</td> <td> vagass {% with result=scheduling|my_filter_day:varJsToDjango %} {{ result|my_filter_time:times.time }} {% endwith %} </td> <td><input type="radio" value="{{ times.id }}" name="model_time"></td> </tr> {% endfor … -
(Django) Code runs fine locally but seems to stop after second iteration in production
I am scraping a website for their data, using Selenium (Firefox). I've created a UI with some buttons, like "start scrape" and "stop scrape." When someone with access to the UI clicks either of these buttons, it makes a call to a Django Rest Framework API which starts or stops a scrape. Locally, everything runs fine and there seem to be no problems. However, in production, the scrape always only gets to the 2nd item that is to be collected. Here is the code: # api/views.py r = redis.Redis(host='localhost', port=6379, db=0, decode_responses='utf-8') @api_view(['POST']) @permission_classes((IsAuthenticated,)) @ensure_csrf_cookie def scrape_website(request): if request.method == 'POST': session_key = request.session.session_key r.set('scrape-stop-%s' % (session_key), 'no') r.expire('scrape-stop-%s' % (session_key), 60000) data = request.POST location = data.get('location') company_type = data.get('company_type') limit = data.get('limit') scrape(session_key, location, company_type) return Response({'msg': 'scrape successfully started'}) # scrape.py def scrape(session_key=None, location='united_states', agency_type='digital_marketing_agencies', limit=200): options = Options() options.headless = True profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.dir", os.path.join(base_dir, 'reports')) profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.helperApps.alwaysAsk.force", False); profile.set_preference("browser.download.manager.showAlertOnComplete", False) profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference('browser.helperApps.neverAsk.saveToDisk','application/zip,application/octet-stream,application/x-zip-compressed,multipart/x-zip,application/x-rar-compressed, application/octet-stream,application/msword,application/vnd.ms-word.document.macroEnabled.12,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/rtf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/vnd.ms-word.document.macroEnabled.12,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/xls,application/msword,text/csv,application/vnd.ms-excel.sheet.binary.macroEnabled.12,text/plain,text/csv/xls/xlsb,application/csv,application/download,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/octet-stream') driver = webdriver.Firefox(firefox_profile=profile, options=options) print('Working...') driver.get(links[location][agency_type]) def get_boxes(location, agency_type, limit, index=0): print('index: %s' % (index)) boxes = driver.find_elements_by_xpath("//*[contains(@class, 'sc-AykKC') and contains(@class, 'sc-AykKD') and contains(@class,'hfxDgE')]") while index <= (len(boxes) - 1): box = boxes[index] index += 1 link_element = box.find_element_by_xpath(".//a[contains(@href,'profile')]") … -
How to install Django pg_trgm by makemigrations?
I have a Django app and a Postgresql database (in production). Now I want to intall pg_trgm extension for Postgres. But I can't find any step-by-step instructions for installing it from Django app. I have a superuser status. How to do it correctly? -
Python (Redis + DRF): Invalid input of type: 'NoneType'. Convert to a bytes, string, int or float first
I've got my redis running server, this is the configuration for it: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://TestPass1234@192.168.0.30:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } CACHE_TTL = 60 * 1 # 1 hour SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" This is my views.py: from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_cookie from rest_framework.viewsets import ModelViewSet from .serializers import TestSerializer from .models import Test # Create your views here. class NameofViewSet(ModelViewSet): serializer_class = TestSerializer queryset = Test.objects.all() #lookup_field = 'name_of_lookup_field' # and more.. @method_decorator(vary_on_cookie) @method_decorator(cache_page(60*60)) def dispatch(self, *args, **kwargs): return super(TestSerializer, self).dispatch(*args, **kwargs) And I have one object in the database, just to get something by requesting the URL. The error : [08/Dec/2020 02:17:25] "GET /tests/ HTTP/1.1" 500 158257 Internal Server Error: /tests/ Traceback (most recent call last): File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\redis\connection.py", line 643, in on_connect auth_response = self.read_response() File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\redis\connection.py", line 756, in read_response raise response redis.exceptions.AuthenticationWrongNumberOfArgsError: wrong number of arguments for 'auth' command During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\dziugas\.virtualenvs\test_cache-PBGnRHhx\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
Reading the time zone of the end-user in Django
according to this apparently there is no way to read time zone of the end-user in Django. different methods all will read time zone of the server, rather than end user. I see that in javascript the following code will give time zone of the user and not server: const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; according to this which my test confirmed that. now my question is where would be the cleanest place to run the above code in a Django project which perhaps will be followed by an Ajax call to Activate() timezone. -
ValueError: invalid literal for int() with base 10: '' django
I created a models in django-framework but after run migrate, I got this type of error from django.db import models # Create your models here. class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to="shop/images", default="") desc = models.CharField(max_length=300) pub_date = models.DateField() def __str__(self): return self.product_name but I get this error after run migrate PS C:\Users\Lenovo\Desktop\django-recap\django\myshopcart> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, shop Running migrations: Applying shop.0002_auto_20201208_0348...Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields_init_.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Lenovo\Desktop\django-recap\django\myshopcart\manage.py", line 22, in <module> main() File "C:\Users\Lenovo\Desktop\django-recap\django\myshopcart\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, … -
what is the best way to store and read data with python (django app)?
I am making a django website. I have some medium size data (around 50 Mo) that will be used for read only. They contain for example city names and codes and other inputs. I have tried several methods so far: store in json file and load with python or pandas store in csv file and read with python csv reader store it as a dict inside a variable, directly in a python module. like below: module.py my_dict_variable = {mydict} Json file is the slowest of all to read the data because of the loading time (I guess). CSV file is better but still quite slow. The last method is by far the fastest one (by a factor of minimum 10 compared to CSV). But I wonder if it's good practice or not. This data is used for query while typing request with Ajax, so I need to have really fast process and results. Do you guys have other ideas about the best/most efficient way to deal with such use cases? -
How to add django rest knox token django views
I would like to add jwt generated by django rest knox to authenticate users that login as well as verify users that sign up using an otp generator Here is the user profile model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class UserProfileModel(models.Model): """The Model of the User Profile.""" account = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") profile_photo = models.ImageField() def __str__(self): return self.account.first_name Custom django user model class User(AbstractBaseUser, PermissionsMixin): mobile = models.CharField( _('mobile'), max_length=16, unique=True, help_text= _("Required. mobile number must be entered in the format: '+999999999'." ), validators=[validate_mobile], error_messages={ 'unique': _("A user with that mobile no already exists") }, ) email = models.EmailField( _('Email Address'), max_length=100, unique=True, help_text= _("Required. email number must be entered in the format: 'abc@abc.com'." ), validators=[validate_email], error_messages={'unique': _("A user with that email already exists.")}, ) password = models.CharField( _('Password'), max_length=128, help_text=_("Required. enter password."), ) first_name = models.CharField( _('first name'), max_length=30, blank=False, help_text=_('Required. Please enter name '), ) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=False, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.'), … -
Using inline url() property with Django template {%staric 'img/header/header-1.jpg%}
I'm having trouble with displaying images with Django templates {%static%}. <div class="slide" style="background: url({% static "images/header/header-1.jpg" %}) center center; background-size: cover;"> However, I am successfully able to display an image with tag <img src={% static "images/logo.png" %} alt="Olga"> Thanks in advance -
Get Instagram followers count in Django
I'm building a dashboard for a client and I want to show their Instagram follower count. I've seen this done in many dashboards and I'm wondering how they do it. I have a working example that works in development but whenever I push it to production I get a huge string rather than the parsed number I usually get. def dashboard_view(request): def insta_follower_count(): user = "username" url = "https://instagram.com/" + user try: r = requests.get(url).text start = '"edge_followed_by":{"count":' end = '},"followed_by_viewer"' count = (r[r.find(start)+len(start):r.rfind(end)]) except: count = 'Could not fetch followers' return count context = { "insta_followers": insta_follower_count(), } return render(request=request, template_name='dashboard/dashboard.html', context=context) Perhaps there's a much better way of doing this? -
Finding all hardcoded string in big django project (Python 2.7)
I need to refactor a huge project written in django. I need a tool that can easily search all application code and find all of hardcoded strings, especially file paths. I have to move all these hardoces to settings.py. Is it possible to configure lint to only show hardcodes? Or maybe pycharm has tools/plugin for this? Thank You :) -
Django performance: Separate tables on database for each "user" for action model
class ActionModel(models.Model): target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, ) # django user that performed the action I have this action model. It has maybe 30 million records and counting. There is another follower model that count all actions for a given follower (target) for a specific user (AUTH_USER_MODEL) each time it query, and it also have 500K followers for most cases. So instead of having one huge 30M table - can I separate it to table per user ? so it will query faster, by only looking at a specific table ? I guess it like folders and files, better not put all images on same folder. right ? -
Django get best-selling product in a timeline
I have these models (with irrelevant fields removed) class VentaProducto(RegistroModel): unidad_inventario = models.ForeignKey('almacenes.UnidadInventario', on_delete=models.CASCADE, related_name='ventas') amount = models.DecimalField(max_digits=10, decimal_places=2) class UnidadInventario(RegistroModel): control_stock = models.ForeignKey('almacenes.ControlStock', on_delete=models.CASCADE, related_name='unidades_inventario') amount_producto = models.DecimalField(max_digits=10, decimal_places=4, default=Decimal('0.0000'), verbose_name='Amount of producto') class ControlStock(RegistroModel): producto = models.ForeignKey('productos.Producto', on_delete=models.CASCADE, related_name='stocks') class RegistroModel(models.Model): date_created = models.DateTimeField(auto_now_add=True, verbose_name='date created') And the Producto model, which is just basic information about the product. VentaProducto is the one where each sale is stored, name of product and how many were sold. The products currently in possession are in UnidadInventario, and ControlStock determines which product it is. I need to get a list of the (10,15, all) best-selling products in a day/month/year. How can I group each sale (VentaProducto) by product (VentaProducto.unidad_inventario.control_stock.producto), then adding their amount values to get the total amount sold, and display each product in a list? This is what I currently have, a list of each sale and this is what I want, a list of best-selling products in a day, done in paint I thought about adding an amount_sold filter to products, but I need to filter by date. I tried some things but I got stuck and realized it wouldn't work the way I want. How can I do … -
Send notifications to users in Django
I have a more general Django question on how to approach the following functionality. Think of the Facebook/Messenger; once you receive a like or message, you will instantly receive a red circle at the top with "1" (or just think of any other notification). I have a scenario where I wan't a user to get a notification if I for example add them to a certain group, preferably without having to reload the page. I have googled around and I think that WebSockets are the way to go, but it seems fairly complex and not many tutorials out there. Anyone has any feedback or if someone could point me in the right direction? If not in realtime and without having to refresh the page, I would somehow want the user to get a (1) notification in the navbar. Any thoughts/feedback appreciated!