Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Azure IoT device loosing connection to transparent edge gateway device
I have an issue with a IoT device looses the connection to a transparent Azure IoT Edge gateway. I don't know where to start searching, therefore I'm a bit lost here. IoT Device I used the sample telemetry application (Python) and customized it to our needs. It connects to the Edge Device with MQTT over WS. Initially, it works great until the disconnect happens. SDK version is 2.11.0 IoT Edge I have setup an Azure IoT Edge device as transparent gateway. It is running the latest versions (1.2), installed on a Azure Linux VM. Problem When the script has been running for some time (e.g. 30 minutes) a connectivity issue appears. Exception caught in background thread. Unable to handle. ReconnectStage: DisconnectEvent received while in unexpected state - CONNECTING, Connected: False ['azure.iot.device.common.pipeline.pipeline_exceptions.OperationTimeout: Transport timeout on connection operation\n'] Traceback (most recent call last): File "C:\Users\foo\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\iot\device\iothub\aio\async_clients.py", line 33, in handle_result return await callback.completion() File "C:\Users\foo\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\iot\device\common\async_adapter.py", line 91, in completion return await self.future azure.iot.device.common.transport_exceptions.ConnectionDroppedError: transport disconnected The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\Development\machine-poc\python\telemetrysender.py", line 165, in <module> main() File "c:\Development\machine-poc\python\telemetrysender.py", line 76, in main send_telemetry_from_device(device_client, payload, i) File "c:\Development\machine-poc\python\telemetrysender.py", line 86, in send_telemetry_from_device … -
django:Model get all User except one user with his user id
Is there any method of django model.object to get all the users from User model except one user with his id? -
Django - Can I use one UpdateView to update fields on separate pages?
Let's say I have a Student model, with name and age fields, and I have a page with a DetailView class showing these fields. Let's say that rather than having one "update" button that will take me to a form to update all fields of my model at once, I want a separate button for each field that takes me to a separate page with a form to update it. I know how I could do this with a separate HTML file and separate UpdateView class for each field, but it seems like there should be a cleaner way. In the first HTML file I have two buttons: <a href="{% url 'update_name' pk=student.pk%}">Update name</a> <a href="{% url 'update_age' pk=student.pk%}">Update age</a> In the second I have the form: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> Urls: urlpatterns = [ path('<int:pk', views.StudentDetailView.as_view(), name="detail"), path('update_name/<int:pk>', views.StudentUpdateView.as_view(), name="update_name"), path('update_age/<int:pk>', views.StudentUpdateView.as_view(), name="update_age"), ] Views: class StudentUpdateView(UpdateView): model = models.Student template_name = 'update_student.html' I suppose I'm looking for some sort of if statement that I can put in my view, like: if condition: fields = ("name",) elif condition2: fields = ("age",) Hopefully this makes sense! Thank you for any help :) -
'no app installed with this label' error when creating an empty migration
WOrking on a django project, I had to split an app in two apps and move models from one app to the other. Now i want to move the data from the old table to the new one using the migrations. However, when i want to create an empty migration with "manage.py makemigrations --empty myapp" i have the error ==> 'no app installed with this label'. My new app is in the installed apps in settings. This is where the error occurs, when reading the settings. Has anyone a clue to help me solve my problem? -
Django: View and View-Test working against each other
right now I'm trying to test one of my really simple views - which is working totally fine - and receiving an error: Traceback (most recent call last): File "C:\Users\someone\Documents\django_tests\app\tests\test_views.py", line 42, in test_person_post ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000262BBE2CF10>>": "Person.created_from" must be a "CustomUser" instance. I've changed the default auth.user.model with AbstractUser and changed it into mail/password-, instead of username/password-combination. models.py: class Person(models.Model): GENDERS = ( ('-', '-'), ('Diverse', 'Diverse'), ('Female', 'Female'), ('Male', 'Male'), ) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) gender = models.CharField(max_length=10, null=False, blank=False, choices=GENDERS, default=GENDERS[0][1]) born = models.DateField(null=False, blank=False) adult = models.BooleanField(default=False) created_from = models.ForeignKey(USER, null=False, blank=False, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['last_name', 'first_name'] constraints = [ models.UniqueConstraint(fields=['last_name', 'first_name'], name="unique person constraint"), ] verbose_name = "Person" verbose_name_plural = "Persons" def get_absolute_url(self): return f"api/persons/{self.id}/" def __str__(self) -> str: return f"{self.first_name} {self.last_name}" forms.py: class PersonForm(ModelForm): class Meta: model = Person exclude = [ 'id', 'adult', 'created_from', 'created_date', 'updated_date', ] views.py: def index(request): form = PersonForm() if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): person = form.save(commit=False) person.created_from = request.user person.save() return redirect('index') context = {'form': form} return render(request, 'app/index.html', context) test_views.py: USER = get_user_model() class … -
Convert string to int before quering django ORM
I have a model class Entry(models.Model): maca = models.CharField(max_length=100, blank=True, null=True) This field will accept only numbers (cannot set char field to integer field for business reasons) Now I have to get all Entries that have maca greater than 90 What I'm trying to do is this: Entry.objects.filter(maca__gte=90) But gte isn't working because the maca is string How can I convert maca to int before filtering? or something like this? Thanks -
Add multiple real-time plots on the same page with Chart.js (Django)
i'm trying to add multiple real-time plots on the same page (Django framework) with Chart.js using websockets. When i try to add separate socket on the 2nd plot, the 1st freezes. Here is my code, thanks a lot. I'm sure there is a better way to write code, but I'm relatively new to js. <script> let socket =new WebSocket('ws://localhost:8000/ws/polData/'); socket.onopen =function(e){ alert('Connection established'); }; socket.onmessage = function(e){ console.log(e.data); var recData=JSON.parse(e.data); dataObjNew=dataObj['data']['datasets'][0]['data']; dataObjNew.shift(); dataObjNew.push(recData.value); dataObj['data']['datasets'][0]['data']=dataObjNew; window.myLine.update(); }; socket.onclose = function(e){ alert('Connection CLosed'); }; </script> <script> var dataObj={ type: 'line', data: { labels: [1,2,3,4,5,6], datasets: [{ label: 'Real time data', borderColor: "#1d7af3", pointBorderColor: "#FFF", pointBackgroundColor: "#1d7af3", pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 1, pointRadius: 4, backgroundColor: 'transparent', fill: true, borderWidth: 2, data: [12, 19, 3, 5, 2, 3], }] }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', labels : { padding: 10, fontColor: '#1d7af3', } }, tooltips: { bodySpacing: 4, mode:"nearest", intersect: 0, position:"nearest", xPadding:10, yPadding:10, caretPadding:10 }, layout:{ padding:{left:15,right:15,top:15,bottom:15} }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } } var ctx = document.getElementById('lineChart').getContext('2d'); window.myLine = new Chart(ctx,dataObj ); </script> <script> let socket =new WebSocket('ws://localhost:8000/ws/polData2/'); socket.onopen =function(e){ alert('Connection established'); }; socket.onmessage = function(e){ console.log(e.data); var recData=JSON.parse(e.data); … -
How to duplicate input field?
I want to create a button to add more file input. I mean, there is a file input on the page, when the user clicks the add more button, then it should create a new and different file input field. How can I do that? -
Difference Django DB models using the ForeignKey to object with or without "to" statement?
I am new to Django and trying to understand someone else code. Where I am struggling with is the models.py and when to use a direct assignment of another object or when to use the "to" statement. What is the difference between those statement? model = models.ForeignKey('Car', on_delete=models.CASCADE, blank=True, null=True) model = models.ForeignKey(to='Car', on_delete=models.CASCADE, blank=True, null=True) -
Get comma separated id with Group by and annotate with sub-query in django
from django.db.models import Subquery, OuterRef My queryset looks like this: AssessmentQueueTable.objects.filter(patient=1,is_deleted=False).annotate(followup_id= Subquery(FollowUp.objects.filter(reference_id=OuterRef('id')).values('id')[:1])) from above query i get only one value in followup_id field like followup_id = 1, but i need all comma separated id like followup_id = 1,2,3,4. if i remove [:1] from sub-query it throws error -
REGEXP for matching or finding only Streetname and housenumber without additionals
This is a regexp specific something that I need to do in the backend to strip the address. I need the streetname + number to be cleaned to a Streetname + housenumber without any additional letters or any other characters with other numbers. For example: Teststreet 123 (correct) Teststreet 123F needs to be stripped to Teststreet 123 Teststreet 12 and 3 needs to be stripped to Teststreet 12 Teststreet 123,5 needs to be stripped to Teststreet 123 Street name long 122 (correct) Street name long 122 - A needs to be stripped to Street name long 122 And so on... I have a function that gets the address from the model and sometimes the addresses could be with some additional characters etc which a API that I have to read does not work with it, so I have split/trim it in python to only a streetname and a housenumber. Does anyone have an idea how I can do this? And anyone an idea what the correct REGEXP for this can be? -
Django I have added an href parameter to my url but it does not work
I have a field in my datatable which represent product url and I have display it in my django template as href in order to enable the user to get the product page by clicking on this link. this is my code in django template : <td><a href="/Productlinks/">{{product.Productlinks }}</a></td> But when I click the url it gives me an error page . -
Why is my sign up button in Django not working?
I have been following a Django blog tutorial where a user can register an account, however my 'sign up' button should be redirecting to the homepage and creating the user, however it does neither. I have extensively searched online for an answer, yet can't seem to resolve the issue. Any help would be much appreciated. Here is my register.html file: {%block content%} <div class="content-section" <form method ="POST" > {%csrf_token%} <!django required security> <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{form.as_p}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit" value="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign in</a> </small> </div> </div> {%endblock content%} and here is my views.py file: from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register (request): if request.method == 'POST': form = UserCreationForm(request.POST) #creates instance of form with POST data if there's a POST request if form.is_valid(): #validation of form form.save() username=form.cleaned_data.get('username') messages.success(request, f'Account created for {username}.') return redirect ('requests-home') #redirecting to home page after account creation else: form = UserCreationForm() #creating instance of user creation form (empty) return render(request, 'users/register.html', {'form': form}) I also get this error when running the views.py file in VsCode: ** "ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, … -
I Want to get card rate in response to card category
What I am trying to do is that once I select a card category, the corresponding card rate should appear, I have three models: Giftcard, Category, and CardRate, which I link together using ForeignKey. Here are my models class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard/', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) card = models.ForeignKey(Giftcard, on_delete=models.CASCADE) class CardRate(models.Model): rate = models.IntegerField() card_category = models.ForeignKey(Category, on_delete=models.CASCADE) Here is my view: def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) categories = Category.objects.all() context = { 'giftcards': giftcards, 'categories': categories, } return render(request, 'dashboard/giftcard.html', context) Here is my template, i thinking here were my mistake is coming from: {% for giftcard in giftcards %} <!-- Card --> <div class="col-lg-4 gift__card col-6 p-0"> <a type="button" class="btn"> <img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}"> </a> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <select id="category" class="form-select py-2" aria-label="Default select example"> {% … -
OrderForm not saving data to django database
i'm creating a webapp that allows a user to enter information in a form which then saves the data into django. Everything works well, I can add information to the form in the template and press submit however the data is not saved into the database (I cannot see it in my admin panel inside 'Order' table. I have the if form.is_valid() form.save() in my views.py file which should POST the data to my database but its not. Anyone know what i'm doing wrong? Order model from models.py class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) # on_delete = If customer is delete, we dont delete child (orders), customer just becomes null without deleting order customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) forms.py OrderForm class is inherited by CreateOrder views.py from django.forms import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' createOrder function from views.py: def createOrder(request): form = OrderForm() if request.method == 'POST': #print('Printing POST:',request.POST) form = OrderForm(request.POST) #form handles the process of saving to database/ if form.is_valid(): form.save return … -
writing to mariadb causes non-UTF-8-endocing
I am using mariadb with Server charset: UTF-8 Unicode (utf8mb4) and python 3.7.3 and for some reason beyond me, a CSV file read in and written to the database is saved in some weird encoding: models.py: class Product(models.Model) data = models.JSONField() store = models.ForeignKey(Store, on_delete = models.CASCADE) number = models.PositiveIntegerField() and when reading in a csv file: with open(filename, encoding = "utf-8") as f: reader = csv.reader(f) for row in reader: d = {header[i]: row[i] for i in range(1, len(row))} logging.error(f"{row[0]} - {d}") # prints "123 - süden" product = Product.objects.get(store = store, number = row[0]) product.data = d product.save() but in my database the line reads as "number": 123, "data": "s\u00fcden". So my struggles here: csv file is encoded in UTF-8 csv file is opened with UTF-8 encoding console prints the charset correctly phpmyadmin shows, "ü" saved as "\u00fc" printing the line in django shell prints "ü" correctly I already tried setting the an encoder for the JSONField: from django.core.serializers.json import DjangoJSONEncoder ... data = models.JSONField(encoder = DjangoJSONEncoder) and then ran migrations again. A simple test can be done in the admin, when searching for products süden returns zero hits. But when manually altering the value to süden in … -
Django uses untranslated strings instead of translations
I have a small Django application, which I tried to localize. In the urls.py I have urlpatterns += i18n_patterns( path('add_request/',AddRequest.as_view(),name='add_request'), path('add_offer/', AddOffer.as_view(), name='add_offer'), ) In the settings.py I have MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and LANGUAGES= [ ('en', 'English'), ('de', 'German') ] In my models.py I used gettext (also tried gettext-lazy) for the verbose_name arguments of my fields. I extracted po files via django-admin makemessages -l en django-admin makemessages -l de Translated them and ran django-admin compilemessages Now I have the prefixes de/ and en/ for my urls, but all field names are the untranslated verbose_names from my models. How do I get Django to use the translations? -
when i am deploying on heroku i get Page not found (404)
Page not found (404) Request Method: GET Request URL: https://blogapp85.herokuapp.com/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ blogapp/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py from pathlib import Path import dj_database_url import os import django_heroku # 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-@88uzl)swhs9@api7_%qj#vw=wa0!jf3+)l5-mmlch@t5%%^fl' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1', 'blogapp85.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogapp', 'django_social_share', 'whitenoise.runserver_nostatic' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', … -
POST method not working in django, where i use Formview
I have class where is use both, FormView and DetailView. when i send post request i see this log in terminal [06/Apr/2022 14:44:16] "POST /profile/question/1/ HTTP/1.1" 200 6327, but not working post, form_valid and form_invalid methods. does not call these 3 functions and therefore the form is not stored this is my code -> class QuestionDetail(FormView, DetailView): model = Question form_class = CommentForm template_name = "Profile/question_detail.html" context_object_name = "detail" def dispatch(self, request, *args, **kwargs): try: self.object = self.get_object() except: return redirect('Profile:error') self.get_object() return super(QuestionDetail, self).get(request, *args, **kwargs) def get_success_url(self): return self.request.path def get_context_data(self, *args, **kwargs): like_exist=bool(Like.objects.filter(user=self.request.user, question=self.get_object())) dislike_exist=bool(DisLike.objects.filter(user=self.request.user, question=self.get_object())) self.object=self.get_object() context = super(QuestionDetail, self).get_context_data(**kwargs) try: question = Question.objects.get(id=self.kwargs["pk"]) context['detail'] = question context['like_ex'] = like_exist context['dislike_ex'] = dislike_exist except Http404: return reverse("Profile:error") return context def post(self, request, *args, **kwargs): print("Not working post method") def form_invalid(self, form): print("Error") return super(QuestionDetail, self).form_invalid(form) def form_valid(self, form): print("It's here") form.instance.user = self.request.user form.instance.question = self.get_object() form.save() return super(QuestionDetail, self).form_valid(form) i don't understand what happened. -
ManytoManyField Django : how to call models in methods?
I need help for something, I want to call models with ManyToManyField. I want to have method to get Class A from Class B, and another in Class B to get Class A. here's my (shortened) code : class Licence(models.Model): name = models.CharField(max_length=64) picture = models.ImageField(upload_to='finder/static/finder/img/licence/',null=True, blank=True) description = models.TextField(null=True, blank=True) #returns a list of games from this license def getGamesOnThisLicence(self): #i don't know how to proceed class Game(models.Model): name = models.CharField(max_length=64) description = models.TextField() release_date = models.DateField(null=True, blank=True) licence = models.ManyToManyField(Licence, blank=True, null=True) #return name of licence to which the game belongs def getLicenceName(self): return self.licence.name -
How to load images using JavaScript in Django in a Jinja format?
Basically what I am doing is here there is a emotion detection model running in background which will detect the emotion and create an emoji in .svg format. This svg file keeps on changing as the emotion changes. Like if emotion="Happy" then an image with a happy face will be generated in a svg file format. Now I want this generated image to be displayed in by Django template but I am getting error. This is my view.py def epred(emotion): global ep ep = emotion def res(request): global sc_id,cc_id,hc_id,ht_id,a_id,fht_id,ct_id, ep sc_id = request.GET.get('skincolor') cc_id = request.GET.get('clothingcolor') hc_id = request.GET.get('haircolor') ht_id = request.GET.get('hairtype') a_id = request.GET.get('accessory') fht_id = request.GET.get('facialhairtype') ct_id = request.GET.get('clothingtype') update(fht_id, ct_id, cc_id, a_id, hc_id, ht_id, sc_id, ep) return render(request, 'result.html') def gen(camera): while True: frame = camera.get_frame() update(fht_id, ct_id, cc_id, a_id, hc_id, ht_id, sc_id, ep) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type ='multipart/x-mixed-replace; boundary=frame') This is my result.html file where I need the image to be displayed <body style="background-color:#9ADCFF"> <h1 id="mh1">LOOK AT THE CAMERA</h1> <div class="row"> <div class="column" id="cols"> <img src = "{% url 'video_feed' %}"> </div> <div class="column" id="cols"> <img id="resimg" src="{% static 'output/emoji1.svg' %}"> <div id="resbtn"> <a href="#"><button class="btn btn-primary" … -
How can I truncate serializer CharField value if it exceeds a certain length
I have a model field that I want to restrict to a certain length (max_length=200). I however want the serializer to truncate any value that exceeds that length (max_length=200). How can I achieve this model field description = models.CharField(max_length=2000) serializer field description = serializers.CharField( max_length=2000, required=False, allow_blank=True, default="" ) -
How to allow users to input in only 5 fields out of 10 in django model form
I have developed a django project to test 10+2 students online. I used django model forms.In the question paper, there will be 90 questions. In each subject 30 questions. Out of 30 , in each subject, first 20 are multiple choice. In that I don't have any problem. But in the remaining 10, students have to input integer values . But only 5 out of 10. How to restrict them not to input more than 5 in that 10 questions in each subject. Pls advice me. I am not rendering questions, only form to collect options and integers. Pls advice me -
How to get top n rows in django rest framework serializers using serializers relations
I have a serializer that is working fine for all of the data, which is getting from the Database. I want to get top n numbers of rows sorted by some value. Below is my code in views.py: @api_view(['GET']) def org_api(request, org_id): if request.method == 'GET': try: org = Organization.objects.prefetch_related('team').get(org_id=org_id) except Organization.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializers = OrgSerializers(org) return Response(serializers.data) And here is my serializers.py code: class OrgSerializers(serializers.ModelSerializer): team = TeamSerializer(many=True, read_only=True) class Meta: model = Organization fields = ['org_id','name', 'team'] And here is my TeamSerializers Code: class TeamSerializer(serializers.ModelSerializer): ticker = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all()) class Meta: model = Team fields = ['name', 'resignation', 'org_id'] It is returning all of the team members of the same organization like below: { "org_id": "ABC", "name": "Stocks Telegraph", "team": [ { "name": "Mr. Timothy D. Cook", "title": "CEO & Director", "org_id": "ABC" }, { "name": "Mr. Luca Maestri", "title": "CFO & Sr. VP", "org_id": "ABC" }, { "name": "Mr. Jeffrey E. Williams", "title": "Chief Operating Officer", "org_id": "ABC" }, { "name": "Ms. Katherine L. Adams", "title": "Sr. VP, Gen. Counsel & Sec.", "org_id": "ABC" }, { "name": "Ms. Deirdre O'Brien", "title": "Sr. VP of People & Retail", "org_id": "ABC" }, { "name": "Mr. Chris Kondo", "title": "Sr. … -
Adding a 'show all' to django search with js/ajax if results > 5
I have a simple django search functionality using js/ajax. I want to add functionality so that when the queryset is greater than 5 a 'Show all' href will appear in the search results and it will redirect to a page with all the queryset. This is for the case when a queryset returns a large number of results, rather than have them in one big box. I thought I could just add a dictionary to my queryset, e.g. data.append({'pk': <add number to querset>, 'name': 'Show all results'}) but then I think this will mess around with the js logic with the forEach loop. I'd want each search result up to 5 to link to the detail view, but then the last one should link to a completely different view. I'm not sure what the best option is here. My search in views.py: def search_results(request): """ Handles search logic """ if request.is_ajax(): res = None quote = request.POST.get('quote') qs = Quote.objects.filter(name__icontains=quote) if len(qs) > 0 and len(quote) > 0: data = [] for pos in qs: item = { 'pk': pos.pk, 'name': pos.name, 'image': str(pos.image.url) } data.append(item) res = data else: res = 'No quotes found...' return JsonResponse({'data': res}) return JsonResponse({}) …