Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a link between two models in Django?
There are 2 models School Director It is necessary to make sure that in the school model there is a director (full name), and in the Director model there is the name of the school from django.db import models class Director(models.Model): created_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50, verbose_name='Name') last_name = models.CharField(max_length=50, verbose_name='Surname') school = models.CharField() #<----???? photo = models.ImageField(upload_to="uploads/img/", height_field=None, width_field=None, max_length=10000, verbose_name='photo') birthday = models.DateField( verbose_name='birthday') class school(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50, verbose_name='name') capacity = models.IntegerField(max_length=20,verbose_name='capacity') registration_is = models.BooleanField(max_length=20,verbose_name='Registration') director_name = models.ForeignKey(Director, related_name='name boss') class school, inherits the model of the director in the director_name class Director, must also inherit the Boss class, for the director_name field school = models.CharField() But it doesn't work for obvious reasons Django guru, tell me how to implement this task, please I Googled everything I could but didn't find a solution. -
Sequnce vs TextChoice vs IntegerChoices in Django
Which method is preferable for determining the choices in the `choices` argument when defining the model field in Django? Suppose I have a some model: class Balance(models.Model): reason = models.CharField(choices=...) # or models.IntegerField ... Sequnce: REFILL = 1 CASHBACK = 2 SUBSCRIPTION = 3 ORDER = 4 Reason = ( (REFILL, "Refill"), (CASHBACK, "Cashback"), (SUBSCRIPTION, "Subscription"), (ORDER, "Order"), ) TextChoices: class Reason(TextChoices): REFILL = "refill", "Refill" CASHBACK = "cashback", "Cashback" SUBSCRIPTION = "subscription", "Subscription" ORDER = "order", "Order" IntegerChoices: class Reason(IntegerChoices): REFILL = 1, "Refill" CASHBACK = 2, "Cashback" SUBSCRIPTION = 3, "Subscription" ORDER = 4, "Order" Django documentation does not give preference to any one method. Just showing different ways. I often see examples with a sequence, but what's wrong with using TextChoices or IntegerChoices? In what situations is it better to use these classes? -
Two Layer Nested Serializers - Django Rest Framework
Say I have models with grandparent-parent-child relations like so: models.py class Unit(...): number = models.CharField(...) class Listing(...): unit = models.ForeignKey('Unit', related_name="listings", ...) number_of_bedrooms = models.IntegerField(...) class Price(...): listing = models.ForeignKey('Listing', realted_name="prices", ...) amount = models.DecimalField(...) Using DRF - how can I grab all of the price instances for a listing in the ListingSerializer; all prices are determined by the grandparent Unit. I am trying: serializers.py class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ["amount"] class ListingSerializer(serializers.ModelSerializer): prices = PriceSerializer( source="unit__listings__prices", # <-- this does not seem to work many=True, read_only=True, ) ... Essentially: a unit can have multiple listings a listing can have multiple prices a unit will have many prices as its "grandchildren" how can I get all of the price "grandchildren" on the ListingSerializer -
Call Django service worker method for another device
I want to create a function needsToBeCalled(a, b) in serviceworker.js for Django that can be called from another device. What I need is when Django admin clicks a button, a function should be called but on every SELECTED device with service worker turned on. serviceworker.js var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/base_layout' ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/base_layout')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); function needsToBeCalled(a, b) { console.log(a + b); } Service worker is working as it should, I just need a way to call this function from device 1 so it outputs something on devices 2, 3, 4... -
generate a custom token on django rest framework
I am developing an application which I wrote an api for it this api create a user by verifying it's phone number so then I want to generate him token the post request should be like this { "phone_number": "", "username": "", "bio', "profilePic": null } and if model serializer is valid the output should be like this and it should generate a token for another requests { "phone_number": "", "username": "", "bio', "profilePic": null, "token": "28duw8he282hd2sszajqj" } so I want to create a customize auth class is there any one to help with my problem this is the user model class class WhIronUsers(models.Model): phone_number = models.CharField(max_length=100, verbose_name="phone_number", unique=True) username = models.CharField(max_length=100, verbose_name="username") bio = models.CharField(max_length=255, verbose_name="bio") profilePic = models.ImageField(upload_to="images/profile") and this is the view which in this view I want to generate the token from rest_framework import generics from .serializers import WhIronUserSerializer from .models import WhIronUsers class WhIronUserView(generics.ListCreateAPIView): serializer_class = WhIronUserSerializer queryset = WhIronUsers.objects.all() class WhIronDetailUserView(generics.RetrieveDestroyAPIView): serializer_class = WhIronUserSerializer queryset = WhIronUsers.objects.all() -
How do I use a forms action attribute to work with an object pk in django?
I have a form which needs to use the pk of the object its use is needed for. How do I write the url in the action attribute instead of leaving it blank? The url conf is this: path('add/<int:pk>/', ObjectView.as_view(), name='add') The link to the form from the other template pages is this: <a href="{% url 'app:add_users' object.id %}">Form</a> The class handling it is pretty basic with get and post which currently accept **kwargs for the object's pk So how do I edit the action attr to work when not left blank in the form?: <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Invite"> </form> -
Django Media files: https://https://
In Django the following settings are configured: MEDIA_URL="https://abcdefg.cloudfront.net/media/" STATIC_URL="https://abcdefg.cloudfront.net/static/" In web browsers the URL for the static files is correct. The URL for media files however is incorrect with https://https: leading to 404's: https://https://abcdefg.cloudfront.net/media/ When I print(f"MEDIA_URL: {MEDIA_URL}"), from the settings the URL is correct. I use {% get_media_prefix %} and {% get_static_prefix %} for my static and media files. For example: <img src="{% get_media_prefix %}image.jpg" alt="Image"> This alternative does not work: MEDIA_URL="abcdefg.cloudfront.net/media/" The result observed in the browser is https://example.com/abcdefg.cloudfront.net/media/ EDIT: I am using Django-CMS What is the issue here? -
Django get pk row if pk is found in queryset filter
I have the current table example : I know how to get the rows where the ID is found in : result_query_1 = models_contacts.objects.filter(company_members_id__icontains= str(pk)+";") result_query_2 = (here I would like the row of the ID used for the previous query if a match is found) But I would like to go one step further and also get the row of the ID in another queryset (depending on the first one matches). For example : If id 1 is found in company_members_id : result_query_1 = row N°2 (addidas) + row N°4 (Jordan) and result_query_2 = row N°1 (Nike) I was thinking of using a for loop but I don't Know how to do this in Django. Maybe there is a simpler / better way to do this ? Thanks -
How to communicate between Django, and a Python script running on a Raspberry Pi
I have a Django Dashboard sample that I want to use to demonstrate Multi Factor Authentication for an iot hub based on a raspberry pi. The Pi is connected to a fingerprint sensor, and a temperature/humidity sensor. A python script is running on the raspberry pi interfacing with the fingerprint and temp/humidity sensors. I need to communicate between the Django Dashboard, and the python script, so that I can change pages on the web app based on the status of the fingerprint sensor and update a home page showing the values of the temp/humidity sensor. The dashboard already has implemented user authentication, I will add a fingerprint enrollment step during signup, after which the pi will generate a 6 digit random number to be used as an otp, which will be sent to the user via the email they gave during the signup process. This otp will be entered in the web ui, and sent to the pi for confirmation, after which the pi will send back a otp matched response. The fingerprints will remain stored on the sensor, the sensor will only return the id of a matched finger, which corresponds with the user id. During the login process … -
Django - type validation on not required field
in Django admin interface, when submitting a form which has an optional integer field, I want to show a validation error message when user enters an incorrect type (string). However when user enters a string into this field and submits the form, Django recognizes it as an incorrect type and changes the value to None and successfuly validates the form. Therefore there is no way to find out if the field was left blank or user entered incorrect type. Even when I try to get clean data from custom form (clean_<field_name>) it always returns None. Is there a way to show a validation error for an optional field? Or can I somehow get the value that was actually entered into the field? Thank you for your help. I tried to overwrite default behaviour with custom form and tried to get clean data from the field but nothing works, it always returns None. Here is the model: class Condition(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) code = models.CharField() common_name_en = models.CharField() ordering = models.IntegerField(blank=True, null=True) common_name_cs = models.CharField() eval_time_frame = models.ForeignKey('ConditionEvalTime', models.DO_NOTHING, db_column='eval_time_frame') unit = models.CharField(blank=True, null=True) metric_extreme_low = models.FloatField(blank=True, null=True) metric_extreme_high = models.FloatField(blank=True, null=True) metric_scale = models.FloatField(blank=True, null=True) class Meta: managed = … -
Larger Django project with mulptiple levels of subfolders with 20 apps
I am working on larger Django project which needs multiple levels of subfolders, for example applications/examples/example_1 where the app is. When adding this app to settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home_app.apps.HomeAppConfig', 'applications.examples.example_1.apps.Example1Config', ] home_app works well, but example_1 give this error: django.core.exceptions.ImproperlyConfigured: Cannot import 'example_1'. Check that 'applications.examples.example_1.apps.Example1Config.name' is correct. My app.py in example_1 is this: from django.apps import AppConfig class Example1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'example_1' structure of project: C:. │ db.sqlite3 │ manage.py │ ├───applications │ ├───examples │ ├───example_1 │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ └───__pycache__ │ apps.cpython-311.pyc │ __init__.cpython-311.pyc │ ├───home_app │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ __init__.cpython-311.pyc │ │ │ ├───static │ │ background_img.jpg │ │ │ ├───templates │ │ └───home_app │ │ about.html │ │ base.html │ │ home.html │ │ │ └───__pycache__ │ admin.cpython-311.pyc │ apps.cpython-311.pyc │ models.cpython-311.pyc │ urls.cpython-311.pyc │ views.cpython-311.pyc │ __init__.cpython-311.pyc │ … -
Django Template Folder Naming
Preface I have a Django project called shopping_list and an app in that project called main with this structure. the main page of the main app will use main.html as a template . ├── main │ ├── migrations │ │ └── 0001_initial.py │ ├── templates │ │ ├── create_product.html │ │ └── main.html │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── shopping_list │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── templates │ └── base.html ├── db.sqlite3 └── manage.py with all the templates in main/templates extending base.html in the base templates folder. I am aware that the templates folder in Django can be configured with adding ... 'DIRS': [BASE_DIR/'templates'], ... to the settings.py file on the project folder. this will successfully connect all templates with no problem. However when I change the folder name to something else, i.e. ... 'DIRS': [BASE_DIR/'somethingElse'], ... and rename the folders accordingly, . ├── main │ ├── migrations │ │ └── 0001_initial.py │ ├── somethingElse │ │ ├── create_product.html │ │ └── main.html │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── … -
Django canvas charts disappear after HX-GET
I'm working on a Django project using MDBootstrap to display charts using . Initially, everything works perfectly. However, when I update the information on the dashboard using Htmx's HX-GET, the charts turn blank and fail to display. The issue is that every time I use HX-GET to refresh the view, the charts vanish. They only reappear if I manually refresh the page. <canvas class="card border p-2" data-mdb-chart="pie" data-mdb-labels="{{ req_budget_type_labels }}" data-mdb-dataset-data="{{ req_budget_type_data }}" data-mdb-dataset-background-color="['rgb(59,112,202)', 'rgb(245,111,35)']"> </canvas> I suspect that this might be related to how the charts are rendered after an HX-GET request, but I'm not sure how to resolve it. Has anyone encountered a similar problem, and if so, what steps can I take to ensure that the charts remain visible after an HX-GET update? Thanks in advance for your help! -
Overview of using Authorization Code grant type to authenticate a user in django
I have a django app that Im using drf and ReactJS for my frontend and token authentication. I've been messing around with various packages in Django so that I can implement Social Authentication. I was using implicit authorization but am wanting to switch to an Authorization Code Grant Type. I have been able to make the request, redirect to a callback url on my server where I am able to make a post request to get the user data, refresh token and access token. This is where I have gotten a little stuck because Im not sure how to return those tokens to the frontend. After I authenticate I need to be able to redirect to a "success" page but dont know how to inlcude the access token in that redirect. I know I could use django sessions and just store the tokens there and use that for my authentication but I was hoping to use Token authentication where the user includes their access token to access secure data. I was able to come up with two "working" solutions. With Set-Cookie response = HttpResponseRedirect("/login-success") response.set_cookie("access_token", "<access_token>") return HttpResponseRedirect Appending <access_token> return HttpResponseRedirect("/login-success#<access_token>") # parse token when page is reached I … -
Order Django queryset by annotated field and annotate it again
I need to order Django queryset by annotated field and then annotate result with row number. Steps: Add complex_order field to QuerySet that defines extra logic for future ordering. Order QuerySet by new field and old fields (complex_order, order and id) Annotate sorted QuerySet with number using RowNumber() function. Sample code that almost works queryset.annotate( complex_order=Case( When( Q(foo__type=FooType.ONE.value) | Q(foo__isnull=True) then=Value(1), ), default=Value(0), ), ).order_by( '-complex_order', 'order', 'id' ).annotate( number=Window(expression=RowNumber()) ) But I have a problem with wrong number annotation. After inspecting the SQL query I noticed that annotation happens at the same time with ordering. SELECT "table.id", ... CASE WHEN ("foo"."type" = ONE OR ("foo" IS NULL)) THEN 1 ELSE 0 END AS "complex_order", ROW_NUMBER() OVER () AS "number" FROM ... ORDER BY 32 DESC, "table"."order" ASC, "table"."id" ASC I need to annotate queryset second time, right after sorting it. Or maybe there is a better way to add iterable number for each row in queryset? -
MySQL Query exclude item when blank
I have this issue in my Query which is I can't perform the actual output that I expected, so let say I have this all data in my table named Tev_incoming ID code slashed_out status 1 23-09-00001 1 2 23-09-00002 1 3 23-09-00003 2023-09-18 22:45:46.099847 3 4 23-09-00004 2023-09-18 22:42:14.785251 3 5 23-09-00005 2 8 23-09-00004 3 9 23-09-00003 2 I have this query now SELECT * FROM tev_incoming t1 WHERE (code, id) IN ( SELECT DISTINCT code, MAX(id) FROM tev_incoming GROUP BY code )AND `status` IN (1,3) I have this result to my query provided ID code slashed_out status 1 23-09-00001 1 2 23-09-00002 1 4 23-09-00004 3 Expected output ID code slashed_out status 1 23-09-00001 1 2 23-09-00002 1 As you can see in all data there is duplicate code, it has two duplicate of 23-09-00004 I want to exclude 23-09-00004 because the slashed_out is blank which is status is equals to 3. I tried MAX(id) just to choose the max Id of the duplicate codes. Now How can I modify my query which has conditions I've mention above. -
django.core.exceptions.ImproperlyConfigured: WSGI application 'app.wsgi.application' could not be loaded; Error importing module
INSTALLED_APPS = [ 'base.apps.BaseConfig', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware' 'django.middleware.common.CommonMiddleware', ] WSGI_APPLICATION = 'wsgi.application' I installed everything, even whitenoise and imported all, I still cant get rid of this error -
Connection problem to related_name in save_model function in Django
There is a model called Borrow. Inside BorrowLine model, a ForeignKey is defined with related_name lines. I write BorrowAdmin and BorrowLineInline for Borrow model. Inside BorrowAdmin class I used the save_model function as follows: def save_model(self, request, obj, form, change): obj.save() print(obj.lines) return super(BorrowAdmin, self).save_model(request, obj, form, change) But when I add an instance of Borrow model in Django administration, the following line is printed in the console: borrow.BorrowLine.None and I don't have access to any of the BorrowLine fields. For example, one of its fields is book, but when I call it, it gives this error: 'RelatedManager' object has no attribute 'book' How can I fix this problem and access the class fields? my codes: class Borrow(models.Model): student = models.ForeignKey('student.Student', on_delete=models.CASCADE, related_name='borrow') created_time = models.DateField(auto_now_add=True) delivery_time = models.DateField(default=date.today() + timedelta(days=7), validators=[delivery_time_validator]) delivered = models.BooleanField(default=False) def __str__(self): return str(self.student) class BorrowLine(models.Model): borrow = models.ForeignKey('Borrow', on_delete=models.CASCADE, related_name='lines') book = models.ForeignKey('book.Book', on_delete=models.CASCADE, related_name='lines') def __str__(self): return f'{self.borrow} -> {self.book}' def clean(self): book = self.book if not book.is_available: raise ValidationError(f'The book {book.title} is not available.') class BorrowLineInline(admin.TabularInline): model = BorrowLine extra = 1 max_num = 3 autocomplete_fields = ('book',) @admin.register(Borrow) class BorrowAdmin(admin.ModelAdmin): inlines = (BorrowLineInline,) list_display = ('student', 'created_time', 'delivery_time', 'delivered') search_fields = … -
i am creating a ecommerce website and i want to display size variant of perticular product
my models.py class SizeVariant(models.Model): size_name=models.CharField(max_length=50) price=models.IntegerField(default=0) def __str__(self): return self.size_name class Product(models.Model): product_name=models.CharField(max_length=50) slug=models.SlugField(unique=True, null=True,blank=True) category=models.ForeignKey(Category, on_delete=models.CASCADE, default=1) price=models.IntegerField() desc=models.TextField() image=models.ImageField(upload_to='products') color_variant=models.ManyToManyField(ColorVariant, blank=True) size_variant=models.ManyToManyField(SizeVariant, blank=True) def save(self,*args,**kwargs): self.slug=slugify(self.product_name) super(Product,self).save(*args,kwargs) my html template <div class="product__details__option__size"> <span>Size:</span> {% for size in product.size_variant.all %} <label for="{{size.size_name}}">{{size.size_name}} <input type="radio" > </label> {% endfor %} </div> i have tried using for loop to show all the size variant of particular product but its not working i think there is problem in for loop. because its not taking size variant from database -
TimeoutError while trying to connect SMTP server
I'm trying to make a website that has a message form so that when somebody submits the form it will be present in the django admin panel, but I will get it in e-mail form as well. Here is the port configuration from settings.py: EMAIL_HOST = 'smtp.live.com' EMAIL_HOST_USER = 'mymail@hotmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TSL = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' My model has the fields name, phone, email and message. The function from views.py: def contact(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') message = request.POST.get('message') subject = "WeCreate - Contact Form" content = f"Name: {name}\nPhone: {phone}\nEmail: {email}\nMessage: {message}" from_mail = 'wecreate.designs.srl@hotmail.com' recipient_list = ['wecreate.designs.srl@gmail.com'] send_mail(subject, content, from_mail, recipient_list, fail_silently=False) return redirect('/contact') else: form = MessageForm() return render(request, '../templates/lpadj/form.html', {'form': form}) And the error log: TimeoutError at /contact/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond If I ping the hostname all the packages return. I have triend different ports, changing the EMAIL_USE_TSL/SSL, changing the host to 'smtp.office365.com' and the firwall lets through the … -
I want to generate a token after I verified the user phone number in Django how can I do that
I write an application which send otp from api server and it actually works but after the user verify the phone number I want to generate a token for the user and after that every time the user want to send the request he should post the token to the headers. first I try tokenauth in rest framework but it needs user to be authenticated and it wants username and password which I can't post this to django server. how can I do that with posting phone number and otp this is all of my code """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.2.14. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ "2858-151-240-216-221.ngrok-free.app", "localhost" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'home', 'requests', 'users', 'api', 'otp_api' ] MIDDLEWARE = … -
Django: query to iterate through a column values and search match in another table
I have this 2 tables in my DB : I would like a query to iterate through "company_members-id" and if there is a match in the "table_contacts" id column, return the line as a result I need to use the result in my HTML template to populate a selectbox with something like this : HTML template : <select id="members_in_companies"> {% for option in rendered_result %} <option value="{{ option.id}} "> {{ option.first_name}} + " " + {{ option.last_name}} </option> {% endfor %} </select> For example : iterate through the "Nike" company would populate the selectbox with 2 and 4 as selectbox value and " Ellon Musk" and "Willy Wonka". -
Already registered models django
I want to automate registering models in admin.py here is the code: from django.contrib import admin from django.apps import apps models = apps.get_models() for model in models: try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass Even though i added exception it raises this error raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model Group is already registered in app 'auth'. -
Django filtered and pagination issue
I have a form that filter a queryset, filtering are ok, but if I use pagination links, I loose the filtering value. How can I paginate my filter result ? template table.html {% if is_paginated %} <div class="row"> <div class="col-lg-12"> {% if page_obj.has_other_pages %} <nav> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="{{request.path}}?page=1"> First </a> </li> <li class="page-item"> <a class="page-link" href="{{request.path}}?page={{ page_obj.previous_page_number }}"> Previous </a> </li> {% endif %} {% for page_number in page_obj.paginator.page_range %} {% if page_number <= page_obj.number|add:3 and page_number >= page_obj.number|add:-3 %} {% if page_obj.number == page_number %} <li class="page-item active"> <a class="page-link" href="{{request.path}}?page={{ page_number }}"> {{ page_number }} </a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{{request.path}}?page={{ page_number }}"> {{ page_number }} </a> </li> {% endif %} {% endif %} {% endfor %} views.py: class CmsView(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport template_name = 'table.html' context_object_name = 'table' paginate_by = 10 def get_queryset(self): queryset = super(CmsView, self).get_queryset() field = self.request.GET.get('field') lookup = self.request.GET.get('lookup') value = self.request.GET.get('value') reset = self.request.GET.get('btn-reset') if (field and lookup and value) is not None: field = self.request.GET.getlist('field') lookup = self.request.GET.getlist('lookup') value = self.request.GET.getlist('value') query = dict() for (f,l,v) in zip(field,lookup,value): q = f.lower().replace(" ", "_") + '__' … -
Implement Recurring Classes/Events
I have to implement upcoming classes functionality. Upcoming classes can be repeated weekly or monthly. User will only create it once and repeat logic should be handled from back end. There should be no data duplication. Listing api should return the first 10 upcoming classes where date >= today date. Add live or upcoming Class Upcoming Class listing The last tried solution is: calculate the next 100 dates based on weekly or monthly interval and store it in a list named repeated_dates. write a scheduler which will get the last repeated date and if it less than today date then calculate the next 100 dates and update the list. filter out upcoming classes based on repeated_dates list. The issue is: If I filter out from list, I only get the class object. I don't know which date is matched. If there is only two classes, then it should return 1st 10 classes from these two based on dates >= today date. But in this solution, it will only return 2. Here is the model: REPEAT_CHOICES = ( ('no_repeat', 'Does not repeat'), ('repeat_weekly', 'Repeat Weekly'), ('repeat_monthly', 'Repeat Monthly'), ) def image_path(instance, filename): if filename: extension = filename.split('.')[-1] else: extension = "png" …