Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The form for UpdateView for editing the user profile is not displayed. Django
I'm trying to make an UpdateView to edit user profile without pk or slug using get_object() with self.request.user. But when I run my settings, the form is not shown. Here is my code: urls.py: urlpatterns = [ path('settings/', UserSettings.as_view(), name='settings'), path('<slug:profile_slug>/', ShowUserProfile.as_view(), name='profile'), ] views.py: class UserSettings(LoginRequiredMixin, DataMixin, UpdateView): template_name = 'users/user_settings.html' form_class = UpdateUserForm def get_object(self, *args, **kwargs): return self.request.user def get_success_url(self): return reverse_lazy('profile', kwargs={'profile_slug': self.request.user.userpofile.slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title='Settings') forms.py: class UpdateUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password') widgets = {'username': forms.TextInput(attrs={'class': 'form-control form-input form__input'}), 'password': forms.TextInput(attrs={'class': 'form-control form-input form__input'})} user_settings.html: <form class="form" method="post"> {% csrf_token %} {% for item in form %} <div class="row"> <div class="col-sm-4"> <label class="form__label" for="{{item.id_for_label}}">{{item.label}}: </label> </div> <div class="col-sm-8"> {{item}} </div> </div> <div class="form__errors">{{item.errors}}</div> {% endfor %} <button class="button" type="submit">Set settings</button> </form> It doesn't even throw an error. What I need to do? -
why django displaying inconsistant migration history error while migrating?
hope you are doing well, i am beginner to the django and python, encountered the error while practicing projects from the github which is the custom user model project. i have posted a code below. feel free to ask if you have any questions. i have posted a question in this StackOverflow website to find the solution to the issue. please solve the issue. Thanks a lot for your help. temp/settings.py """ Django settings for temp project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/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/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&ttc6c6nmvo(t0j-@0=ybd$61t(k#yo)*-e2%*5!xm@29+rfv=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tempapp', ] 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 = 'temp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to properly bind a Django form?
I am working on a form that picks a Sale id and submits it to the server. When i submit it to the server a bind it using form = DeleteSalesForm(request.POST) and check it form.is_bound returns False. This is my views.py def delete_sales(request): if not request.user.is_authenticated: return redirect('/login') if request.method == 'GET': form = DeleteSalesForm() print("GET") return render(request, 'inventorymanagment/delete_sales.html', {'form': form}) form = DeleteSalesForm(request.POST) print("checking if form is valid", request.POST, form.is_bound, form) if form.is_valid(): form.delete_sale() # redirect return redirect('/') else: print("sale not deleted") # why is the form invalid? print(form.errors) return render(request, 'inventorymanagment/delete_sales.html', {'form': form}) Here is the traceback: [31/Aug/2022 15:38:36] "POST /delete_sales HTTP/1.1" 200 932 checking if form is valid <QueryDict: {'csrfmiddlewaretoken': ['q3aga7bySuscQ6bb9zrh3pFUlfoIoRoGQnHvQQ8LlbiEfUl1XDSGp2fk3nCj5KJk'], 'id': ['16']}> False <tr> <th><label for="id_id">Sale:</label></th> <td> <select name="id" id="id_id"> <option value="16">id: 16, iphone 6 quantity: 50 price: 30.00 day: 2022-08-31</option> <option value="17">id: 17, Iphone 8 quantity: 70 price: 80.00 day: 2022-08-31</option> </select> </td> </tr> sale not deleted why isn't the form validating? -
Python: Update dictionary with multiple variables?
I've got this code: def update_amounts(self): container = {} a = {'a': self.a_amount} if self.a_mount or self.a_amount is None else {'': ''} container.update(a) b = {'b': self.b_amount} if self.b_amount or self.b_amount is None else {'':''} container.update(b) c = {'c': self.c_amount} if self.c_amount or self.c_amount is None else {'':''} container.update(c) return container And I wanted to know if its possible to do the dict update more efficient than calling the update function three times? Thanks in regard! -
It is shown that value error.. how to figure it out?
@csrf_exempt def login(request): if 'email' in request.session: return redirect(home) if request.method=="POST": email = request.POST["emailOrPhone"] password = request.POST["password"] user=authenticate(email=email,password=password) if user is not None: request.session['email'] = email if (User.objects.filter(email=email).exists()): request.POST.get(User.objects.get(password).only()) if password==User.objects.get(password): return JsonResponse({'statuscode':200}) else: return JsonResponse({'statuscode':400,'message':'password mismatch'}) else: return JsonResponse({'statuscode':400,'message':'not enrolled'}) else: print('invalid credentials') else: return JsonResponse({'statuscode':200}) -
Converting a static HTML website into a fully fledged Django project
I am just getting started with Django. I have a situation where I have a project consisting of a large number of static HTML Pages compiled over time. Now I am in a situation to use a framework and I have opted for it. However I can't just write the whole project in Django because the large number of pages is being a problem for me and my team. As you know maintaining each one is a tedious task and not practical at all for me. So if anyone could suggest a tool or a script to convert entire static website into a Django project will save me a lot of time. Every solution is appreciated. -
Azure B2C : Error in the callback after the edit profile when it tries to get a new token
I try to implement an azure B2C authentication in Django. Unfortunately, there is not much documentation in Django on this topic. However, I managed to write the functions and views to get an id_token and store the user's information in the session. I wanted to integrate the edit profile with the specific authority. The page is perfectly redirected to update the user information. However, after the validation of the new data, I get an error message in the callback when I try to get a new token (function _get_token_from_code). {'error': 'invalid_grant', 'error_description': 'AADB2C90088: The provided grant has not been issued for this endpoint. Actual Value : B2C_1_signupsignin_20220810 and Expected Value : B2C_1_profileediting\r\nCorrelation ID: xxxxxxxxxxx nTimestamp: 2022-08-31 14:58:54Z\r\n'} So it implies the following error in the python execution : _store_user(request, result['id_token_claims']) KeyError: 'id_token_claims' However the new information of the user are correctly saved in the azure. Since I am newbee in this authentication process ? Do we need to generate a new token for the edit profile user flow ? Where does come from this mistake ? Here is the code in djnago : load_dotenv() def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', … -
How to compute cumulative sum of a count field in Django
I have a model that register some kind of event and the date in which it occurs. I need to calculate: 1) the count of events for each date, and 2) the cumulative count of events over time. My model looks something like this: class Event(models.Model): date = models.DateField() ... Calculating 1) is pretty straightforward, but I'm having trouble calculating the cumulative sum. I tried something like this: query_set = Event.objects.values("date") \ .annotate(count=Count("date")) \ .annotate(cumcount=Window(Sum("count"), order_by="date")) But I'm getting this error: Cannot compute Sum('count'): 'count' is an aggregate -
for loop in html gives me the same id
When I click the span on html I cant make variable span id with id="mylink-${i}" I couldn't get this with var mylink = document.getElementById("mylink-"+id) in javascript part. and also at onclick="theFunction(i)" console gives me i is not defined error but it should be defined because of {% for i in data %} i is one of the elements of data how can ı solve this <div class="row sideBar"> {% for i in data %} <div class="row sideBar-body"> <div class="col-sm-9 col-xs-9 sideBar-main"> <div class="row"> <a href= "{% url "start_chat" i.room %}" onclick="theFunction(i)" > <div class="col-sm-8 col-xs-8 sideBar-name"> <span class="name-meta" id="mylink-${i}"> {{i.name}} </span> </div> </a> </div> </div> </div> {% endfor %} </div> const rooms = JSON.parse(document.getElementById('data').textContent) function theFunction(id) { var mylink = document.getElementById("mylink-"+id) } -
Django date events
I have this model: class Prognose(models.Model): Benutzer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Lehrer_Vorname = models.CharField(max_length=255, null=True, blank=True) Lehrer_Nachname = models.CharField(max_length=255, null=True, blank=True) von_Datum = models.DateField(null=True, blank=True) Status = models.CharField(max_length=20, null=True, blank=True) Stunden = models.CharField(max_length=20, null=True, blank=True) bis_Datum = models.DateField(null=True, blank=True) Erstellt_Datum = models.DateField(null=True, blank=True) def __str__(self): return '{}'.format (self.Benutzer) The idea is to schedule an event or a task from one date to another date, and filter those out Like so Employee Name, from 2022-2-2 do this to 2022-3-3 else default (something else without date) and then when I user a filter, I want that it shows either past events within given date or default in future events if date is greater then the event date. Or the current event within given date I saw a lot of examples but have no clue how to implement it into my thing my view class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' my template {% for Ansicht in Ansicht.prognose_set.all %} {{Ansicht.Lehrer_Vorname}} {{Ansicht.Lehrer_Nachname}} {{Ansicht.von_Datum}} {{Ansicht.Status}} {{Ansicht.Stunden}} {{Ansicht.bis_Datum}} {{Ansicht.Erstellt_Datum}} thought about ifs and so on but there must be something more efficient -
How to send email using smtp django rest framework after google policies are updated [closed]
I used the old techniques it did'nt work because gmail disabled Less secure apps features i am trying to send an verification email with django rest framework by smtp if there are any alternatives please help This is the old method in django to send email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_USE_TLS=True EMAIL_HOST_USER=os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD') -
POSTing large number of many-to-many relatedfields in django rest framework
I am building an inventory-like system using Django Rest Framework where I have two models (Category and Location) that I want to allow Users to add to their Filters to keep an eye of them. #models.py class Category (models.Model): code=models.CharField(max_length=10, unique=True) name=models.CharField(max_length=50) class Location (models.Model): code=models.CharField(max_length=10, unique=True) name=models.CharField(max_length=50) class Filter (models.Model): categories = models.ManyToManyField(Category) locations = models.ManyToManyField(Location) name = models.CharField(max_length=50) user = models.ForeignKey(User) I am using ModelSerializers and built-in ModelViewSets. #serializers.py class UserFilterSerializer(serializers.ModelSerializer): categories = serializers.SlugRelatedField( queryset=Category.objects.all(), many=True, slug_field='code', allow_empty=False) location = serializers.SlugRelatedField( queryset=Location.objects.all(), many=True, slug_field='code', allow_empty=False) user = serializers.HiddenField( default=serializers.CreateOnlyDefault(default=serializers.CurrentUserDefault())) class Meta: model = UserTenderSelection fields = ['id', 'categories', 'locations', 'name', 'user'] #views.py class UserFilterView(ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = UserFilterSerializer pagination_class = None def get_queryset(self): return self.request.user.filter_set.prefetch_related("categories", "locations").all() I would like the users to be able to CRUD their filters using REST methods. However, rather than using ids, I needed at some point to use the codes of Category and Location when both on GET responses and POST/PUT requests. e.g. //Example GET Response: { "id": 55, "categories": [ "88-9", "72-3", ], "locations": [ "BE0", "BE1", "DE12" ], "name": "Filter1" } //Example POST request: { "categories": [ "87-9", "77-1", ], "locations": [ "SP75", "DE20" ], "name": "Filter3" } My … -
Django httpResponse open pdf then print window in navigator
I'm running a django app in which i created a view to open a pdf file in the browser for printing purpose. Until this, everything works fine. For a better UX, i'm trying to automatically open the print window (specific to each computer). However, i'm struggling to do so. Aas long as the new window open a pdf but not a html file , i cannot insert JS in my code... Any idea to do so ? Here is my code (i deleted the intermediate steps where i combine some pdfs or add blank page for recto/verso printing...) class CombinePdf (View): def post(self, request, *args, **kwargs): response = HttpResponse(content_type='application/pdf') response['Content-Transfer-Encoding'] = 'binary' file = open("my_pdf.pdf", 'rb') # generate pdf in response try: file.write(response) except Exception as e: return e #open pdf in new window return response Thanks for your help ! -
how can i use socket.io in django for private chat?
I am working in Django and I want to create a chat application so can I use socket.io to private chat? -
How to render many to many field data in Django template
I am able to render list of all courses and list of topics corresponding to the courses in different templates. I need help to view list of all courses and when each course is clicked,a new page should show the list of associated topics models.py class Topic(models.Model): topic_name = models.CharField(max_length=200, null=True) topic_file = models.FileField(upload_to = "topic_file", blank=True, null=True) def __str__(self): return self.topic_name class Course(models.Model): course_name = models.CharField(max_length=200, null=True) course_image = models.ImageField(upload_to="images", blank=True, null=True) related_topic = models.ManyToManyField(Topic) def __str__(self): return self.course_name Views.py def view_course(request): course_list = Course.objects.all() context = {'course_list':course_list} return render(request, 'upskill/view_course.html',context) def course_topic(request,pk): course_topic_list = Course.objects.get(id=pk) var = course_topic_list.related_topic.all context = {'var':var} return render(request, 'upskill/course_topic.html',context) -
My website not responding to http using Elastic beanstalk
I have my domain name on route 53 and got the acm already I set up load balancer on beanstalk Port 80 http 80 Port 443 https 80 http Yet my site won’t respond -
Infinite loop process inside Django application
I need to make a process inside my django application that just after the application starts, it will randomly take one record from Products table (which contains f.e. name, price and rating) and set it into another table named SingleProduct. The process should run inside infinite loop and replace the single product inside SingleProduct table every 15 minutes. How can I do stuff like this? What should I looking for? What do I need it for? I want to display some random product from the database on my home page every 15 minutes. -
Django Throttle on Test Server
I am working on a project and i am using django restframework throttle it works well when using the server either on local or production but when i tries testing the endpoint using testcase it returns an error This is my configurations the default rest framework setting REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { """ anon is for the AnonRateThrottle base on anonymous user user is for the UserRateThrottle base on logged in user ScopedRateThrottle this is just used to set custom throttle just like the authentication, monitor below """ 'anon': '100/min', 'user': '200/min', # the throttle is the amount of time a user can access a route in a minute 'authentication': '3/min', # used on route where the user is not logged in like requesting otp 'monitor': '3/min', }, 'DEFAULT_AUTHENTICATION_CLASSES': ( # currently setting the default authentication for django rest framework to jwt 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } -
Django - Argument of AND must be type boolean, not type character varying
I have a model called Baksgewijs with a models.BooleanField called eindbaksgewijs and I try to on the page of the baksgewijs if eindbaksgewijs is True. Here is my model: class Baksgewijs(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=512, blank=True, default="") date = models.DateField() peloton = models.ManyToManyField(Peloton) eindbaksgewijs = models.BooleanField(default=False) def __str__(self): return self.name My view for displaying a baksgewijs looks something like this: def display_baksgewijs(request, baksgewijs_id): baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) if Baksgewijs.objects.get(id=baksgewijs_id, eindbaksgewijs=True): print("This is true") return render(request, "baksgewijs/baksgewijs_pelotons.html", { "baksgewijs" : baksgewijs }) display_baksgewijs is shown from this url: path("<int:baksgewijs_id>", views.display_baksgewijs, name="baksgewijs") But when I display a baksgewijs, I get the following error: argument of AND must be type boolean, not type character varying Why can I not check whether or not eindbaksgewijs is True in the model? -
USSD menu response with Django not working
AM building a USSD application, in Django with this API https://documenter.getpostman.com/view/7705958/UyrEhaLQ#intro. I get the responses from the API and initialize the data to be processed. But I don't get the menu (MSG) to display on the user phone successfully. The error I get is invalid(empty) response. This is the response to the user’s request. The content provider should provide a response to the request in the same format. USERID = This is the ID provided by NALO to the client MSISDN = The mobile number of the user MSG =This is a mandatory parameter that holds the message to be displayed on the user’s phone MSGTYPE = This indicates whether the session should continue or be terminated (True/false) @csrf_exempt def ussd(request): if request.method == 'GET': html = "<html><body>Nothing here baby!</body></html>" return HttpResponse(html) elif request.method == 'POST': url = "https://99c9-102-176-94-213.ngrok.io/ussd" response_data = json.loads(request.body) code_id = response_data["USERID"] serviceCode = response_data["MSISDN"] type = response_data["MSGTYPE"] session_id = response_data["SESSIONID"] text = response_data["USERDATA"] msg = "" if text == "": msg = "Welcome To TEST Dev" elif text == "1": msg = "This is Test Two" payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type, "USERDATA": text, "SESSIONID": session_id, "MSG": msg, } headers = { 'Content-Type': 'application/json' … -
invalid literal for int() with base 10: b'31 11:15:47.294407' on Django
I have model like this when I created an item. it gives an error like this: invalid literal for int() with base 10: b'31 11:47:21.619913' from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Book(models.Model): name = models.CharField(max_length=255) writer = models.CharField(max_length=255) explanation = models.TextField(blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) publication_date = models.DateTimeField() def __str__(self): return f'{self.name} - {self.writer}' class Comment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='comments') owner = models.CharField(max_length=255) comment = models.TextField(blank=True, null=True) publication_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.rating -
Fill Foreign Key Field in Form Field with Related Record in Django
I have 2 models Office & Meeting. class Office(models.Model): name = models.CharField(verbose_name=u"name",max_length=255) class Meeting(models.Model): meeting_office = models.ForeignKey(Registration,verbose_name=u"Office", on_delete=models.DO_NOTHING, related_name='meeting_office') date = models.DateField(verbose_name=u"Date", null=False, blank=False) I have a form that creates the blank meeting successfully class MeetingForm(ModelForm): class Meta: model = Registration fields = ( 'date', 'meeting_office' ) widgets = { 'date' :forms.TextInput(attrs={'class': 'form-control'}), 'meeting_office' :forms.Select(attrs={'class': 'form-control'}), When I want to have a prefilled form, i have a view that is below def office_add_meeting(request, office_id): office = Office.objects.get(pk=office_id) form = MeetingForm(request.POST or None) if form.is_valid(): form.instance.meeting_office = office form.save() messages.success(request, "Insert Successfull") return HttpResponseRedirect('/office_main') return render(request, 'Office/meeting-form.html', {"form": form, "office_id": office_id}) But the form does not prefill the foreign key field. Confirmed the office_id has been passed to the view successfully. Idon't see why the form is not using the defined instance. Any ideas what could be causing this? Or is there a better way? -
Signup Form Fields are not rendering Django
Here is my code In Urls.py from django.contrib.auth import authenticate, login, logout from .forms import CustomUserCreationForm def registeruser(request): form = CustomUserCreationForm() if request.method == "POST": form = CustomUserCreationForm(request, POST) if form.is_valid(): user = form.save(commit=False) user.save() user = authenticate(request, username=user.username, password=request.POST['password']) if user is not None: login(request, user) return redirect('home') context = {'form' : form} return render(request, 'signup.html', context) urlpatterns = [ path('signup/', registeruser, name='signup'), ] In forms.py from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(self, *args, **kwargs) self.fields['username'].widget.attrs.update({'class' : 'form-control', 'placeholder' : 'Enter Username'}) self.fields['password1'].widget.attrs.update({'class' : 'form-control', 'placeholder' : 'Enter Password'}) self.fields['password2'].widget.attrs.update({'class' : 'form-control', 'placeholder' : 'Re-Enter Password'}) In Signup.html <form class="text-left clearfix" method="POST"> {% csrf_token %} {% for field in forms %} <div class="form-group"> {{field}} </div> {% endfor %} <div class="text-center"> <button type="submit" class="btn btn-main text-center">Sign UP</button> </div> </form> Result is Signup page image I tried alot of settings but got no input field on signup page. It just render nothing. Please help me what am i doing wrong? -
Django (DRF) fails silently
I have been working on a side project using django and django rest framework. There is even an active version running in the cloud currently without any issue. I wanted to make some minor changes on the code base but while using the django admin page it crashes silently. I haven't changed anything in the code until now. [2022-08-31 13:39:10 +0200] [8801] [INFO] Starting gunicorn 20.1.0 [2022-08-31 13:39:10 +0200] [8801] [INFO] Listening at: http://127.0.0.1:8000 (8801) [2022-08-31 13:39:10 +0200] [8801] [INFO] Using worker: sync [2022-08-31 13:39:10 +0200] [8802] [INFO] Booting worker with pid: 8802 [2022-08-31 13:39:18 +0200] [8801] [WARNING] Worker with pid 8802 was terminated due to signal 11 [2022-08-31 13:39:18 +0200] [8810] [INFO] Booting worker with pid: 8810 [2022-08-31 13:39:23 +0200] [8801] [WARNING] Worker with pid 8810 was terminated due to signal 11 [2022-08-31 13:39:23 +0200] [8814] [INFO] Booting worker with pid: 8814 Same happens with python manage.py runserver command. I'm using a virtual environment with python 3.9 -
Django queryset retrieve many-to-many choosen field values
I have a class A(Aid,Aname,manytomanyfield) with a many to many relationship to a class B(Bid,Bname). I have for example three rows in A : Aid,Aname 1,foo 2,bar 3,baz I have for example three rows in B: Bid,Bname 1,foo 2,bar 3,baz With Django ORM I don't really see the relationship class, C which contains for example: Aid,Bid 1,1 1,2 1,3 2,2 2,3 I want all A rows that match for example class B 3,baz rows, in django "A.objects.filter(manytomanyfield=B.get(Bname=baz))": Aid,Aname,Bname 1,foo,baz Is there a way to retrieve all possible values of A relationship with B after filtering? I want: Aid,Aname,Bname,manytomanyfield 1,foo,baz,"foo,bar,baz" In django admin, django produce this result with a new request for every line of the html table. I wonder if we can do this with only one ORM request. Sorry for my english!