Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I add an item to the cart without the page reloading?
So I wanna add an item to the cart without the page reloading every time, I've used ajax in a previous project and the response time wasn't pretty, so is there a better way to go about this, that won't be slow? if so, how would I fix this? also not the best with javascript so if u can explain stuff a bit, I would really appreciate your help, thx! link to the rest main code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 template: {% load static %} <link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < … -
How to have associated models to be directly linked to a ModelAdmin in the admin panel?
how do I make it better for the website operator to process the order, can we have each orderitem and shippingaddress associated with the order to be under each "Order" in the admin panel? for example when someone clicks on an Order, he sees the Order data and he's able to scroll and also see the orderitem, and shipping address, would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) date_added = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=40, choices=STATUS_CHOICES, default="Order Placed") tracking_no = models.CharField(max_length=300, null=True, blank=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=300) zipcode = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) what it looks like rn: admin.py admin.site.register(Order, OrderAdmin) admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(ShippingAddress, ShippingAddressAdmin) -
Django Gitlab CI/CD Problem with WEB_IMAGE=$IMAGE:web
I am new to Gitlab CI/CD. I have a django project running on my local machine in docker. I want to configure Gitlab CI/CD with my django project (database is postgres, proxy server is nginx). Here are my config files. .env DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] DATABASE=postgres SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=foo SQL_USER=foo SQL_PASSWORD=foo SQL_HOST=db SQL_PORT=5432 POSTGRES_USER=pos POSTGRES_PASSWORD=123456 POSTGRES_DB=foo Dockerfile: FROM python:3.9.6-alpine ENV HOME=/web ENV APP_HOME=/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles WORKDIR $APP_HOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /web/entrypoint.sh RUN chmod +x /web/entrypoint.sh COPY . /web/ RUN python manage.py collectstatic --no-input --clear ENTRYPOINT ["/web/entrypoint.sh"] docker-compose.yml version: '3.8' services: web: build: . command: gunicorn pos.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/web/ - static_volume:/web/staticfiles ports: - 8000:8000 env_file: - ./.env db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env nginx: build: ./nginx ports: - 1337:80 volumes: - static_volume:/web/staticfiles depends_on: - web volumes: postgres_data: static_volume: entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py … -
Using Header Referer risk to hold needed values for endpoint
I want to use the header referer to communicate between Authenticated URLs in my app. Normally the end point URLs comes like this: appsite.com/editor/UUID-39929922 My plan is to present this view without the UUID-39929922 param. So the url end point should be as below, if I use the referer header to carry the UUID: appsite.com/editor My question is, Is there any downside to doing this? -
Django: Will large uploads hang the server?
I’m using: Django Django rest framework Django Storages with s3 I’m wondering if large (50mb+) uploads to a RestFramework FileField will hang the server from processing requests while the upload completes. Is this a concern? Should uploads be done somehow else? -
adding bind attribute to django cirspy form field
I was trying to add an alpine js directive which is x-bind:attr to a crispy form field but I couldn't find a solution that works, I know that attributes with a dash are handled by using an underscore, I tried to do the same by replacing double underscore with the double colon but It didn't work and no replacement is made. class ChildFormSetHelperUpdate(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.include_media = False self.layout = Layout( Div( Div(Field('model', x_bind__disable="disableInput"), css_class='col-md-6'), Div(Field('model_option'), css_class='col-md-6'), Div(Field('DELETE', css_class='input-small'), css_class="delete_row"), HTML( '<div class="row mt--2"><div class="col-md-6"><button type="button" class="btn btn-danger btn-sm text-white" x-on:click="hideForm($el,target)">Delete</button></div></div>'), css_class=f"row formset") ) self.attrs.update(dict( [((k.replace('__', ':')), conditional_escape(v)) for k, v in kwargs.items()])) self.render_required_fields = True``` -
django filter __contains returns no value on a list while __in does
am essentially trying to perform a select * from xyxtable where col like '%value%' on a list of alphanumeric values from another dataframe column(prev_df['VendorPartNumber]. I thought the filter __contains= should do the trick. but this returns nothing product_df=pd.DataFrame(Product.objects.filter(legacy_productid__contains=prev_df['VendorPartNumber']).values('id','legacy_productid')) however using the __in to filter works (just that the result is not what I want since __in tests for equality) product_df=pd.DataFrame(Product.objects.filter(legacy_productid__in=prev_df['VendorPartNumber']).values('id','legacy_productid')) I tried a couple of things such as product_df= Product.objects.all() for search_term in perv_df['VendorPartNumber']: product_df = product_df.filter(legacy_productid__contains=search_term) or product_df=pd.DataFrame(Product.objects.filter(reduce(operator.and_, (Q(legacy_productid__contains=x) for x in prev_df['VendorPartNumber']))).values('id','legacy_productid')) what am I missing? -
Static file are not working in Django "js/jquery.magnific-popup.min.js" 404
All static file is probably working but 2 files are not working. I want results like this in my HTML file. **My Code ** <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> <script src="{% static 'js/asyncloader.min.js' %}"></script> <!-- JS bootstrap --> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/owl.carousel.min.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/jquery.counterup.min.js' %}"></script> <!-- popper-js --> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/swiper-bundle.min.js' %}"></script> <!-- Iscotop --> <script src="{% static 'js/isotope.pkgd.min.js' %}"></script> <script src="{% static 'js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'js/slick.min.js' %}"></script> <script src="{% static 'js/streamlab-core.js' %}"></script> <script src="{% static 'js/script.js' %}"></script> ** Getting Cmd error** [17/Apr/2022 02:54:56] "GET / HTTP/1.1" 200 55322 [17/Apr/2022 02:54:56] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 160392 [17/Apr/2022 02:54:56] "GET /static/css/style.css HTTP/1.1" 200 154139 [17/Apr/2022 02:54:56] "GET /static/css/all.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:56] "GET /static/css/fontawesome.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:56] "GET /static/js/swiper-bundle.min.js HTTP/1.1" 200 140317 [17/Apr/2022 02:54:56] "GET /static/css/ionicons.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:56] "GET /static/css/owl.carousel.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-6.jpeg HTTP/1.1" 200 315755 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-5.jpeg HTTP/1.1" 200 248498 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-4.jpeg HTTP/1.1" 200 340003 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-1.jpeg HTTP/1.1" 200 179687 [17/Apr/2022 02:54:57] "GET /static/css/flaticon/fonts/ionicons.ttf HTTP/1.1" 200 188508 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-3.jpeg HTTP/1.1" 200 … -
A user just can a one comment, What will be the logic?
I already made a review form where user can give their feedback on the service. The form works perfectly, and data is also stored in the database. There is a rating star options as well. Now I just want to make a system where the user just can do one review. If a user did a review the review form won't show to the user. Now, what should I do? and What'll be the logic? models.py: class Frontend_Rating(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="frontend_rating") Rating = models.IntegerField(null=True) Feedback = models.TextField(max_length=250, null=True) template: <form action="frontend_ratings/" class="mt-3" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="radio-toolbar d-flex justify-content-center "> <input type="radio" id="one_star" name="frontend_ratting" value="1" checked> <label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label> <input type="radio" id="two_star" name="frontend_ratting" value="2"> <label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label> <input type="radio" id="three_star" name="frontend_ratting" value="3"> <label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label> <input type="radio" id="four_star" name="frontend_ratting" value="4"> <label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label> <input type="radio" id="five_star" name="frontend_ratting" value="5"> <label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label> </div> <!-- feedback area--> <div class="d-flex justify-content-center"> <textarea style="font-size: small;" maxlength="250" name="frontend_feedback" placeholder="Share your experience in 250 charecters...." class="col-10 mt-2 hireme_textarea btn montserrat text-left d-block" required rows="5"></textarea> </div> <div class="d-flex justify-content-center mt-3"> <button type="submit" class="btn singUpBtn col-10 submit_btn_sing_up_in sing_up_js1" id="message">Save</button> </div> … -
How to get and display data from database without refresh page using ajax and django
I want to get and display data from database to my page using django and ajax. This is my view : def getMessages(request, sender_id, receiver_id): if request.user.profile == 'A': chat = Chat.objects.filter(Q(sender_id=sender_id) | Q(receiver_id=sender_id)).all() elif request.user.profile == 'C': chat = Chat.objects.filter(Q(sender_id=sender_id,receiver_id=receiver_id) | Q(sender_id=receiver_id,receiver_id=sender_id)) return JsonResponse({"chat":list(chat.values())}) And This is my javascript: $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'getMessages/{{request.user.id}}/to/{{receiver_user.id}}'}", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.chat) { var temp='<div class="msg-box {% if request.user == msg.sender %} right {% else %} left {% endif %}"><div class="details"><p class="msg">{{ msg.message }}</p><p class="date">{{ msg.msg_time }}</p></div></div>'; $("#display").append(temp); } }, error: function(response){ console.log('An error occured') } }); },1000); }); And this is my urls.py: urlpatterns = [ path('<int:sender_id>/to/<int:receiver_id>',views.chat), path('send/', views.send, name='send'), path('getMessages/<int:sender_id>/to/<int:receiver_id>', views.getMessages, name='getMessages'), ] I try these codes but it doesn't work. -
django-bootstrap-modal-forms additional data in trigger
Using the following JQuery to trigger a modal: $("#view-large").modalForm({ modalID: "#fullscreen", formURL: "{% url 'view-fullscreen' ID %}" }); The 'ID' i formURL is is what I'm missing. It's from a subset of a query set (double foreach) and it prints a data-id="" into a html tag. How do I get that ID into the Jquery -
HTMX pass button value from selected list
I'm trying to make an application with Django using htmx. I have created a dropdown list as: <select class="custom-select mb-4" name="fields" hx-get="{% url 'select_field' %}" hx-trigger="change" hx-target="#Wells"> <option selected>Select a field</option> {% for Field in TFTFields %} <option ue="{{Field.Perimeter}}">{{Field.Perimeter}}</option> {% endfor %} </select> Now I want to take the selected value from this list and pass it to a button to excite another function called "plotlybar", I did something like this: <button class="btn btn-primary" hx-get="{% url 'plotlybar' %}" hx-target="#plotlybar">Plot the bar Well Serv</button> So now I didn't know how to pass this selected items? any hints or solution? All my best -
Getting correct data order from queryset python
I have a problem, then when I'm trying to get specific values from query set its giving me this in alphabet order. Example: account_data = Account.objects.all() [<Account: Merchant: ID: 267 (google@gmail.com), Currency: RUB, Brand: Brand NEWW (google@gmail.com)>, <Account: Merchant: ID: 265 (goole@gmail.com), Currency: EUR, Brand: Brand new (google@gmail.com)>, <Account: Merchant: ID: 264 (google@gmail.com), Currency: USD, Brand: Brand new2 (google@gmail.com)>, <Account: Merchant: ID: 266 (google@gmail.com), Currency: TRY, Brand: Brand new 3 (google@gmail.com)>, <Account: Merchant: ID: 269 (google@gmail.com), Currency: BGN, Brand: Brand new 4 (google@gmail.com)>] currency = ', '.join(sorted(list(account_data.values_list('currency__code', flat=True)))) Out[66]: 'BGN, EUR, RUB, TRY, USD' And this issue appears for all values, need to get currency connected to a specific account, not random or alphabet order. -
no such column error when trying to retrieve data in raw() Query in Django
I have the following classes in my models.py class Users(models.Model): username = models.CharField('User Name', null=False, max_length = 50) password = models.CharField('User Password', max_length=50) def __str__(self): return self.username def get_filepath(filename): old_filename = filename ts = time.time() timeNow = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y_%H-%M-%S') filename = "%s%s" % (timeNow, old_filename) return filename class Photo(models.Model): name = models.CharField(max_length=100, default="Image") id = models.AutoField(primary_key=True) uploader = models.ForeignKey(Users, default=None, on_delete=models.CASCADE) def __str__(self): return self.name class Photo_History(models.Model): image = models.ImageField(upload_to="media/results") upload_time = models.DateTimeField(auto_now_add=True, blank=True) photo_id = models.ForeignKey(Photo, null=True, blank=True, on_delete=models.CASCADE) What I am trying to access is, a user is logged in. I need to get the Photo History Objects along with the "name" from the Photo model of the user who's currently logged in. I tried to search a way to write a command using filter function to get this but I couldn't find any results that showed how you can get data from two different tables in a single query. And instead, people mentioned I should be using raw() query. So I used the raw query which I believe is totally fine, but I am getting a weird error (which you get if you haven't done in your migrations, but my migrations were done long ago and the column … -
Create Image Gallery accessble by a pin number
I'm trying to create an Image Gallery. I'm wanting the ability to upload multiple images at once and have them accessible to the customer by a pin number. I'm using Django and have tried a few different ways but can't seem to come up with something that works for the desired result I'm after. Any ideas or leads on the best way to accomplish this? Thank you! Jared -
apache2 throws the 500 error every time I restart the server (Python Django project)
I have a problem with my apache 2 server. Apparantly the problem was in the wsgi.py file connection because when I changed the DEBUG variable to true ,nothing changed. Here is my .conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the … -
how to run django custom management command using crontab?
I want to delete expired file every min I created command python manage.py delete which delete all expired files. but crontab won't work, I don't know maybe I did something wrong. here cronjobs in settings.py CRONJOBS = [ ('* * * * *', 'django.core.management.commands.delete'), ] so how can I fix this? -
how do I add an item to the cart without the page reloading
So how do I do this? if I gotta use REST api how do I set it up? would really appreciate your help, thx! link to the code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 -
Not able to create heroku-redis for my heroku application
I have been trying to add a heroku-redis add on to my django application deployed on heroku,usually free add-ons like heroku PostgreSQL and heroku-redis should not need me to verify my account with billing but for some reason I can't create a heroku-reddis add-on but can normally create Heroku Postgres add-on Here's the error I'm getting -
Can't send http request from React to Django, using nginx and certbot
I have a docker swarm where I configured a React app on port 3000, Django backend on port 8000, nginx and certbot. On the frontend part everything works great and all the routes have ssl. However, whenever I try to send a request from my React app to Django it fails. Desired behavior: 1.Access frontend on http 2.Nginx forwards it to https 3.Https frontend sends http request to Django 4.Django sends back a http request which is forwarded to https by nginx This fails at step 4 where there is an error because of the https and http trying to communicate with each other. I send my request as: fetch("http://example.com:80/app/receipt") and get the error login.js:55 Mixed Content: The page at https://example.com/login' was loaded over HTTPS, but requested an insecure resource <the same route but http>. This request has been blocked; the content must be served over HTTPS. I understand what the problem is, but I have not configured https separately in my backend app and I was hoping there is a way to do this only from the nginx configure file. From what I read, generating a self-signed certificate is not a good idea. I do not currently understand how … -
Cannot assign "'username'": "Message.sender" must be a "User" instance
I'm fairly new to Django / Channels so apologies if everything required isn't being shown here. I'd be happy to provide further info if necessary. Anyway, I've been working on a one-to-one chat application and am running into this error: ValueError: Cannot assign "'admin'": "Message.sender" must be a "UserProfileModel" instance. This issue is that I thought admin was an instance of my user model? admin is the username of my superuser, which is logged in as I get this error. When I try to change the admin input to self.scope['user] I then get a serialization error. Any help is appreciated. Here is my consumers.py file: import json from channels.generic.websocket import WebsocketConsumer from django.conf import settings (unused) from accounts.models import UserProfileModel from asgiref.sync import async_to_sync from chat.models import Thread, Message class ChatConsumer(WebsocketConsumer): def create_chat(self, msg, sender): new_msg = Message.objects.create(sender=sender, text=msg) new_msg.save() return new_msg def connect(self): self.me = self.scope['user'] self.user_name = self.scope['url_route']['kwargs']['room_name'] self.you = UserProfileModel.objects.get(username=self.user_name) self.thread_obj = Thread.objects.get_or_create_personal_thread(self.me, self.you) self.room_group_name = f'personal_thread_{self.thread_obj.id}' # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() print(f'[{self.channel_name}] [{self.room_group_name}] connected') def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) # WHAT IS TEXT_DATA REFERRING TO? … -
Debugging Django on a deployed remote server
I am running Django with Nginx and Gunicorn on a remote server. There are certain types of interactions I can do on the remote machine (via my web browser) that will cause the webserver to respond with a "502 Bad Gateway nginx/1.10.3 (Ubuntu)" error after doing certain POST operations to the Django webserver. This error happens repeatably after exactly 30 seconds. Which makes me think it's some kind of timeout with Nginx. When I run the Django server locally everything runs fine. But I don't think this is a problem with Nginx, I think it's a problem with Django on the remote system. Can anybody provide any guidance about how to see what is going on with Django on the remote machine? Or how to debug this problem further. -
How to have orderitem and shipping under each order in the admin panel?
how do I make it better for the website operator to process the order, can we have each orderitems and shipping addresses associated with the order to be under each "Order" in the admin panel? would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) date_added = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=40, choices=STATUS_CHOICES, default="Order Placed") tracking_no = models.CharField(max_length=300, null=True, blank=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=300) zipcode = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) admin.py admin.site.register(Order, OrderAdmin) admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(ShippingAddress, ShippingAddressAdmin) -
How to create arrays out of Rest Api data DJango Angular Typescript
I have this returned and stored in a variable "detections: any =[]" from my rest API in django. [ { "DetectionId": 2, "CityId": 2, "TimeUpdated": "2018-11-20T21:58:44.767594Z", "Percent": 22, }, { "DetectionId": 3, "CityId": 2, "TimeUpdated": "2016-11-20T21:58:44.767594Z", "Percent": 22, } ] Im trying to move all "Percent" and "TimeUpdated" values into seperate arrays so I can connect them to a line graph in ChartJS but as this is my first time using advances typescript and rest APIs I dont know how to approach this problem as I need to have this data connected to a chart. any help or advice is greatly appreciated. -
Django - Is it possible to get objects of "indirectly related one to one field" with reverse_many_to_one_manager?
For instance I have these models: class Company(models.Model): name = models.CharField(max_length=100) class User(AbstractBaseUser): email = models.EmailField(max_length=250, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.PROTECT) is_admin = models.BooleanField(default=False) Now I can easily get all the profiles for a company using the following query: Company.objects.first().profile_set.all() But is there a way I can get the related users from company instead of profile, keeping in mind that a user object is one to one related with profile object? Note: These models are just example models, and keeping in view the application logic, we can't combine user and profile model.