Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to output data from a linked table in django?
I have a built-in User table and a Note table associated with it by key. class Note(models.Model): header = models.CharField(max_length=100) note_text = models.TextField() data = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py. I tried different ways, don't know how to do that. -
create a subarray of products with unique username (django)
I need an array of customer orders where username are unique and the order quantity should be added on. I got the result using annotate but I need an subarray with product name and respective quantity as sub array. Please check the outputs I got and outputs required below. Thanks in advance views.py orders = Order.objects.values('staff_id', 'staff__username', 'product__name').annotate(quantity=Sum('order_quantity')).order_by() models.py class Product(models.Model): name = models.CharField(max_length=100, choices=PRODUCTS, null = True) quantity = models.PositiveIntegerField(null = True) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) order_quantity = models.PositiveIntegerField(null=True) Output: [ { "staff_id":15, "staff__username":"John", "product__name":"samsung", "quantity":2 }, { "staff_id":15, "staff__username":"John", "product__name":"apple", "quantity":18 }, { "staff_id":16, "staff__username":"test", "product__name":"apple", "quantity":100 } ] Output required [ { "staff_id":15, "staff__username":"John", "product": [ { "product__name":"samsung", "quantity":2 }, { "product__name":"apple", "quantity":18 } ] }, { "staff_id":16, "staff__username":"test", "product": [ { "product__name":"apple", "quantity":100 } ] } ] -
How to merge two model in one fieldset in django admin module
I have two table like below tableA field1 field2 field3 tableB field4 field5 Group 1 field1: textfield (tableA) field3: textfield (tableA) field5: textfield (tableB) Group 2 field2: radiobutton (tableA) field4: textfield (tableB) I tried the solution like form inlines but I want the grouping of fields in one form, not a separate inline form. -
Any help, on why is returning the same status in every object here?
So I have a search endpoint here which will fetch the users that contains certain entry and check if there is any on going friends relationship. My endpoint: path('filter/', SearchUserByStringAPIView.as_view()), My View: class SearchUserByStringAPIView(ListAPIView): queryset = User.objects.all() serializer_class = UserProfileSerializer permission_classes = [IsAuthenticated] def get_queryset(self): queryset = self.queryset.filter(username__icontains=self.request.query_params.get('search')) return queryset My Serializer: class UserProfileSerializer(serializers.ModelSerializer): friendship = serializers.SerializerMethodField() def get_friendship(self, obj): user_obj = self.instance.values_list('id') friends_obj = Friend.objects.filter(Q(receiver=self.context['request'].user) | Q(requester=self.context['request'].user)).values_list('requester', 'receiver', 'status') if not friends_obj: pass else: for f in friends_obj: for i in user_obj: if int(i[0]) in f: return str(f[2]) pass class Meta: model = User fields = ['id', 'username', 'about_me', 'avatar', 'friendship'] My Response : [ { "id": 2, "username": "BB", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 3, "username": "BiG", "about_me": "", "avatar": "http://127.0.0.1:8000/media-files/BigG/Screen_Shot_2022-11-14_at_22.06.55.png", "friendship": "A" }, { "id": 7, "username": "babybabybear", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 13, "username": "shadabjamil", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 14, "username": "sirberkut", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 17, "username": "buddlehman", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 20, "username": "tforbes", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 30, "username": "ol99bg", "about_me": "", "avatar": null, "friendship": … -
How to send mail from users Gmail with Oauth in django
I'm currently working on website project. It's intended to be used by business owners to send invoices to their customers. Each owner is a django user model instance and have an organization model associated to them. Now I don't know how to ask permission from owner to give me access to him account and used these credentials to send invoices to customers. I'm working with django and drf. A minimalist HTML CSS and JavaScript are used for front. I had already done mail sending with Gmail but only for desktop app and I needed to save app credentials to filesystem. Does exist anyway to do it with web app ? Thanks in advance. -
Why doesn't show profile picture from the database?
setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py profile_photo = models.ImageField(null=True,blank=True,upload_to='upload') everything all my pages - my question pages here my database problem I have tried many times and search everything in here. but not yet show profile_image in database. Can anyone tell me what's problem in my page? -
Using Flex To Create a 3x2 Grid | Django Template for loop
I am using Django Templating for my blog, and am adding cards using a for loop. I am trying to create a 3x2 structure of the added cards. Currently, each card takes up an equal amount of space within the div. I am trying to model what they have at Ahrefs Blog. That similar sort of structure for their most recent 6 posts. This is my HTML/Bootstrap 5 code: <div class="latest-articles"> {% for post in post_list %} <div class="card mb-4 mx-3 publishedPost"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text">{{ post.author }} | {{ post.createdOn }}</p> <p class="card-text">{{post.content|slice:":200" }}</p> <a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> This is my CSS code: .latest-articles { display: flex; flex-wrap: wrap; flex-direction: row; justify-content: center; align-items: stretch; padding-top: 0; text-align: center; position: relative; padding: 10px; } .publishedPost { flex: 1; } Any help is massively appreciated -
Pass data in body of API request
I need to update some info in my database using PUT request and Django rest framework So i have this urls and i need to update max_date parameter (pass True or False) but i have 0 ideas how to do it without passing a variable in the url, like api/config/max_date/<str:bool> -
How do I put django cms plugins classes inside multiple files instead of just putting it all inside cms_plugins.py?
So I have a project where I am using Django CMS as the root of my project. First of all I'm new to Django CMS, and I now want to code some plugins to put into my pages. I searched for the solution but everywhere it says that I should put it inside cms_plugins.py. I tried creating a folder named cms_plugins and created an __init__.py file inside it. Then I created the plugin inside a file named ThePlugin.py and coded my plugin the same way I did it in cms_plugins.py. Unfortunately it's not working. If someone can help me I'd be really gratefull. Thanks. -
Is Django only good for web applications where a user logs in? [closed]
Is Django only good for web applications where a user logs in? The reason I ask is because I recently learned Django and built a website where a user could sign up, input their measurements, and the website tells them how many calories they should eat. Is there a way to build this website in a way where the user doesn't need to sign up or log in? I've seen Javascript-based exampled where data is carried from page to page using cookies but using Python / Django the only way I know how to do this is by using a database. -
How to generate newsfeed / timeline consisting of different types of contents?
I have to implement a newsfeed for an application where I need to show different types of content. And in the future, some new types of content may come. I have the following idea in my mind at a high level. At this point of time, I'm not concerned about ranking, caching, etc. My focus is to generate newsfeeds having different types of content. class ContentType1(models.Model): pass class ContentType2(models.Model): pass class ContentType3(models.Model): pass class Content(models.Model): c_type = models.CharField( max_length=6, choices=[ ('TYPE1', 'Type 1 content'), ('TYPE2', 'Type 2 content'), ('TYPE3', 'Type 3 content') ] ) type_1 = models.ForeignKey(ContentType1, null=True, blank=True) type_2 = models.ForeignKey(ContentType2, null=True, blank=True) type_3 = models.ForeignKey(ContentType3, null=True, blank=True) The idea is to have a general Content model having separate fields for every type of content and a field named c_type which determines the type of the content and guides to access the corresponding field. And responding to users' requests from the Content queryset. I'm not fully satisfied with the approach, looking for a better approach maybe something with polymorphism or any better approach using Django. -
You're using the staticfiles app without having set the required STATIC_URL setting - Django
I have 5 months of experience in django and I can not just find the solution of the error which I encounter. I think it depends on frontend files, I can not deal with static files right now Recently, I have been building a chat app called PyChatt Whole project available on Github -> here Please I need your help urgently!!! traceback: Traceback (most recent call last): File "C:\Users\pytho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\pytho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "D:\python_projects\Webogram\Internal\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\core\management\commands\runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\management\commands\runserver.py", line 35, in get_handler return StaticFilesHandler(handler) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\handlers.py", line 75, in __init__ self.base_url = urlparse(self.get_base_url()) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\handlers.py", line 30, in get_base_url utils.check_settings() File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\utils.py", line 49, in check_settings raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the required STATIC_URL setting. and settings.py: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-pke21+-&vpt2=ka6$a_=x5vz-@#_)o^ro#eet+h03sy&y-l+8w' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'UsersAuthentication', 'MessageHandleEngine', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { … -
Check box field in django forms showing error
Based on my django project I want to add multiple users to a group and I'm trying to do this using a form. But when I try adding choices via CheckBoxSelectMultiple() widget its not working as expected. models.py file from django.db import models from members.models import User from django.contrib.auth.models import Group class Sprint(models.Model): status_choice = [('Working','Working'), ('Closed','Closed')] sprint_name = models.CharField(max_length=180) sprint_created = models.DateTimeField(auto_now= True) lead = models.ForeignKey(User, on_delete=models.CASCADE, related_name='team_lead') sprint_members = models.ForeignKey(Group, on_delete=models.CASCADE, related_name = "member") sprint_period = models.PositiveIntegerField() sprint_status = models.CharField(max_length=10, choices=status_choice, default='Working') forms.py file from django import forms from .models import Sprint from members.models import User from django.core.exceptions import ValidationError from django.contrib.auth.models import Group class SprintForm(forms.Form): sprint_name = forms.CharField() sprint_period = forms.IntegerField(label="Sprint period (in days)", min_value=7) lead = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'), label="Team Lead") sprint_members = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'), widget= forms.CheckboxSelectMultiple(), label="Team members") # class Meta: # model = Sprint # fields = ['sprint_name', 'lead', 'sprint_period', 'sprint_members'] def clean(self): cleaned_data = super().clean() lead = cleaned_data.get('lead') team = cleaned_data.get('sprint_members') if team and lead: if lead in team: raise ValidationError('Team lead cant be in team') def save(self): team = Group.objects.get_or_create(name=f'team{self.cleaned_data["sprint_name"]}')[0] for team_member in self.cleaned_data['sprint_members']: team.user_set.add(team_member) Sprint.objects.update_or_create( sprint_name=self.cleaned_data["sprint_name"], lead=self.cleaned_data["lead"], sprint_period=self.cleaned_data["sprint_period"], _members=team ) views.py file class SprintCreationView(generic.FormView): model = Sprint template_name … -
WebSocket dosn't work with postman (django channels)
I have a Django project which I run locally on my mac. And I use channels to create websocket connection. And an interesting thing happened: The web socket works when I try to connect through .html file: myTemplate.html const ws = new WebSocket( 'ws://' + window.location.host +'/ws/test/?token=' +'**mytoken**' );' I can send, and receive messages. But the same URL doesn't work in postman or https://websocketking.com/ Firstly, I thought it is because I run server locally. But on real server nothing works at all. I searched all stackoverflow and implement everything - to no avail. asgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev') django.setup() from channels.routing import ProtocolTypeRouter,get_default_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import path, re_path from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack from myapp import consumers, routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) ), }) settings ASGI_APPLICATION = 'spacetime.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', *** ] vccode console Django version 4.1.2, using settings 'spacetime.settings.dev' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the … -
Django. Asynchronous requests are executed in only one async event loop
I'm trying to find out how to use Django 4.0 asynchronous request support. There is one very strange thing I can't understand: Django (uvicorn or asgi.py) creates only one event loop for two different views, despite the fact that I specified max_workers=8 in uvicorn settings. This can lead to a case, when we have a lot of views (ex. 100) and in this views there are a lot of CPU-bound logic (ex: conditions, loops, calculations, etc) and a lot of IO-bound logic. Using async/await we speed up and optimize all IO-bound operations, but our CPU-bound logic is slowing down our event-loop. Instead of using event-loop for every process (worker), it uses only one loop, while other workers (7) stand still. I think, it isn't a normal behavior. What do you think? Check the code below to see more details: views.py import asyncio import os import random import time from django.http import HttpResponse from django.utils.decorators import classonlymethod from django.views import View class AsyncBaseView(View): @classonlymethod def as_view(cls, **initkwargs): view = super().as_view(**initkwargs) view._is_coroutine = asyncio.coroutines._is_coroutine return view class AsyncTestView(AsyncBaseView): async def get(self, request, *args, **kwargs): r = random.randint(1,4) print('Recieved', r) print('PID = ', os.getpid()) # Simulate long code-inside operations (conditions, loops, calculations, ets) … -
Trying to make Follow button dynamic. Follow, Unfollow feature addition
If we click, follow button it should update followers then show unfollow and if clicked again it should show follow, decrementing followers. urls.py urlpatterns = [ path('',views.index, name = 'index'), path('signup',views.signup, name = 'signup'), path('signin',views.signin, name = 'signin'), path('logout',views.logout, name = 'logout'), path('settings',views.settings, name = 'settings'), path('profile/<str:pk>',views.profile, name = 'profile'), path('like-post',views.like_post, name = 'like-post'), path('upload',views.upload, name = 'upload'), path('follow',views.follow, name = 'follow'), ] profile.html <span style="color: white; font-size: 27px;"><b>{{user_followers}} followers</b></span> <span style="color: white; font-size: 27px;"><b>{{user_following}} following</b></span> <input type="hidden" value="{{user.username}}" name="follower"> <input type="hidden" value="{{user_objects.username}}" name="user"> {% if user_object.username == user.username%} <a href = "/settings" data-ripple="">Account Settings</a> {% else %} <a data-ripple="">{{button_text}}</a> {% endif %} views.py @login_required(login_url='signin') def profile(request, pk): user_object = User.objects.get(username=pk) user_profile = Profile.objects.get(user=user_object) user_posts = Post.objects.filter(user=pk) user_post_length = len(user_posts) follower = request.user.username user=pk if FollowersCount.objects.filter(follower = follower, user = user).first(): button_text = 'Unfollow' else: button_text = 'Follow' user_followers = len(FollowersCount.objects.filter(user=pk)) user_following = len(FollowersCount.objects.filter(follower=pk)) context = { 'user_object': user_object, 'user_profile': user_profile, 'user_posts':user_posts, 'user_post_length':user_post_length, 'button_text': button_text, 'user_followers': user_followers, 'user_following': user_following } return render(request, 'profile.html', context) models.py class FollowersCount(models.Model): follower = models.CharField(max_length=100) user = models.CharField(max_length=100) def __str__(self): return self.user admin.py from django.contrib import admin from .models import Profile, Post, LikePost, FollowersCount # Register your models here. admin.site.register(Profile) admin.site.register(Post) admin.site.register(LikePost) admin.site.register(FollowersCount) I have … -
(Many to one relation) not forwarding sub-fields of child object when creating parent object
I am creating a Project object, with a milestone child object as a field of project, using ForeignKey and nested-serializers. first i wrote the test for creating milestone(s) on creating a new project : PROJECTS_URL = reverse('project:project-list') def test_create_project_with_new_milestones(self): """Test creating project with milestones""" payload = { 'title': 'Test', 'time_hours': 10, 'milestones': [ { 'title': 'FirstMilestone', 'hierarchycal_order': 1, 'order': 1 }, { 'title': 'FirstMilestoneSub', 'hierarchycal_order': 1, 'order': 2 }, { 'title': 'SecondMilestone', 'hierarchycal_order': 2, 'order': 1 }, ], } res = self.client.post(PROJECTS_URL, payload, format='json') """ ... + rest of the test ...""" Then updated serializers.py adding function to create milestones and updating the create function adding creation of milestones in a similar way as i did for tags(working for tags but tags is many to many relation ship and has only a name field): class ProjectSerializer(serializers.ModelSerializer): """Serializer for projects""" tags = TagSerializer(many=True, required=False) milestones = MilestoneSerializer(many=True, required=False) class Meta: model = Project fields = ['id', 'title', 'time_hours', 'link', 'tags', 'milestones'] read_only_fields = ['id'] ... def _create_milestones(self, milestones, project): """Handle creating milestones as needed.""" auth_user = self.context['request'].user for milestone in milestones: milestone_obj, created = Milestone.objects.create( user=auth_user, project=project, **milestone, ) project.milestones.add(milestone_obj) def create(self, validated_data): """Create a project.""" tags = validated_data.pop('tags', []) milestones … -
The view "../{api}" didn't return an HttpResponse object. It returned None instead. Unable to make api fetch request due to following error?:
I have a views.py containing an api. I am calling a function that does a fetch request. I get an error relating to my code not returning a specific object type. Setup: vuejs frontend, django backend Function in methods: add_auction_item(){ console.log('testing..'); if (this.item_name.length > 0){ var auc_item = { 'item_name': this.item_name, 'item_condition': this.item_condition, 'posted_by': this.posted_by, 'created_at': this.created_at }; this.auction_items.unshift(auc_item) fetch('/add_auction_item_api/', { method:'POST', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken':'{{ csrf_token }}', 'Content-Type':'application/json' }, body: JSON.stringify(auc_item) }) } Api in views.py: @login_required @csrf_exempt def add_auction_item_api(request): if request.method=='POST': data = json.loads(request.body) item_nme = data['item_name'] item_cond = data['item_condition'] item_pstd_by = data['posted_by'] Item.objects.create(item_name=item_nme, item_condition=item_cond,posted_by=item_pstd_by) return JsonResponse({'new':'updated'}) -
How can I access Django model fields in form via JavaScript to auto calculate fa ield?
I would like to auto-calculate my deposit amount height in a form. Therefore, I included JavaScript to make it happen. The idea: After entering the net into the form, the suitable deposit height will be displayed in the amount field. And there is nothing to do for the user here. I really appreciate any suggestions since I am total beginner with Django. I tried to access the field via known methods like netObj.fishing_type and ['fishing_type'] but I feel like this is not the issue. Somehow I can't access the model fields of the triggered record. html file {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content%} <p> </p> <div class ="form-group"> <form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <script> // Get the input elements by targeting their id: const net_input = document.getElementById('id_net'); const vessel_input = document.getElementById('id_vessel'); const amount = document.getElementById('id_amount'); // Create variables for what the user inputs, and the output: let netObj = 0; let vesselObj = 0; let height = 0; // Add an event listener to 'listen' to what the user types into the inputs: net_input.addEventListener('input', e => { netObj = e.target.value; console.log(netObj); updateAmount() }); // Update the value of net … -
How to test file upload in pytest?
How to serializer a file object while using json.dumps ? I 'm using pytest for testing file upload in django and I 've this function def test_file_upload(self): # file_content is a bytest object request = client.patch( "/fake-url/", json.dumps({"file" : file_content}), content_type="application/json", ) I 've tried to set the file_content as a bytes object but I 'm getting this error TypeError: Object of type bytes is not JSON serializable I need to send the whole file to my endpoint as json serialized -
How to rollback changes if error into chain celery django task?
The scheme is: chain(group | result_task). How can I rollback changes in database if error? Is it possible to use database transactions in this situation? -
my static folder where I place my js ans css files is not at the root of my django project. How to call these satic files in the template?
Here is the configuration of my static_root variable: STATIC_ROOT = [os.path.join(BASE_DIR,'vol/web/static')] My templates are at the root of the project. TEMPLATES={ ... 'DIRS':[os.path.join(BASE_DIR, 'templates')], ... } This is how I call my bootstrap.min.css file in a project template: <link rel="stylesheet" href="{% static 'assets/plugins/bootstrap/css/bootstrap.min.css' %}"> But it doesn't work because the file is not loaded. What's the right way to do it? -
Receiving an Operation Error when accessing Django Admin page
While in the admin page of my django project, I get an error relating to an ID having no column. Method type is GET. The error I get is: OperationalError at /admin/../item/ no such column: app_item.written_by_id So I attempt to create for the column it does not have and I get an error about the two clashing. So what exactly should I do to resolve this as I am merely trying to access a subheading in my admin page? class Item(models.Model): written by = models.ForeignKey(CustomUser, on_delete=models.CASCADE) # written_by_id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) -
Sending a variable to a Django backend for processing
I am working on a payment processing script. The front end is a javascript module and the backend is a Django app. I seem to be missing something with my code and I can't pinpoint it. Here are the parts of the app: {% extends 'dash.html' %} {% load static %} {% block 'title' %} Subscription | Simpledocs {% endblock %} {% block extra_title %}<h2>Subscription</h2>{% endblock %} {% block paymentInfo %} {% endblock %} {% block content %} <div class="columns is-centered"> <div class="column is-5 box"> {% if company.paid_till < today %} <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="content"> <h1 class="title is-4"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Account is not active </h1> Your company <strong>{{user_organization.organization}}</strong> is not active. Please renew the subscription.<br> </div> {% else %} <p class="label">We have great subcription options for you. Choose from our list either for monthly or annual plans</p><br> {% endif %} <h2>Subscription Packages</h2><br> <div class="select"> <select name="search" onchange="updateButtonDataAmount(event)" > <option value="select-a-plan">Select A Plan</option> <option value="7.99">Starter - Monthly ($7.99/Month)</option> <option value="79.00">Starter - Annually ($79.00/Year)</option> <option value="49.00">Business - Monthly ($49.90/Month)</option> <option value="499.00">Business - Annually ($499.00/Year)</option> </select> </form> </div><br><br> <div id="searched-subs"></div><br><br> <button class="intaSendPayButton button is-btn-mycolor is-fullwidth" data-amount="10" data-currency="KES" data-email="joe@doe.com" data-first_name="JOE" data-last_name="DOE" data-country="KE"> Pay Now </button><br> </div> </div> … -
Django Ordering by a specific ManyToMany Field
the following structure is given: `python class MovieTranslation: lang=CharField() title=CharField() class Movie: key = CharField() movie_translations = ManyToManyField(MovieTranslation) ` Now for example, for english users I want to sort by the english MovieTranslation of a Movie? I want to use it in a ViewSet as a Filterset class. I think it should be something like order_by(movie_translations__name='en'__title). The last part of course doesn't work. I found solutions, for filtering before, but I do not think filtering for english Translations work, since then I get a list of Movie Objects who have an english Title, but could still have other languages. I want to sort specifically by the field of a manytomany field. So is there a way to order by a specific ManyToMany Instance (i.e. all MovieTranslations where the name is 'en' ) ? I was thinking about annotate, but had the same problems I am thinking now that maybe joining with a specific ManyToMany field could work.