Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Separate array to small array by count [duplicate]
I have array like this [1,4,2,3,4,14,2,5,1,2,3,14,1,3] Now I want to separate this to small 3 arrays( last might be 1 or 2 array) [[1,4,2],[3,4,14],[2,5,1],[2,3,14],[1,3]] I think I can do this such as ,but obviously it's not clear and clean. Is there any more easy way to do this? total = [] item = [] for cnt,a in enumerate(original_arr): item.append(a) if len(item) == 3: total.append(item) item = [] total.append(item) -
Bad Request error when trying to refresh Django login access token
Trying to refresh the access token I receive from Django every few seconds, however I am getting the error message Request Method: POST Status Code: 400 Bad Request I am sending my refresh token to this endpoint: "http://127.0.0.1:8000/api/token/refresh/" This is my urls.py: from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), ] This is how I am sending my refresh token: let updateToken = async ()=> { try { let response = await axios.post('http://127.0.0.1:8000/api/token/refresh/',JSON.stringify(authTokens.refresh)) //update state with token setAuthTokens(authTokens => ({ ...response.data })) //update user state const decoded = jwt_decode(response.data.access) setUser(user => ({ ...decoded })) //store tokens in localStorage //we stringify because we can only store strings in localStorage localStorage.setItem('authTokens',JSON.stringify(response.data)) } catch(err) { //if fail, something is wrong with refresh token console.log(err.response) } } This is the error I am getting: config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: refresh: ['This field is required.'] [[Prototype]]: Object headers: content-length: "39" content-type: "application/json" [[Prototype]]: Object request: XMLHttpRequest onabort: ƒ handleAbort() onerror: ƒ handleError() onload: null onloadend: ƒ onloadend() onloadstart: null … -
( django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.accounts'. Check that 'mysite.apps.accounts.apps.AccountsConfig.name' is correct
This is how it is structured The code inside apps.py of accounts folder file is from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = "apps.accounts" The code inside Settings is INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite.apps.accounts', ] I tried changing 'mysite.apps.accounts', to 'mysite.apps.AccountsConfig', and changing name = "apps.accounts" to name = "accounts" I am new to Django and was following How to make a website with Python and Django - MODELS AND MIGRATIONS (E04) tutorial. Around 16:17 is where my error comes up when I enter python manage.py makemigrate to the vscode terminal The error is ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.accounts'. Check that 'mysite.apps.accounts.apps.AccountsConfig.name' is correct. Someone please help me. -
I can't make migrations between two models in Django
I have a problem with my migrations, it turns out that when I try to do python manage.py migrate I get a series of errors but the one that surprises me the most is the one from heroku: django.db.utils.IntegrityError: insert or update on table "carros_carro" violates foreign key constraint "carros_carro_cliente_id_3c6fe221_fk_Clientes_clientes_id" DETAIL: Key (cliente_id)=(1) is not present in table "Clientes_clientes" So my problem is between those two models, the bad thing is that I already replaced those models that were in my previous folders and the error continues to appear. clientes/models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) TITLE = ( ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Mr.', 'Mr.'), ) corporacion=models.CharField(max_length=200,blank=True) titulo = models.CharField(max_length=200, choices=TITLE,default='Mr.') nombre = models.CharField(max_length=200, blank=True) apellido = models.CharField(max_length=200,blank=True) telefono = models.IntegerField(blank=True, null=True) tel = models.IntegerField(blank=True, null=True) fax = models.IntegerField(blank=True, null=True) correo = models.EmailField(max_length=200,blank=True, null=True) website=models.URLField(max_length=200,blank=True, null=True) social_media=models.CharField(max_length=200,blank=True, null=True) social_media2=models.CharField(max_length=200,blank=True, null=True) social_media3=models.CharField(max_length=200,blank=True, null=True) contacto_alternativo=models.CharField(max_length=200,blank=True, null=True) contacto_alternativo2 = models.CharField(max_length=200,blank=True, null=True) contacto_alternativo3 = models.CharField(max_length=200,blank=True, null=True) pais = models.CharField(max_length=200,blank=True, null=True) direccion=models.CharField(max_length=200,blank=True, null=True) ciudad=models.CharField(max_length=255,blank=True, null=True) estado=models.CharField(max_length=255,blank=True, null=True) zip=models.CharField(max_length=255,blank=True, null=True) fecha_registro = models.DateTimeField(default=datetime.now,blank=True, null=True) def __str__(self): return f'{self.nombre} {self.apellido}' carros/models.py class Carro(models.Model): placas=models.CharField(max_length=255, blank=True,null=True) tipo=models.CharField(max_length=255, blank=True,null=True) marca=models.CharField(max_length=255, blank=True,null=True) modelo=models.CharField(max_length=255, blank=True,null=True) año=models.IntegerField() vin=models.CharField(max_length=255, blank=True,null=True) color=models.CharField(max_length=255, blank=True,null=True) motor=models.CharField(max_length=255, blank=True,null=True) agente_seguros=models.CharField(max_length=255, blank=True,null=True) compañia_seguros=models.CharField(max_length=255, blank=True,null=True) no_politica=models.CharField(max_length=255,blank=True,null=True) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(blank=True, … -
how to render unseen notification from models using channels in django
Actually i wanted to render unseen notification into the templates from models.py using channels models.py class Notify(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.TextField(max_length=500) seen = models.BooleanField(default=False) def save(self,*args,**kwargs): channel_layer = get_channel_layer() notification_object = Notify.objects.filter(seen=False).count() data = {'count': notification_object ,'notification':self.message} async_to_sync(channel_layer.group_send)( 'notification_consumer_group', { 'type':'send_notification', 'value':json.dumps(data) }) super(Notify,self).save(*args,**kwargs) and if notification once seen then remove from notification icon . -
is there a way to integrate pixela (calendar graph) into a website through html? like what github has?
is there a way to integrate PIXELA (calendar graph) into a website through html? like what github has? the one with the contributions section. Thanks in advance! ( API docs for pixela https://docs.pixe.la/ ) -
DRF AssertionError: Expected a `time`, but got a `datetime`
I have a model: class Inspection(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name='vendor_inspections') inspection_date = models.DateField(default=date.today) inspection_time = models.TimeField(default=timezone.now) ... class Meta: unique_together = (('vendor', 'inspection_date'),) serializer: class InspectionSerializer(serializers.ModelSerializer): class Meta: model = Inspection fields = ['vendor', 'inspection_date', 'inspection_time'] and modelviewset: class InspectionModelViewSet(viewsets.ModelViewSet): serializer_class = InspectionSerializer queryset = Inspection.objects.all() I want to change data and time fields with PUT/PATCH requests or set their values manually on instance creating if it's needed, otherwise, current date & time should be saved. When I send POST request with or without inspection_time in payload I get this error: AssertionError: Expected a `time`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly. This error isn't raised if I remove inspection_time from fields in serializer Meta class. I've implemented serializer field validation method just to understand what's going on: def validate_inspection_time(self, inspection_time): raise Exception(inspection_time) Aforementioned AssertionError is raised before validate_inspection_time. Although the listed an inspection instance is saved in DB. what the problem could be? Thank you. -
Django behind NGINX reverse proxy and AWS Application Load Balancer doesn't get HTTPS forwarded from client in HTTP_X_FORWARDED_PROTO
I'm running Django on Gunicorn behind a NGINX reverse proxy, and an AWS Application Load Balancer. The ALB has 2 listeners. The HTTPS listener forwards to a Target Group in port 80, and the HTTP listener redirects to HTTPS. The ALB thus connects with an AWS ECS Cluster, which runs a task with 2 containers: one for the Django app, and another for the NGINX that acts as a reverse proxy for the Django app. Here's the configuration for the NGINX reverse proxy: upstream django { server web:8000; } server { listen 80; listen [::]:80; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_ssl_server_name on; proxy_redirect off; } } This configuration ensures that whenever the client tries to hit the website app using an HTTP request, he gets redirected to HTTPS. And everything works fine with one exception. In Django, when I run request.is_secure() I'm getting False instead of True as expected. If I run request.build_absolute_uri(), I get http://mywebsite.com and not https://mywebsite.com as expected. I already tried adding the following lines to settings.py: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') as explained in the documentation, but it doesn't … -
How to get additional context without repeating database queries?
I want to provide extra context in my serializer in get_serializer_context. Currently I'm having to repeat the database queries that the serializer is performing by itself anyway in order to do so. Is there a way around this, to access the data that's already been queried? class MyView(generics.ListCreateAPIView): def get_serializer_context(self): context = super().get_serializer_context() # Is this somewhere I can get to it? data = self.paginate_queryset(self.filter_queryset(self.queryset)) context["extra_stuff"] = get_extra_stuff_for(data) return context -
How to fix Heroku Openai Django Deployment Error?
When deploying a new Heroku App Using a Django Docker Enviorment Inside my requirments.txt I have openai==0.11.0 When doing git push heroku master During Build I get this Error Building wheel for pandas (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for pandas (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [1803 lines of output] gcc: fatal error: cannot execute 'cc1plus': execvp: No such file or directory compilation terminated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] Building wheel for numpy (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for numpy (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [251 lines of output] RuntimeError: Broken toolchain: cannot link a simple C++ program. note: A compiler with support for C++11 language features is required. [end of output] Any help really appreciated. Thank You -
Django admin.TabularInline import csv function
The following code is an inline class, how to make it support the import and export functions of django-import-export。 class DataSourceTableFieldline(admin.TabularInline): # resource_class = DataSourceTableFieldForm model = DataSourceTableField list_display = ( 'column_name_cn', 'column_name_en', 'column_type', 'column_length', 'ordinal_position', 'column_is_pk') extra = 0 class DataSourceTableAdmin(admin.ModelAdmin): inlines = [DataSourceTableFieldline] list_display = ['table_name_zh', 'table_name_en', 'table_logical_name', 'table_code', 'table_sort_id'] search_fields = ['table_name_zh', 'table_name_en'] list_display_links = ['table_name_en'] -
"detail": "JSON parse error - Extra data: line 1 column 9 (char 8)" in django rest framework post request
Here is my view @api_view(["POST"]) def afficher_donnees_instantanees(request): if request.method == "POST": print(request.data) deveui = request.data["deveui"] donnees = Historique.objects.filter(infos_signal__machine=deveui, infos_signal__jour=datetime.today()).order_by("-id").first() serializer = HistoriqueSerializer(donnees) return Response(serializer.data) else: return Response({"echec": "echec"}) serializer.py class HistoriqueSerializer(serializers.ModelSerializer): class Meta: model = Historique fields = '__all__' I want to display data from my Historique model in response to a POST request, but I get the message "JSON parse error - Extra data: line 1 column 9 (char 8)". Knowing that the response code is 400. Where can this error come from please? -
Django can't get the correct url path to media file
I have a problem when I try to show the media files pictures from my database Django keeps renaming '/media/' to '/dashboard/' in the requests to my media files here is the model:` class PetPhoto(models.Model): photo = models.ImageField( upload_to='photos/', blank=True ) tagged_pets = models.ManyToManyField( Pet, ) description = models.TextField( null=True, blank=True, ) publish_date = models.DateTimeField( auto_now_add=True, ) likes = models.IntegerField( default=0, ) Here is the view class CreatePetPhotoView(auth_mixin.LoginRequiredMixin, views.CreateView): model = PetPhoto template_name = 'web/photo_create.html' fields = ('photo', 'description', 'tagged_pets') success_url = reverse_lazy('dashboard') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) ` Here is settings.py MEDIA_ROOT = BASE_DIR / 'mediafiles' MEDIA_URL = '/media/' Here is the urls.py file from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('petstagram.web.urls')), path('accounts/', include('petstagram.accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django admin form multi validation
admin.py class UserControlAdmin(ExportActionMixin, admin.ModelAdmin): form = UserControlModelForm fields = ('user', 'team', 'position') forms.py class UserControlModelForm(forms.ModelForm): def clean_position(self): position = self.cleaned_data['position'].id if not isinstance(self.cleaned_data['team'], type(None)): team = self.cleaned_data['team'].id ... if p['company_group'] != t['company_group']: raise ValidationError('...') return self.cleaned_data['position'] def clean_team(self): if isinstance(self.cleaned_data['team'], type(None)): position = self.cleaned_data['position'].id if position < 4: ... raise ValidationError('...') return self.cleaned_data['team'] I get error KeyError at /admin/information/user/add/ 'position'. I found a problem that, inside clean_team doesn't have position value because position stands behind team in admin fields. How can I fix that? Is it possible to check after getting all parameters? In post request still have position parametr. -
Django multi project user management
I want to learn is there a way to keep django multi project and authenticate/authorize them with one project? For example: I have Project-B and Project-C with different operation fields like hotel automation and gas station. Both of them are my products and I want to manage them by keep licences and users in one place, in other words different project, Project-A. In Project-B and Project-C has it's own apps and apps' models so I don't want to merge them in one project, I want to keep them separate. But I want authorize/authenticate users from one place Project-A. So Project-A will be used only for management. I am planning to use OAuth toolkit for it, but in the first place I have another problem. Project-B and Project-C's apps' models have foreign key fields and many to many fields that defined in Project-A like customer itself. Authentication can be solved Rest Framework and OAuth2 I think but I don't have a solution for this problem. Can you help me out? Thanks in advance. -
Django access related items in template
Please help me I’m stuck in understanding how Django ORM works. Here is my very simple models: class Department(models.Model): title = models.CharField(max_length=50) class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.PROTECT) I want a template that looks like: Department 1 Employee 1 Employee 2 Department 2 Employee 3 Employee 4 But I can’t figure out what I should do in my view and(or) template -
how to display images in templates while using django wagtail
I have the codes below: models.py class BlogImagePage(Page): feature_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True) body = RichTextField(blank=True) excerpt = models.TextField(blank=True) thumbnail_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True) content_panels = [ FieldPanel('title'), FieldPanel('body', classname='full'), FieldPanel('excerpt'), ImageChooserPanel('feature_image'), ImageChooserPanel('thumbnail_image'), ] class BlogPageIndex(Page): content_panels = [ FieldPanel("title"), ] class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] using wagtail admin I am able to create an instance of the table BlogImagePage. Now i am trying to display the image field in the BlogPageIndex page: blog_page_index.html {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-blogindexpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <div class="intro">{{ page.intro|richtext }}</div> {% for post in page.get_children %} <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2> {{ post.specific.body|richtext }} {% endfor %} {% endblock %} It does show/render the instance with the title but unfortunately i am not able to render/display the image saved either on the page above or the detail page of BlogImagePage instance that has the code below blog_image_page.html {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-blogindexpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <div class="intro">{{ page.intro|richtext }}</div> {% for post in page.get_children %} <h2><a … -
How to deploy a Django backend and Flutter frontend web app
I've been working on a web application that uses Django REST Framework and Django channels in the backend and has a Flutter frontend. It works successfully when tested locally, but my question was how would I deploy this: What server is most appropriate for this application? (it should be free as this is just a personal project I've been testing) Do I need to deploy the frontend and backend separately? Are there any online resources I can refer to, to help me in this process? Any help is appreciated :) -
Django get user data in main template
I'm trying to check if user logged in in the main template using this: {%if request.user%} ... {%endif%} but it's not working maybe because main template doesn't have a view could any one help i don't know if the question duplicated,but i didn't find my answer. -
How can we specify organization level permissions using Django Rest Framework
I am new to Django authentication and Authorisation , we have a login and signup implemented with ReactJS on the client side and the Django JWT authentication on the server side. Now, I want to take this to next level by adding authorisation aswell by making users from same organizations only must be able to view/read/write the data existing in the application. Every user will be identified using a specific domain name ex: @gmail.com,@xyz.com. Users from one domain must not have any access to the database of the other organizations. I think we can achieve this with Permissions concept in Django but dont know how we can do it technically. Any ideas are well appreciated. Thanks -
django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails
from django.db import models from django.contrib.auth.models import User Previously my models was like this . class Login(models.Model): pid = models.AutoField(primary_key=True) custom_username = models.BooleanField(default=False) tnx_hash = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.username Then i changed to like this to inherit from base admin user model. class Login(User): pid = models.AutoField(primary_key=True) custom_username = models.BooleanField(default=False) tnx_hash = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.username Now when i am running makemigrations and migrate getting below error . File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`baby`.`#sql-16a7_6a`, CONSTRAINT `api_login_user_ptr_id_7f748092_fk_auth_user_id` FOREIGN KEY (`user_ptr_id`) REFERENCES `auth_user` (`id`))') Please take a look. How can i solve this problem safely. Because i have data in my database and login table is foreign key for many tables. -
Move Authentication error in django crispy form
I created a login page using django authentication system. The validation errors are showing good, but I don´t know how to manipulate location for my error messages within my LoginForm layout. I attached where I need to displace my message message displacement forms.py class LoginForm(AuthenticationForm): remember_me = forms.BooleanField(required=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = "id-authenticationForm" self.helper.form_class = "form-signin" self.helper.form_method = "post" self.helper.form_action = "login" self.helper.layout = Layout( HTML("""{% load static %}<img class="mb-4" src="{% static 'images/logo.jpg' %}" > <h1 class="h3 mb-3 fw-normal">Please sign in</h1>"""), FloatingField("username", "password"), Div( Div( Div("remember_me", css_class="checkbox mb-3"),css_class="col"), Div(HTML("<p><a href='{% url 'password_reset' %}'>Lost password?</a></p>"),css_class="col"), css_class="row" ), Submit('submit', 'Sign in', css_class="w-100 btn btn-lg btn-primary"), HTML("""<p class="mt-5 mb-3 text-muted">&copy; 2022 all rights deserved</p>""") ) login.html.py {% extends "blog/base.html" %}{% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} views.py def custom_login(request, user, backend=None): """ modificated generic.auth login. Send signal with extra parameter: previous [session_key] """ # get previous seesion_key for signal prev_session_key = request.session.session_key #send extra argument prev_session_key user_logged_in.send(sender=user.__class__, request=request, user=user, prev_session_key=prev_session_key) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): super().form_valid(form) """Security check complete. Log the user in.""" #changed default login custom_login(self.request, form.get_user()) #get remember me data from cleaned_data of … -
Unable to call django view using ajax
I want to call the django view from client side that will display all the messages from the models on the html page AJAX function <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/load_with_room_name/{{room_name}}/", success: function(response){ console.log(response); $("#display").empty(); }, error: function(response){ alert('An error occured') } }); },1000); }) </script> django view function def load_with_room_name(request,room_name): try: current_user = Account.objects.get(email=str(request.user)) chat_room = ChatRoom.objects.get(room_name=room_name) if chat_room.room_user_1 == current_user or chat_room.room_user_2 == current_user: print(current_user) return redirect('room',room_name,current_user.username) else: return redirect('chat') except Exception as e: log_exception(request,e,view_name="load_with_room_name") return render(request,"error.html") django urlpattern for the above view urlpatterns = [ path('load_with_room_name/<str:room_name>',views.load_with_room_name,name='load_with_room_name'), ] -
Angular 12 - I get data from backend to component but it doesn't show on my HTML View
Since yesterday I am trying to understand what I did wrong. I want to pass data from my django backend to my frontend angular. Supposedly, backend is sending data. I can see it by this command: [18/Mar/2022 11:41:46] "GET /list-users/ HTTP/1.1" 200 82 My front end is making the request, and my backend is responding aswell. Also, I can see the results by a console.log here: Array(5) [ "admin@lab.com", "lab@lab.com", "lab2@lab.com", "lab3@lab.com", "lab4@lab.com" ] 0: "admin@lab.com" 1: "lab@lab.com" 2: "lab2@lab.com" 3: "lab3@lab.com" 4: "lab4@lab.com" length: 5 <prototype>: Array [] main.js:164:80 I guess, everything is right until now. This is my component code, and my html component code. import {Component, OnInit} from '@angular/core'; import { SharedService } from 'app/shared.service'; @Component({ selector: 'app-regular', templateUrl: './regular.component.html', styles: [] }) export class RegularComponent implements OnInit { userlists: any; constructor(private service: SharedService) { } ngOnInit() { this.getUserlist(); } getUserlist() { let observable = this.service.getUsersList(); observable.subscribe((data) => { this.userlists = data; console.log(data); return data; }); } } html component <div class="card main-card mb-3"> <div class="card-header"> </div> <table class="table table-striped"> <thead> <tr> <th scope="col">No.</th> <th scope="col">Date</th> <th scope="col">Patient Code</th> <th scope="col">Status</th> </tr> </thead> <tbody> <tr *ngFor="let user of userlists"> <td>{{user.email}}</td> … -
How to get table data based on id which obtains from another table data? Django
Views company = Company.objects.get(id = company_id) # getting input from django urls (<int:company_id>) vehicles = CompanyContainVehicles.objects.filter(company_id=company.id) # Give all rows having same id (company.id) all_vehicles = Vehicles.objects.filter(id=vehicles.vehicle_id) # Not Working How do I get data from tables whose multiple id's obtained by another table? Models class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) description = models.TextField() class Vehicles(models.Model): id = models.AutoField(primary_key=True) vehicle_number = models.IntegerField() name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) class CompanyContainVehicles(models.Model): id = models.AutoField(primary_key=True) company_id = models.ForeignKey(Company, on_delete=models.CASCADE) vehicle_id = models.ForeignKey(Vehicles, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) Above are my table details and I need to get all vehicles from table Vehicles which is obtained from CompanyContainVehicle table (that define which company seel out which vehicle) based on company_id that obtain from table Company which contains details of companies.