Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot receive data in Django View from frontend through Ajax
I am trying to post data from frontend to Django view, and render the view inside another page, but I don't receive any data from frontend. Any help is appreciated! Thanks in advance. Jquery: <script> window.getDisplayConfirmation = function(ele){ var row = $(ele).closest('tr'); var displayObjectId1 = row.find('td').eq(2).text() console.log(typeof(displayObjectId1)) console.log(displayObjectId1) var displayObjectId = parseInt(displayObjectId1) $.ajax({ url:'/detailedData/', data: { 'displayObjectId': displayObjectId }, success: function(){ alert('Vote successful!'); $("#dataDisplayArea").load("/detailedData/"); }, }); }; </script> View: def detailedData(request): displayObjectId = request.GET.get('displayObjectId') displayObjects = TemporaryModel.objects.get(id=displayObjectId) return render(request, 'frontend/detailedData.html', {'obj': displayObjects,"receivedObjectId":displayObjectId}) html: this is part of my table in this html page <td ><button id = "showButton" class ="btn btn-primary btn-xs" onclick="getDisplayConfirmation(this)"> S </button></td> <td ><button id = "deleteButton" class = "btn btn-primary btn-xs" onclick="getDeleteConfirmation(this)"> D</button></td> <td >{{ obj.id}}</td> I also have this part on the same html page to include rendered page as a sub-page: <div id ="dataDisplayArea"> {% include 'frontend/detailedData.html' %} </div> urls: urlpatterns = [ path('', auth_views.login, {'template_name': 'registration/login.html'}, name='login'), path('panelOne/', views.panelOne, name='panelOne'), path('panelTwo/', views.panelTwo, name='panelTwo'), path('detailedData/', views.detailedData, name='detailedData'), path('panelThree/', PanelThreeView.as_view(), name='panelThree'), ] -
Preserving value of variables between subsequent requests in Python Django
I have a Django application to log the character sequences from an autocomplete interface. Each time a call is made to the server, the parameters are added to a list and when the user submits the query, the list is written to a file. Since I am not sure how to preserve the list between subsequent calls, I relied on a global variable say query_logger. Now I can preserve the list in the following way: def log_query(query, completions, submitted=False): global query_logger if query_logger is None: query_logger = list() query_logger.append(query, completions, submitted) if submitted: query_logger = None While this hack works for a single client sending requests I don't think this is a stable solution when requests come from multiple clients. My question is two-fold: What is the order of execution of requests: Do they follow first come first serve (especially if the requests are asynchronous)? What is a better approach for doing this? -
Automatic file download in Django
I am creating a file download functionality on link click from admin panel in django. I am using FieleField for storing the files. For the download purpose I researched and found help on stackoverflow. After using that help, I have the following code for file download (with some minor changes of my own). def pdf_download(request): #print("request: ", request.META["PATH_INFO"]) a = request.META["PATH_INFO"] #print(type(a)) a = a.split("/") a = a[-1] #print(a) #print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"\\router_specifications\\"+a ,"rb") as pdf: #Here router_specifications is the directory on local storage where the uploaded files are being stored. response = HttpResponse(pdf.read()) #can add ', content_type = "application/pdf" as a specific pdf parameter' response["Content-Disposition"] = "attachment; filename ="+a pdf.close() return response Now, when I this code runs in my laptop, the file is downloaded automatically. but, when I switch to some other laptop, it asks me where should I save the file i.e. it's not automatically getting downloaded. What changes should I do so that the file automatically gets downloaded without asking for manual save. Requesting help at the earliest. -
Form input to a template
I am trying to pass the form input to a template. However, the template is rendering without the form input. I am sure that I am doing some silly mistake, possibly either in the context of views.py or in results.html, but I can't figure out what! Thanks in advance :) models.py from django.db import models class Location(models.Model): """ Model representing a Location, attached to Hashtag objects through a M2M relationship """ name = models.CharField(max_length=1400) def __str__(self): return self.name class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) locations = models.ManyToManyField(Location, blank=True) def __str__(self): """ String for representing the Model object (search_text) """ return self.search_text def display_locations(self): """ Creates a list of the locations """ # Return a list of location names attached to the Hashtag model return self.locations.values_list('name', flat=True).all() forms.py from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from .models import Location, Hashtag class SearchHashtagForm(ModelForm): """ ModelForm for user to search by hashtag """ def clean_hashtag(self): data = self.cleaned_data['search_text'] # Check search_query doesn't include '#'. If so, remove it. if data[0] == '#': data = data[1:] # return the cleaned data return data class Meta: model = … -
How do I change the name of the Django admin page?
I'm leaning Django I saw django tutorial part7 and I wanted to rename of name the django admin page so I did it but it hasn't worked..... mysite/mysite/settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] mysite/templates/admin/base_site.html {% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('mysite') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} I renamed to mysite from Django administration -
compare table last two rows value and highlighted update field
check table rows last recently two update filled and compare updated value and highlighted that change def highlight(request): filter11 = request.session.get('orderId') if request.method=="GET": client_data=request.GET.get("client_data") invoice_data = request.GET.get("invoice_data") user_data = request.GET.get("user_data")//its get value through models user = request.user if client_data: resp = Clients.history.filter(id=client_data).order_by('name') if resp and len(resp)>3: resp=resp[:3] data="client_data" htmldata=render(request,'temp_logs1.html',{'resp':resp}) invoice_data = request.GET.get("invoice_data") if invoice_data: resp = Invoice.history.filter(client=invoice_data).order_by('-history_date') if resp and len (resp)>3: resp = resp[:3] data="invoice_data" htmldata=render(request,'temp_logs.html',{'resp':resp}) if user_data: resp = User.history.filter(id=user_data).order_by('history_date') if resp and len (resp)>3: resp = resp[:3]//getting last recently 3 updated field data="user_data" htmldata=render(request,'temp_logs2.html',{'resp':resp}) //its all depends django historical records return HttpResponse(htmldata, status=201) -
QueryRenderer request payload different than one sent by GraphiQL
I have a QueryRenderer whose fetch payload is slightly different from the one GraphiQL sends to my endpoint. GraphiQL gets a response with data back, but the QueryRenderer's response is empty. grove.gql_schema.py: from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Tree class TreeNode(DjangoObjectType): class Meta: model = Tree filter_fields = ['owner'] interfaces = (relay.Node,) class Query(ObjectType): def resolve_my_trees(self, info): if not info.context.user.is_authenticated: return Tree.objects.none() else: return Tree.objects.filter(owner=info.context.user) my_trees = DjangoFilterConnectionField(TreeNode) tree = relay.Node.Field(TreeNode) project.gql_schema: class Query(grove.gql_schema.Query, graphene.ObjectType): pass schema = graphene.Schema(query=Query) With that setup, I can successfully run the following query in GraphiQL query { myTrees { edges { node { id } } } } So far so good, but now I'm trying to build a client-side component that can use this query. jsapp/components/index.jsx: import React from 'react'; import {graphql, QueryRenderer} from 'react-relay'; import environment from '../relay_env' const myTreesQuery = graphql` query componentsMyTreesQuery { myTrees { edges { node { id } } } } `; export default class App extends React.Component { render() { return ( <QueryRenderer environment={environment} query={myTreesQuery} variables={{}} render={({error, props}) => { if (error) { return <div>Error!</div>; } if (!props) { return <div>Loading...</div>; } return <div>User ID: {props.edges}</div>; }} /> ); } } … -
TypeError: is_valid() missing 1 required positional argument: 'self'
if RegistrationForm.is_valid() and employeeForm.is_valid(): TypeError: is_valid() missing 1 required positional argument: 'self' Im having this error which i cant find the source.Where am i missing something ? @transaction.atomic def create_view(request): if request.method == 'POST': user_form = RegistrationForm(request.POST) profile_form = employeeForm(request.POST or None,request.FILES or None) if RegistrationForm.is_valid() and employeeForm.is_valid(): user = RegistrationForm.save() user.refresh_from_db() profile_form = employeeForm(request.POST, instance=user.employeemodel) profile_form.full_clean() profile_form.save() return redirect('emp_list') else: user_form = RegistrationForm() profile_form = employeeForm() return render(request,'create_employee.html',{'userform':user_form,'profileform':profile_form}) -
runsslserver command not working in django with executable built with pyinstaller
I am using runsslserver command to run django application. on command line before generating its executable and its working fine For example, Validating models... System check identified no issues (0 silenced). June 11, 2018 - 16:57:54 Django version 2.0.4, using settings 'XApp.settings' Starting development server at https://0:8002/ Quit the server with CTRL-BREAK. Settings.py INSTALLED_APPS = (... "sslserver", ... ) when i built executable using pyinstaller (i already included package in .spec file e.g, Analysis(hiddenimports=[...,'sslserver',...]) and used with command XApp.exe runsslserver 8000 then it shows message like, Unknown command: 'runsslserver' Type 'manage.py help' for usage. How do i resolve it? -
django change cache settings when testing
I'm using redis as my cache server. When a user created , the post_save signal will save his information in redis with key="user_info_<userid>". However, when I run the unit test and create the user, the information will be overwritten. How can I prevent this. How can I change the cache storage when testing? -
Trouble getting started with Django Channels
I am creating my own application inspired from the Channels 2.0 tutorial. However, I am unable to establish WebSocket connection. Daphne complains for 404 saying the websocket URL can not be found. I am not sure where the error is My directory structure is as follows - SomeDashboardProject |-- Dashboard |-- asgi.py |-- settings.py |-- urls.py |-- routing.py |-- ... |-- WebSocketTest |-- consumers.py |-- routing.py |-- urls.py |-- views.py |-- templates |-- WebSocketTest |-- index.html WebSocketTest/templates/WebSocketTest/Index.html <script type="text/javascript"> var dashboard_id = '1'; var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/dboard/' + dashboard_id + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); console.log(data); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; </script> WebSocketTest/views.py def index(request): return render(request, 'WebSocketTest/index.html', {}) WebSocketTest/consumers.py class TestConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print(message) WebSocketTest/routing.py websocket_urlpatterns = [ url(r'^ws/dboard/(?P<dashboard_id>\d+)/$', consumers.TestConsumer), ] WebSocketTest/urls.py urlpatterns = [ url(r'^$', views.index, name='index'), ] Dashboard/routing.py application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( WebSocketTest.routing.websocket_urlpatterns ) ) }) Dashboard/urls.py urlpatterns = [ url(r'^test/', include('websockettest.urls'), name='test'), ] Daphne Error log 2018-06-12 02:41:58,857 WARNING Not Found: /ws/dboard/1/ None - - [12/Jun/2018:02:41:58] "GET /ws/dboard/1/" 404 974 -
vue.js - How to disable a button after clicking a button using vue.js
I am making a voting application. I want to disabled the button once clicking the voting button.Please tell me how to disabled the button. template <v-btn v-for="choice in data.choices" @click="doVote(choice.id)" color="success" v-bind:key="choice.id"> votes: {{ choice.votes }} </v-btn> script data () { return { vote: null, questions: [], } }, methods: { fetchData () { this.$request.questions.list().then(res => { this.questions = res.data.results }) }, // add votes doVote (vote) { if (!vote) { return } this.$request.questions.vote(vote).then(res => { this.fetchData() }) }, mounted () { this.fetchData() }, -
Django date filter not working with datetime value
Environment: PostgreSQL, Django 1.10 I have a django model.datetime field named created_at with auto_not_add=True. When I output the date in a template it is displayed as "2018-06-01T15:17:08.524939-07:00" I have attempted to use the Django date filter to output the date in a friendly format such as: {{ created_at|date:"M d, G:i" }} but the date filter fails and there is no output at all. What is the correct way to format the datetime object so that it shows as needed in the template? -
Django URLResolver error
I am trying to host a Django app on windows server using IIS using wfastcgi. After creating a new django project using django-admin.py startproject foo,the admin page opens up fine when I run it with the django server python manage.py runserver. However when I try to access it through 127.0.0.1/foo I get the Django 404 error saying : Using the URLconf defined in foo.urls, Django tried these URL patterns, in this order: admin/ The current path, foo, didn't match any of these. The log file shows that it is a URLResolver error .Following is the log file 2018-06-11 17:42:19,210 django.template DEBUG Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "D:\Python_venvs\foo\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "D:\Python_venvs\foo\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response resolver_match = resolver.resolve(request.path_info) File "D:\Python_venvs\foo\lib\site-packages\django\urls\resolvers.py", line 523, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>]], 'path': 'foo/'} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Python_venvs\foo\lib\site-packages\django\template\base.py", line 835, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Python_venvs\foo\lib\site-packages\django\template\base.py", line 843, in … -
Is there a good example somewhere of how to use django defender plugin?
I have django defender and redis installed on my django app as instructed here: https://github.com/kencochrane/django-defender However, I seem to be having issues figuring out how to properly use it. When I login successfully it shows each attempt in the attempt database, but no one in the blocked table when I create a user, logout, and fail to login 5+ times. Does anyone know where to find any good examples of django defender being used anywhere that I can look at? In settings I have redis cache setup to: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, } } -
Django: Can't display data from an abstract model in template
I'm trying to display data from table(Tornillos) that inherits from table (articulos. abstract table) i want to get the value from sistema to display on my template. My views.py # def tipo_medicion(request, id): def tipo_medicion(request): template = 'inventario/sistema.html' try: sis = Tornillo.objects.values('sistema').distinct() print(sis) except Tornillo.DoesNotExist: raise Http404() #return render(request, template, { sis:'sis', id:'id' }) return render(request, template, { sis:'sis' }) My Server terminal screen: [11/Jun/2018 23:55:10] "GET /sistema-medicion/2 HTTP/1.1" 200 761 <QuerySet [{'sistema': 'MM'}, {'sistema': 'STD'}]> [11/Jun/2018 23:55:10] "GET /sistema-medicion/2 HTTP/1.1" 200 761 My Template: {% extends 'inventario/base.html' %} {% block content %} <div class="container"> <h1 class="tag">SISTEMA</h1> <ul> {% for s in sis %} <li>{{sistema}</li> {% endfor %} </ul> </div> {% endblock %} I'am struggling with an other issue i don't understand the concept yet for urlconf. currently my url for this view is static, i have tried with and get an inspected value error My urls.py app_name = 'inventario' urlpatterns = [ path('', views.index, name='index' ), path('categorias/', views.categorias, name='categorias'), path('sistema-medicion/2', views.tipo_medicion, name='medicion') #path('sistema-medicion/<int:id>', views.tipo_medicion, name='medicion') ] -
Django-Machina forum panel not showing in wagtail admin panel
I have a wagtail project being developed, essentially a blog with a forum. I chose django-machina as the forum I want to use because of how modular it is and how well it integrates into existing projects. I followed the instructions in the documentation without issue, and the install was a success. I can access the app by going to /forum on my project. However, the next step in the documentation refers to using the forum admin panel. On my install there is no link or form to login, nor any link to be able to register. My wagtail admin menu does not have a section for forum. Where exactly can I access the django-machina forum admin panel in a wagtail project? -
Best way to send html form to an email address within Django project?
I see contact forms on almost all websites and they make it look easy. Reading on how to do it seems complex, especially since most of the solutions are using php and a server. I don't really know php and I already have four languages in my project and it just gets overwhelming. I want something simple; fill out the details, send to an email, and done. Fill out name: John Doe Fill out dob: 6/11/2018 [Submit] (send to example@example.com) -
Django: call class function in form_valid
I have a class based view. I want to update a field in a model whenever it is saved. This field isn't set by the user; it is a field that says the form data has been changed and needs to be reapproved. One way I am thinking about going about this is in the def form_valid to query the model and set the field to the value I need. The query that I'm running is also in a function defined on this class. Can I run this function in def form_valid instead of realling it? All my attempts are proving fruitless. class CUpdateView(LoginRequiredMixin, UpdateView): def get_object(self): qs = C.objects.filter( c_id = self.kwargs.get('c_id') ) if qs.count() == 1: if self.request.user == qs.first().a.user or self.request.user == qs.first().inhouselandmanager.user: pass else: raise PermissionDenied return qs.first() raise Http404 def form_valid(self, form): if self.object.status != 'initiated': return HttpResponseRedirect(reverse('c:detail', kwargs={'c_id': str(self.object.c_id) })) qs = super().get_object() qs.update(approved=False) return super().form_valid(form) -
python manage.py runserver not printing
PS C:\WINDOWS\system32> cd ~/Desktop PS C:\Users\Owner\Desktop> cd ./mywebsite PS C:\Users\Owner\Desktop\mywebsite> ls Directory: C:\Users\Owner\Desktop\mywebsite Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 6/11/2018 2:35 PM .idea d----- 6/11/2018 1:57 PM mywebsite -a---- 6/11/2018 1:37 PM 252 manage.py PS C:\Users\Owner\Desktop\mywebsite> python manage.py runserver PS C:\Users\Owner\Desktop\mywebsite> I am trying to get to the web page that should be created for me, but the runserver function is not printing any information for me to get to there. What am I doing wrong? -
How do I retrieve data to modelForm using Ajax in Django
I want to retrieve data to modelForm based on user input. I am developing a transaction app, I want to retrieve account balance to the form based on the account number selected by the user. First I want to print an alert to test the existence of the account number but keep getting 500 internal server error. Here is the code **models.py** class Account(models.Model): ACCOUNT_TYPE = ( ('Checking','Checking'), ('Savings','Savings')) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) account_number = models.PositiveIntegerField(primary_key=True) account_type = models.CharField(max_length=8, choices=ACCOUNT_TYPE, default='select') account_balance = models.PositiveIntegerField(blank=True, default=0) **views.py** @login_required def validate_account_number(request): account_number = request.Get.get['account_number'] data = { 'is_exist':Account.objects.filter(account_number=account_number).exists() } return JsonResponse(data) **transaction.html** <form class="form-horizontal" method=POST id="sendform"> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade active show" transfer="home"> <div class="col-md-6"> <div class="tile"> <h3 class="tile-title">Transfer Money</h3> <div class="tile-body"> {% csrf_token %} {% bootstrap_form form%} {{ form.non_field_errors }} <div class="tile-footer"> <div class="row"> <div class="col-md-8 col-md-offset-3"> <button type="submit"> <i class="fa fa-fw fa-lg fa-check-circle"></i>Send</button>&nbsp;&nbsp;&nbsp;<a class="btn btn- secondary" href="#"><i class="fa fa-fw fa-lg fa-times-circle"> </i>Cancel</a> </div> </div> </div> </div> </div> </div></div> </div> </form> </main> {% endblock %} {% block javascript %} <script> $("#id_creditor_account").change(function(){ var account_number = $(this).val(); $.ajax({ url: '{% url 'users:validate_account_number'%}', data:{ 'account_number':account_number }, dataType: 'json', success: function(data){ if (data.is_exist){ alert("Account exist"); } } }); }); </script> Here is the … -
Django form are not showing in html template
I'm trying to create a form in Django template but it is just not showing the fields here is my files models.py where i created the desired table class ReportMessage(models.Model): sender = models.ForeignKey(UserModel, related_name="report_message_sender", on_delete='CASCADE') message = models.ForeignKey(Message, on_delete='CASCADE') created_at = models.DateTimeField(auto_now=True) reason = models.TextField(max_length=1500) is_read = models.BooleanField(default=False) forms.py where i created the form to edit only one field in the table class ReportMessageForm(forms.Form): class Meta: model = ReportMessage fields = ['reason', ] views.py where i created the view for the form @login_required def report_message(request, pk): current_user = request.user reported_message = get_object_or_404(Message, pk=pk) if request.method == "POST": report_message_form = ReportMessageForm(request.POST) if report_message_form.is_valid(): model_instance = report_message_form.save(commit=False) model_instance.sender = current_user model_instance.message = reported_message model_instance.save() return redirect('report_confirm') else: report_message_form = ReportMessageForm() context = { 'report_message_form': report_message_form, } return render(request, 'fostania_web_app/report_message.html', context) def report_confirm(request): return render(request, 'fostania_web_app/report_confirm.html') and urls.py where the urls i used for the views path('report/messages/<int:pk>/', views.report_message, name="report_message"), path('report/confirm', views.report_confirm, name="report_confirm"), and finally that is how i used the form in the html template {% extends 'fostania_web_app/base.html' %} {% block content %} {% load static %} <form action="" method="post" name="ReportMessageForm" align="right"> {% csrf_token %} {{ report_message_form }} <input type="submit" class="btn btn-success" style="width: 100px;" value="إرسال" /> </form> {% endblock %} and then all … -
Enable Django View CSFR protection for anonymous Python clients using API requests (rather than templates)
Some Views in my Django 11.1 application get requested by both GUI Templates (user must login for access), and by anonymous python client apps executed as a CLI program (no login). I needed to enable CSFR protection for all Views, but this protection requires a session id to work (without as session, CSFR attack wouldn't work anyway). I came up with the solutions shown bellow, but would like to know if there is a better way of doing it. Solution for GUI templates: This is rather simple and well documented in Django docs. Just include {% csrf_token %} between POST tags. Solution for Python clients (anonymous): This solution is not clearly documented in the docs (or perhaps it is, but I didn't find an easy step by step instruction). So this is what I did: In globals.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', Create a Django View that returns a CSFR token and a session ID for anonymous clients: from django.middleware.csrf import get_token ... csfr_token = get_token(request) ... if not request.session.session_key: request.session.create() .... return JsonResponse({'token': csfr_token, 'sessionid' : request.session.session_key}) The anonymous client, first requests the token and session ID with a GET: ... myrequest = urllib.request.Request(url_to_the_django_view, method='GET') myresponse = … -
dict of a dict called from a queryset don't show me keys and values in django template
I get a data from a queryset that contains a dictionary look this {'somekey': {'name1': 'value1','name2': 'value2','name3': 'value3',...}} I'm working in django template and whem I show the data I get the dict like above,I'm trying this way : {% for key, val in rec.col_ass.items %} {{key}} : {{val}} {% endfor %} The code of template : <tbody> {% for tps in arr %} <tr> <th style="vertical-align: middle">Solicitado</th> <td style="vertical-align: middle"><a href="#my_modal" data-toggle="modal" data-book-id="{{tps}}" data-txt-id="{{tps}}" data-book-url="{{tps}}">{{tps}} </a></td> {% for rec in colab %} {% if rec.tps == tps %} <td style="vertical-align: middle"> {% for key, val in rec.col_ass.items %} # here is my problem {{key}} : {{val}} # -->> values {% endfor %} </td> {% endif %} {% endfor %} <td> {% for doc,serv in dict.items %} {% if serv == tps %} {{doc}}<br> {% endif %} {% endfor %} </td> </tr> {% endfor %} </tbody> showing in template Tks -
django QuerySet for parents with at least one child
I have a many to one relationship like the following: class Adult(models.Model): name = models.CharField(max_length=200) class Child(models.Model): name = models.CharField(max_length=200) adult = models.ForeignKey(Adult) And I am trying to find a way to get a QuerySet of adults who have at least one child, and then further apply filters to that QuerySet. In SQL to obtain the list of adult id's who have at least one child I can just do this: select distinct(child.adult_id) from child; But attempting the same thing in django I am having trouble. I have tried things such as the following, with a few modifications: adult_ids = Child.objects.values_list('adult__id').distinct() adults_with_children = Adult.objects.filter( id__in=adults ) but I keep generating a sql query that involves a join with the adult table in the first line. How can I find adults who have a least one child in a faster/better way? Thanks in advance.