Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access javascript variable in Django template
How can I update a javascript variable and use it in a if statement? <button onclick="hire = true"> Hire </button> {% if hire %} //does not work <!-- print something --> {% endif %} <script> let hire = false; </script> I tried to declare the variable in views.py but then I can't update it in the template -
# replacing url template tag in django
On my home page I have my navbar and in my navbar i have a link for the about page and use the template url tag inside a href which looks like this <a href="{% url 'about' %}" class="nav-link">About</a> But when i run my project and view it in a preview window it does not work. When clicked on a # key appears in the url where '/about' should appear. when i use googles dev tools to look at the element # is inside the href instead of the template url tag and when i edit the html in google dev tools and change it to '/about/' the link works and takes me to the about page and i dont know why this is happening here is the code in my /about/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.about, name='about'), ] and here is the code inside my /about/views.py from django.shortcuts import render from django.http import HttpResponse def about(request): return render(request, 'about/about.html') any help is much appreciated and thank you in advance -
how to append result loop into list
How i can append every value that total_penjualan1 give? this code will append just last total_penjualan1 result, what i must change? agen = UserAddress.objects.filter(status="Agen") for tampungini in agen: postingan_list2 = WriteStream.objects.filter(created_at__year=pkk, created_at__month=pk, nama_userr=tampungini.nama) for tampunglain in postingan_list2: get_transactions = api.getaddresstransaction(tampunglain.userr, tampunglain.address) amount = get_transactions['balance'].get('assets')[0].get('qty') total_penjualan1 = total_penjualan1 + amount tampunganjumlah = [] if total_penjualan1 >=1: tampunganjumlah.append(total_penjualan1) total_penjualan1 = 0 -
Django order by to just put all Null at the end
There is the django order by method, here is an example: Purchase.objects.all().order_by(F('price').desc(nulls_last=True)) This will order by the field price with the additional constraint to have all nulls as last. I want something slightly different, take this example: I have a queryset of Purchase with the following prices in THIS EXACT ORDER: [5, None, 13, None, 2] I want to order by so the result is like this [5, 13, 2, None, None] Basically I am looking for a way to simply move all instances where price=None at the end, not affecting the order of the rest of the elements in the queryset. The method in the example at the top would also sort the rest of the elements in descendent order which I do no want. Any help appreciated if this is even possible. -
How to call Django API with Javascript with Authenticated user in Django
I'm using Django for Backend, PostgresSQL as DB and HTML, CSS and Javascript as Frontend. I am calling Django API via Javascript. Where user is adding a product to a cart, and I'm calling the cart with DRF to show all the data to the user. But problem is that, user can see all the data of other user. So, how can authenticated user can see his/her selected product on a cart. Here is a detailed code: views.py adding product to cart def addProduct(request): user = request.user product_id = request.GET.get('product_id') product_cart = Product.objects.get(id=product_id) Cart(user=user, product=product_cart).save() return render(request, 'cart/addtocart.html') Api View (views.py) @api_view(['GET']) def showproduct(request): if request.method == 'GET': result = Cart.objects.all() serialize = productserializers(result, many = True) return Response(serialize.data) serializer.py from .models import * from rest_framework import serializers class productserializers(serializers.ModelSerializer): class Meta: model = Cart fields = '__all__' depth = 1 Javascript to call Django API $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showproduct/', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr> .. ..........</tr>'); $("#table").append(row); } } }); }); NOW, How to show the specific user(authenticated user) there specific cart item. -
Django get all objects that contains a pk of a many to many relationship
I have the following model and I need to retrieve all the subscriptions that have among their connected subscriptions a subscription (of which I know the primary key) In practice I need all the subscriptions that contains a subscription in their connected_subscription field Subscription(models.Model): connected_subscriptions=models.ManyToManyField('self', blank=True) How can I retrieve all the subscriptions? Subscription.objects.filter(connected_subscription__???=subscription_key) -
Ruby on Rails download freezes while downloading
I have installed ruby on rails and about to create a project while downloading the dependencies using git bash it freezes at some point please help. -
How to connect my filter form to filter view Django?
I have such html form on my page: <form action="{% url 'filter' %}" method="get"> <h2>Color:</h2> <input type="checkbox" name="red" id="">Red<br> <input type="checkbox" name="blue" id="">Blue<br> <h2>Material:</h2> <input type="checkbox" name="wood" id="">Wood<br> <input type="checkbox" name="plastic" id="">Plastic<br> <input type="checkbox" name="metal" id="">Metal<br> <button type="submit">Find!</button> </form> My Django model: class Toy(models.Model): COLORS = ( ('Blue', 'Blue'), ('Red', 'Red') ) MATERIALS = ( ('Plastic', 'Plastic'), ('Wood', 'Wood'), ('Metal', 'Metal') ) photo = models.ImageField(upload_to='images/', blank=True) title = models.CharField(max_length=128, blank=False) description = models.CharField(max_length=5000, blank=False) price = models.PositiveIntegerField(blank=False) count = models.PositiveIntegerField(blank=False) color = models.CharField(max_length=128, blank=False, choices=COLORS) material = models.CharField(max_length=128, blank=False, choices=MATERIALS) and my view.py def filter(request): products = Toy.objects.all() material = request.GET.get("material") color = request.GET.get("color") if material: products = products.filter(material__in=material) if color: products = products.filter(color__in=color) return render(request, 'catalog/products.html', {'products': products}) It should check my checkboxes and filter toys from a database that satisfied checked checkboxes -
How to manage password when entegrating sign with google/facebook?
I'm working on register with social media. When I get data from auth token, google or facebook doesn't sent anything about password. How should I manage that? Or should I use same password for every user as above? def register_social_user(provider,email,name): filtered_user_by_email = User.objects.filter(email=email) if filtered_user_by_email.exists(): if provider == filtered_user_by_email[0].auth_provider: registered_user = authenticate(email = email,password="test") return{ 'email': registered_user.email, } else: raise AuthenticationFailed( detail='Please continue your login using '+ filtered_user_by_email[0].auth_provider ) else: user = { 'email':email, 'password': "test" } user = User.objects.create_user(**user) user.is_active = True user.auth_provider = provider user.save() new_user = authenticate(email=email,password = "test") print("new_user : ",new_user) return { 'email':new_user.email } -
Correct way of implementing custom 404 page in Django 3 in production
I’ve tried importing and editing handler404 in urls.py, made sure pointed to right template etc but kept getting server 500 error responses. The only way I could get it to work was changing return render( to return HttpResponseNotFound( but in that case I only get the text representation of ‘mysite.views.404_error.html’ as need to return HTML directly with HttpResponseNotFound. Wondering what is the correct way to return a custom 404 error template. Thanks a lot. -
DRF - Djoser: Setting 'USER_CREATE_PASSWORD_RETYPE': True overrides other User Model fields
from .models import User from djoser.serializers import UserCreateSerializer, UserSerializer class UserCreateSerializer(UserCreateSerializer): phone = serializers.IntegerField() class Meta(UserCreateSerializer.Meta): model = User fields = ['username', 'email', 'password','first_name','last_name','phone'] When 'USER_CREATE_PASSWORD_RETYPE': True is not used DJOSER = { 'LOGIN_FIELD': 'email', # 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'djangopwa.apps.restapi.serializers.UserCreateSerializer', 'user': 'djangopwa.apps.restapi.serializers.UserSerializer', }, } /users { "username": "", "email": "", "password": "", "first_name": "", "last_name": "", "phone": null } when 'USER_CREATE_PASSWORD_RETYPE': True is used only 3 fields are seen. DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'djangopwa.apps.restapi.serializers.UserCreateSerializer', 'user': 'djangopwa.apps.restapi.serializers.UserSerializer', }, } /users { "email": "", "password": "", "re_password": "" } -
Setting up continuous integration with django 3, postgres and gitlab CI
I'm setting up a continuous integration with Django 3 and Gitlab CI. Having done it previously with Django 2 but now I'm struggling to get things done with Django 3. This warning is shown and I'm wondering if it's the reason : /usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py:304: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. And this error at the end : django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known Here is my config : image: python:3.8 services: - postgres:10.17 variables: POSTGRES_DB : db_test POSTGRES_USER : postgres POSTGRES_PASSWORD : "" POSTGRES_HOST : postgres POSTGRES_PORT : 5432 stages: - tests cache: paths: - ~/.cache/pip/ before_script: - python -V - apt-get update && apt install -y -qq python3-pip - pip install -r requirements.txt test: stage: tests variables: DATABASE_URL: "postgres://postgres:postgres@postgres:5432/$POSTGRES_DB" script: - coverage run manage.py test - coverage report coverage: "/TOTAL.+ ([0-9]{1,3}%)/" Will be grateful if somebody can help me fix this. -
PyCharm type hinting issue: 'Expected type 'str', got 'TruncatingCharField' instead'
I have a custom TruncatingCharField that overrides the general CharField in django: class TruncatingCharField(models.CharField): def get_prep_value(self, value): if value: value = value[:self.max_length] return super().get_prep_value(value) I the use it in a model: class Cartoon(models.Model): authors = JSONField(default=list, blank=True, null=True) title = TruncatingCharField(max_length=400, blank=True) Now, when I define the Cartoon model's methods involving TruncatingCharField, I am getting PyCharm's type hinting warnings. Interestingly, they are shown only when I use an 'if,' for example: def one(self): if self.title: a = '(' + self.title # Expected type 'str', got 'TruncatingCharField' instead return self.title + self.title + 'a' # Class 'TruncatingCharField does not define '__add__' method, so the '+' operator cannot be used on its instances def two(self): a = '(' + self.title # no warnings return self.title + self.title + 'a' # no warnings If I change the 'title' field to the general CharField, the warnings disappear. The code is working fine, the problem is just in the distracting warnings. Django support is enable in the settings. What am I doing wrong? -
Getting results with the correct time zone shift (Postgresql, Django)
In my project (Django, using Postgresql) I need to display statistics on the number of registered users by day. In the database, all time fields are stored with the UTC zone. In settings.py parameters set: USE_TZ = True TIME_ZONE = 'Europe/Moscow' Code in a view that returns this stitistic: (date1 & date2 parameters are obtained from a request) self.queryset = User.objects if date1 and date2: self.queryset = self.queryset.filter( created_at__range=(date1, date2.replace(hour=23, minute=59, second=59)) ) self.queryset = self.queryset \ .extra({'day': "date(created_at)"}) \ .values("day") \ .annotate( count=Count("id"), site_count=Count("id", filter=Q(account_type=User.TYPE_WEBSITE)), bot_count=Count("id", filter=Q(account_type=User.TYPE_TELEGRAM)), ) \ .order_by('day') return Response({ "new_users": self.queryset }) Unfortunately, if I specify date parameters both '2021-05-11', then the "wrong" answer will be formed: "new_users": [ { "day": "2021-05-10", "count": 2, "site_count": 1, "bot_count": 1 }, { "day": "2021-05-11", "count": 4, "site_count": 2, "bot_count": 2 } ], We see the two days instead of one. The following SQL is generated by Django: SELECT (date(created_at)) AS "day", COUNT("authentication_user"."id") AS "count", COUNT("authentication_user"."id") FILTER (WHERE "authentication_user"."account_type" = 'Website') AS "site_count", COUNT("authentication_user"."id") FILTER (WHERE "authentication_user"."account_type" = 'Telegram') AS "bot_count" FROM "authentication_user" WHERE "authentication_user"."created_at" BETWEEN '2021-05-11 00:00:00+03:00' AND '2021-05-11 23:59:59+03:00' GROUP BY (date(created_at) ) ORDER BY "day" ASC I experimented and made select queries manually: SELECT * from … -
Django Widgets with Bootstrap
I am trying to stylize my form using bootstrap. As you know bootstrap uses a lot of classes in order to do what it does. By googling I have found to inject some new classes into my form I could use widgets with django. My form is as follows: class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password1'].label = 'Password' self.fields['password2'].label = 'Password Confirmation' self.fields['first_name'].label = 'First Name' self.fields['last_name'].label = 'Last Name' self.fields['password1'].help_text = None self.fields['password2'].help_text = None class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) help_texts = { 'username': None, } widgets = { 'username': forms.TextInput( attrs={ 'class': 'form-control' } ), 'first_name': forms.TextInput( attrs={ 'class': 'form-control' } ), 'last_name': forms.TextInput( attrs={ 'class': 'form-control' } ), 'email': forms.EmailInput( attrs={ 'class': 'form-control' } ), 'password1': forms.PasswordInput( attrs={ 'class': 'form-control' } ), 'password2': forms.PasswordInput( attrs={ 'class': 'form-control' } ) } But for some reason this is only applying the class to the username field in HTML. It does not apply the class 'form-control' to anything else. Is this some simple format issue I am overlooking or am I doing something wrong? Any help is greatly appreciated! -
Uploading multiple files to django database at once not working
I have a problem with django and it is that I cannot handle the files that I am uploading to a File Uploader. The File Uploader that I am using is the one that we can download in Bootstrap Studio called "Drag and Drop Multiple File Form Input upload" whose code (modified with the csrf_token necessary to make it work in django) is the following: HTML <div id="backdrop" class="backdrop backdrop-transition backdrop-dark"> <div class="text-center w-100" style="position: absolute;top: 50%;"> <div class="bg-light border rounded border-success shadow-lg m-auto" style="width: 150px;height: 150px;"><i class="fa fa-upload d-block p-4" style="font-size: 50px;"></i><span>Drop file to attach</span></div> </div> </div> <div class="jumbotron pt-1"> <div class="alert alert-success invisible mt-5" role="alert"><span id="notify"></span></div> <h1>Subir Ficheros<br></h1> <p><label for="form-files"><a class="btn btn-secondary btn-sm" role="button">Seleccione ficheros</a></label>&nbsp;o arrastre los ficheros a cualquier lugar de la página.<br></p> <p id="filecount"><br></p> <div id="list"></div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="form-files" class="invisible" name="files" multiple=""> <button class="btn btn-outline-primary btn-block" type="submit">Procesar</button> <button class="btn btn-danger mt-5" type="reset" onclick="clearFiles()">Reiniciar</button> </form> </div> <div class="text-center bg-light border rounded border-dark shadow-lg p-3"><img id="image_preview" width="100"> <div><button class="btn btn-warning btn-sm m-3" onclick="previewClose()">Cerrar</button></div> </div> JS var dt_allowed=false,readerfiles,drop,fileCount,fileinput,backdrop,notify,list,listwait,listsync=false,image_preview; addEventHandler(window, 'load', function () { init_elements(); init_fileinput(); if (window.FileReader && window.DataTransfer) { init_datatransfer(); } else { notify_msg('Your browser does not support the HTML5 FileReader.<br/> Drag … -
Allauth social_account_added signal not sent
views.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(social_account_added) def after_social_account_added(request, sociallogin, **kwargs): profile = Profile.objects.filter(user=request.user).first() sc = sociallogin.account if DEFAULT_PP in profile.avatar.url: if sc.provider == 'facebook': profile.avatar = f"http://graph.facebook.com/{sociallogin.account.uid}/picture" else: profile.avatar = sc.extra_data[ALL_AUTH_IMAGE_KEYS[sc.provider]] profile.save() The create_profile is fired when a user is created, it creates a new Profile. When a user add their social account, the after_social_account_added is fired, it updates the avatar of the Profile and sets it to the image provided by the Provider. The create_profile works fine, but the after_social_account_added does not run. Any help is highly appreciated. Thank you -
How to Create an object of model A with two random objects of a model B in Django?
I'm trying to create an app that meets two random users in Django. my question is how to create an object Meeting out of 2 random users from my User model, I want something like a for loop so that every 2 users in my database have a meeting! ps: I have only one day left to submit my work i will be so thankful if u help me -
drf-spectacular's extend_schema not working
I recently migrated from drf-yasg to drf-spectacular on my project, but the @extend_schema decorator does not seems to add any information to my generated schema : views.py class SearchView(GenericViewSet): serializer_class = serializers.CriterionSerializer @extend_schema( methods=['post'], summary="Find patients according to search query.", description="Search for patients related to Documents found with the given query.", request=PolymorphicProxySerializer( component_name='Criterion', serializers=[ serializers.TextCriterionSerializer, serializers.GroupCriterionSerializer, ], resource_type_field_name='type', ) ) @action(detail=False, methods=['POST']) def fetch(self, request): serializer = serializers.CriterionSerializer(data=request.data) if not serializer.is_valid(raise_exception=True): return Response(serializer.errors, status=400) return serializers.PatientDocumentSerializer( serializer.create(serializer.validated_data).fetch(), context={'request': request}, many=True ).data And here's the relevant part of the generated schema : /search/fetch/: post: operationId: searchFetchCreate description: '' tags: - search security: - jwtAuth: [] responses: '200': description: No response body Here some additional information for context : urls.py router = routers.DefaultRouter() router.register(r'search', views.SearchView, basename='search') urlpatterns = [ path('', include(router.urls), name="search"), ] SPECTUACULAR_SETTINGS SPECTACULAR_SETTINGS = { 'TITLE': 'API', 'VERSION': '1.0.0', 'CAMELIZE_NAMES': True, 'COMPONENT_SPLIT_REQUEST': True, 'SERVE_PERMISSIONS': ['rest_framework.permissions.AllowAny'], 'SWAGGER_UI_SETTINGS': { 'deepLinking': True, 'filter': True, 'displayRequestDuration': True, 'syntaxHighlight.activate': True, 'syntaxHighlight.theme': 'monokai', }, } Versions : $ pip3 show django drf-spectacular Name: Django Version: 2.2.13 [...] --- Name: drf-spectacular Version: 0.17.1 [...] -
my form not updating database, it sends GET instead of POST
i'm new trying to learn Django by building my e-commerce website. In my terminal i'm getting GET and POST, although i specified action to POST image result in my terminal this code works great before i add translation to my website, but after adding Internationalization to my project, the form is no longer working(the form is not translated because it is comment section) models.py: class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250, blank=True) rate = models.IntegerField(default=1) ip = models.CharField(max_length=20, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject class CommentForm(ModelForm): class Meta: model = Comment fields = ['subject', 'comment', 'rate'] views.py: def addcomment(request, id): url = request.META.get('HTTP_REFERER') # get last url # return HttpResponse(url) if request.method == 'POST': # check post form = CommentForm(request.POST) if form.is_valid(): data = Comment() # create relation with model data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.rate = form.cleaned_data['rate'] data.ip = request.META.get('REMOTE_ADDR') data. product_id = id current_user = request.user data.user_id = current_user.id data.save() # save data to table messages.success(request, "Your review has ben sent. Thank you for your interest.") return … -
I have a table in Django with ManyToManyField. Can't figure out how to update a table entry
I have a table with posts that can have multiple categories, and a table with categories that can have multiple posts. models.py: class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=25) body = models.TextField() image = models.ImageField(blank=True) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts', blank=True) profile = models.ForeignKey('Profile', verbose_name='User', on_delete=models.CASCADE, related_name='profile') def __str__(self): return self.title views.py Сlass ListCategoryView(generic.ListView): def get(self, request, *args, **kwargs): category = kwargs['category'] posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts } return render(request, "list_category.html", context) class ListPostView(generic.ListView): model = Post context_object_name = 'posts' template_name = 'list_post.html' def get_queryset(self): queryset = super().get_queryset() queryset = queryset.order_by('-created_on') return queryset class CreatePostView(LoginRequiredMixin, generic.CreateView): model = Post template_name = 'create_post.html' form_class = PostDocumentForm def post(self, request, *args, **kwargs): blog_form = PostDocumentForm(request.POST, request.FILES) if blog_form.is_valid(): categories = Category.objects.create(name=blog_form.cleaned_data['categories']) title = blog_form.cleaned_data.get('title') body = blog_form.cleaned_data.get('body') profile = request.user.profile image = self.get_image(blog_form) instance = Post.objects.create(title=title, body=body, profile=profile, image=image) instance.categories.set([categories]) return HttpResponseRedirect('/blog/') return render(request, 'create_post.html', context={'form': blog_form}) def get_image(self, form): image = form.cleaned_data.get('image') return image class EditPostView(generic.UpdateView): form_class = PostDocumentForm model = Post template_name = 'edit_post.html' success_url = '/blog/' I can't figure out how to update the post so that the categories are updated as … -
get() returned more than one Log -- it returned 2! in class based views django
I am trying to get a blog post where each post has its unique url with the title views.py: from .models import Log, Comments, Like, Solutions from django.views.generic import ListView, DetailView class LogListView(ListView): model = Log template_name = 'log/home.html' context_object_name = 'item' ordering = ['-created'] class LogDetailView(DetailView): model = Log slug_url_kwarg = 'question' slug_field = 'slug' home.html: {% extends 'log/base.html' %} {% block content %} <title> Error logger - Home</title> {% if item %} {%for i in item %} <div class='m-4'> <div class="container main" style="width: 50vw;"> <a class='link' href="{% url 'log-detail' i.slug %}"><h2 >{{ i.title }}</h2></a> <p>{{ i.content }}</p> <p class='small'>{{ i.created }}</p> </div> </div> {% endfor %} {% else %} <h3 class='container mt-4'>No questions to show</h3> {% endif %} {% endblock content %} urls.py: from django.urls import path from .views import LogListView, LogDetailView urlpatterns = [ path('', LogListView.as_view(), name='home'), path('question/<slug:question>', LogDetailView.as_view(), name='log-detail'), ] I am getting an error stating get() returned more than one Log -- it returned 2! Why am I getting this error and what should I do to fix it? It works fine if I use <int:pk> instead of <slug:question> Edit: I found out that there were two slugs with the same title and hence creating … -
How impact to do request on internal API
please need to know how impact to do request by using Requests on an internal API that returns a JSON response. if it has bad impact on the code could you share with me a better approach? views.py class BookingIndex(TemplateView): def get_context_data(self, **kwargs): account = self.request.user.account context = super().get_context_data(**kwargs) response = requests.get(self.request.build_absolute_uri(reverse('booking:list-appointment')) + f'?farmer_id={account.farmer_id}&account_type={account.account_type}') if response.status_code == 200: data = response.json() if data['appointments']: context['appointments'] = data['appointments'] else: context['appointments'] = [] context['message'] = data['message'] return context class ListUserAppointments(View): def get(self, *args, **kwargs): farmer_id = self.request.GET.get('farmer_id') account_type = self.request.GET.get('account_type') payload = {'farmerid': farmer_id} return JsonResponse({'appointments': appointments}) urls.py path('list-appointment', views.ListUserAppointments.as_view(), name='list-appointment') -
Django: Grouping form fields
I would like to group different formfields like in this example: forms.py a = SelectField() a.group = "Testgroup1" b = CheckboxField() b.group = "Testgroup1" c = IntegerField() c.group = "Testgroup2" d = IntegerField() d.group = "Testgroup2" e = CheckboxField() e.group = "Testgroup3" f = IntegerField() f.group = "Testgroup3" And then in the template something like that: {% for group in form %} {{ group }} {% for field in form %} <div> {{ field }} </div> {% endfor %} {% endfor %} I would like to have a result like that: enter image description here Could someone give my alittle advise how to do that? Thank you in advance. -
Django ORM - How to optimize query for aggregating SUM from different models?
I need to fetch data which contains the total earnings of users within a given date range (from_date and end_date). For example, given from_date=2020-01-01 and end_date=2020-01-07, user 'A' user has a total earnings of 1,000 on 2020-01-01, and then user 'A' has a total earnings of 20,000 on 2020-01-07, the output should be 19,000 since 20000 - 1000 = 19000. In my system, a User model is foreign key with Account model, and a user can have multiple accounts. An AccountModel is foreign key (one is to one) with AccountBonus model, which contains different bonuses that needs to be aggregated in order calculate the total earnings of each user. AccountBonus model inherits the package django-simple-history (https://django-simple-history.readthedocs.io/en/latest/), which creates a new row of data whenever AccountBonus is updated with datetime. Another model is foreign key with Account model which also needs to be aggregated for the total earnings which is AdsCommission model. This is what I'm currently using as a query for this, but it seems like it is too slow even if I have paginator class LIMIT and OFFSET implemented. How can I optimize this query further more? users = User.objects.exclude(groups__name__in=[UserGroups.Admin]) earnings_start = Subquery(AccountBonus.history.filter( Q(history_date__date__gte=from_date) & Q(account__user__pk=OuterRef('id')) ).order_by("history_date")[:1].annotate( total_earnings=Sum(F('itoken_plus_bonus') + …