Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django standalone app - problem reading app settings in main project
I am using Django 3.2 I am writing a standalone app MyApp that uses GeoIP2 I want to be able to have a project using the MyApp app, to be able to do either one of the following. set GEOIP2_PATH in project.settings OR (default) fall back on the GEOIP2_PATH value set in MyApp.settings This is what I have so far: MyApp/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GEOIP_PATH = os.path.join(BASE_DIR, 'userprofile/geodata') # ... MyApp/utils.py from django.conf import settings from MyApp import settings as myapp_settings def get_attribute_from_settings(attribute_name): try: value = getattr(settings, attribute_name) except AttributeError: try: value = getattr(myapp_settings, attribute_name) except AttributeError: raise ImproperlyConfigured() finally: return value Code that uses GeoIP2 from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception from ipware import get_client_ip geo = GeoIP2() def do_something(address): # Barfs at next line: info = geo.city(address) When the function above is called, I get the following exception thrown: raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.') django.contrib.gis.geoip2.base.GeoIP2Exception: GeoIP path must be provided via parameter or the GEOIP_PATH setting How can I use the get_attribute_from_settings() to get the default GEOIP2_PATH if not set in project.settings? -
Filter Django query by annotated field using a subquery
I am trying to further filter a Django query using an annotated field: My (simplified) tables: class Inventory(models.Model): item = models.CharField(max_length=10, primary_key=True) lot = models.CharField(max_length=10) ... MORE FIELDS ... class Car(models.Model): name = models.CharField(max_length=10) item= models.ForeignKey(Inventory, on_delete=models.PROTECT, null=True, blank=True) ... MORE FIELDS ... I would like my results set for the Inventory query to include the name of the car assigned to that item. This works fine: Inventory.objects.annotate(car=Subquery(Cars.objects.filter(item=OuterRef('item')).values('name'))) The car name is retrieved in the queryset. I used to have the car in the item (so it was easy to filter on the car), but due to other requirements, I has to move the reference the other way around - car now has an item field). I ensure that once an item is associated with a car, it cannot be used again for another car since the Subquery must return a single result. Now, I would like to further filter the queryset by the annotated field that brings back car: Inventory.objects.annotate(car=Subquery(Cars.objects.filter(item=OuterRef('item')).values('name'))).filter(car__icontains='AA') Now, I get an error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) Is it possible to do this the way I am trying? -
Deployment in the digital ocean and Django multiplies sessions
I have an application deployed in digital ocean already in production mode (ubuntu); For some reason I can't log in: I enter my credentials and all is well but I am not redirected. In the database I store some data of the session, whether you log in or not, a single user should generate a single record, but it generates between 12-18 records per page, that is, visiting a couple of links will have already stored around 30. I have mounted the service locally and it does not present this inconvenience, neither in production or development mode. What could it be? -
How to retry Django Celery task on Exception when Internal Server Error is raised?
I am trying to use Celery to send anywhere from 1 to about 25 consecutive requests to a third-party API. The measure of success is whether I get a URL back in the response payload: response_json["data"]["url"]. Celery or not, sometimes I get the data I expect, and sometimes I don't. I decided to experiment with Celery to retry the API call while taking advantage of the built-in exponential backoff, which sounds perfectly suited to my needs, but I am struggling to implement. When the data I am expecting is not available in the response payload, I get a TypeError: 'type' object is not iterable (i.e., there is no such item in the response). But I am also getting an Internal Server Error, which I wonder whether I need to handle or whether I could use to trigger the retry. Here is a example of one of several similar approaches I have tried: @shared_task(autoretry_for=(Exception), retry_backoff=True, retry_backoff_max=120) def third_party_api_request(payload, api_url, headers): response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() return response_json["data"]["url"] # output: Internal Server Error: -- snip -- autoretry_for = tuple( TypeError: 'type' object is not iterable Another approach I have tried: @shared_task(bind=True) def third_party_api_request(self, payload, api_url, headers): try: response … -
Timestamped model __init__() got multiple values for argument 'on_delete'
I'm trying to create a foreignkey relationship in DRF models with an on_delete fk_city = models.ForeignKey("region_mgmt.City", "warehouses", on_delete=models.SET_NULL) TypeError: __init__() got multiple values for argument 'on_delete' below is my code: from django_extensions.db.models import TimeStampedModel class State(TimeStampedModel, models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=100) postal_code = models.CharField(max_length=20, blank=True, null=True) fk_country = models.ForeignKey(Country, related_name="states", on_delete=models.CASCADE) def __str__(self): return self.name class City(TimeStampedModel, models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=100) postal_code = models.CharField(max_length=20, blank=True, null=True) fk_state = models.ForeignKey(State, related_name="cities", on_delete=models.CASCADE) def __str__(self): return self.name does anyone know the reason and its solution? -
Create index on nested element JSONField for Postgres in Django
I have a Django model in my python project with a meta class detailing it's indexes. I'm curious if there's a way to create the index using the nested path of the json object. In this case we know the structure of our json and I wanted to stick with a BTree or Hash index on the specific element. If I were simply running this as raw sql, I'd expect to just do something like: CREATE INDEX ON foster_data(root->'level_1'->'level_2'->>'name'); I was hoping I could do something like this in my model: from django.db import models from django.contrib.postgres import indexes class ParentGuardians(Facilitators): # which extends models.Model parent_identifier = models.IntegerField(db_column='p_id', default=None, blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['table_id', name='UniqueConstraint for Parents') ] indexes = [ models.Index(fields=['p_id', ]), indexes.BTreeIndex(fields=[models.JSONField('{"root": {"level_1": {"level_2": "name"}}}'), ] , name="jsonb_p_id_idx"), ] or even: ... indexes.BTreeIndex(fields=["root->'level_1'->'level_2'->>'name'", ] ... But the named field fields only wants strings and only wants them to be the top level field defined in the model. I'm aware of this questions: Indexing JSONField in Django PostgreSQL but it seems more of a hack and wanted the result generated from the codebase and makemigrations, not to manually edit it. Is this possible more recently? -
How to configure an NGINX & UWSGI in Django
I am deploying my Django app on VPS and I would like to use NGINX & UWSGI I have followed this tutorial https://www.youtube.com/watch?v=ZpR1W-NWnp4 in order to configure my NGINX server. Below is my NGINX configuration file named my_nginx.conf: # the upstream component nginx needs to connect to upstream django { server unix:///root/PIDC/ProjetAgricole/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name 173.249.8.237; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/PIDC/ProjetAgricole/media; # your Django project's media files - amend as required } location /static { alias /root/PIDC/ProjetAgricole/staticfiles; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/PIDC/ProjetAgricole/uwsgi_params; # the uwsgi_params file you installed } } I just changed the paths only in this file. When I run this command, I am getting this output that seems … -
show Error Message For Duplicate Item {IntegrityError}
I want to be saved reservation information when is not duplicate After the user clicks on the send message button. i Got This Error django.db.utils.IntegrityError: UNIQUE constraint failed: Restaurant_reservation_received.date, Restaurant_reservation_received.time, Restaurant_reservation_received.table_number My Views: if request.method == "POST" and request.POST.get('name'): reservation = Reservation_Received() reservation.name = request.POST.get('name') reservation.date = request.POST.get('date') reservation.time = request.POST.get('time') reservation.count = request.POST.get('count') reservation.table_number = request.POST.get('table_number') reservation.save() return JsonResponse({'msg1':'Success'}) else: pass if request.method == "POST" and request.POST.get('name2'): contactus = ContactUs() contactus.name2 = request.POST.get('name2') contactus.subject = request.POST.get('subject') contactus.email = request.POST.get('email') contactus.message = request.POST.get('message') contactus.save() return JsonResponse({'msg2':'Success'}) return render(request, 'home.html',context) HTML CODE <form class="row" id="reservationform" action="" method="post"> {% csrf_token %} <div class="col-md-10 col-sm-12 center-col"> <div class="col-md-6 col-sm-12 reservation-name"> <input name="name" type="text" placeholder="Your Name" required="True" class="input-round big-input"> </div> <div class="col-md-6 col-sm-12"> <div class="select-style input-round big-input"> <select name="date" required="True"> <option selected="selected" value="">Select Day</option> {% for item in reservation_date %} <option value="{{ item.date }}"> {{ item.date }}</option> {% endfor %} </select> </div> </div> <div class="col-md-6 col-sm-12"> <div class="select-style input-round big-input"> <select name="time" required="True"> <option selected="selected" value="">Select Time</option> {% for item in reservation_time %} <option value="{{ item.time }}">{{ item.time }}</option> {% endfor %} </select> </div> </div> <div class="col-md-6 col-sm-12"> <div class="select-style input-round big-input"> <select name="count" required="True"> <option selected="selected" value="">Select Number Of Person</option> {% for item … -
Some static files can't be loaded because it is blocked by CORS policy (Django) even it is configured based on Django documentation
I faced an issue with a CORS policy and cannot see what is wrong. I use Django framework and my static files are hosted in Azure Blob So I am getting errors for these files and it says tuat Access-Control-Allow-Origin is not present: What is strange that other files from the same host are loaded.. CORS settings looks like this: ALLOWED_HOSTS = ['support.mdesk.lt', 'https://suppaccountstorage.blob.core.windows.net'] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'support.mdesk.lt', 'https://suppaccountstorage.blob.core.windows.net', ) CSRF_TRUSTED_ORIGINS = ['https://support.mdesk.lt'] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'bootstrap4form', 'supportSystem', 'storages' ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] Wham am I doing wrong? -
How can I find how much 1 star/2 star----5star present in percentage?
I've created a form for being stored ratings and feedback in the database. Ratings and Feedback are being stored in the database perfectly. But the problem is, I can't find out how many different types of rating stars are present in the database. How can I find out how many 1 star/2star/---5 stars are present in the object model in percentage? What should I do It? 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) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) + str("(") + str(self.Rating) + str("stars") +str(")") Views.py: def index(request): #rating____________________ frontend_all_ratings = Frontend_Rating.objects.all() number_of_frontend_rating = frontend_all_ratings.count() average_rating = 0 frontend_one_star = 0 frontend_two_star = 0 frontend_three_star = 0 frontend_four_star = 0 frontend_five_star = 0 percentage_frontend_ONE_star = 0 percentage_frontend_FIVE_star = 0 for frontend_rating_item in frontend_all_ratings: frontend_rating = frontend_rating_item.Rating if frontend_rating: total_ratings = 0 total_ratings += frontend_rating average_rating = round(total_ratings/frontend_all_ratings.count(),1) context = { "frontend_five_star":frontend_five_star, "frontend_one_star":frontend_one_star, } return render(request,'0_index.html',context) -
django-polymorphic Aggregate Sum Price
I want a clean way to sum the price of all products in a queryset when using django-polymorphic. Install dependencies: pip install django-polymorphic Create app: manage.py startapp content path: content/models.py from django.db import models from polymorphic.models import PolymorphicModel from polymorphic.managers import PolymorphicManager from django.utils.text import slugify from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Content(PolymorphicModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='content') title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) objects = PolymorphicManager() class Meta: unique_together = ('user', 'slug') def __str__(self): return str(self.title) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Post(Content): pass class Note(Content): pass class ProductA(Content): price = models.DecimalField(max_digits=6, decimal_places=2, null=True) class ProductB(Content): price = models.DecimalField(max_digits=6, decimal_places=2, null=True) path: project/settings.py INSTALLED_APPS = [ ... 'content.apps.ContentConfig' # add this ] AUTH_USER_MODEL = 'content.user' Run: manage.py makemigrations manage.py migrate In interactive shell: u, _ = User.objects.get_or_create(username='user') post = Post.objects.create(user=u, title='First Post') note = Note.objects.create(user=u, title='First Note') prod_a = ProductA.objects.create(user=u, title='First Product A', price=12.99) prod_b = ProductB.objects.create(user=u, title='First Product B', price=18.99) I want a clean way to sum the price of all products in a queryset. Example: qs = Content.objects.instance_of(ProductA, ProductB) Returns: <PolymorphicQuerySet [<ProductA: First Product A>, <ProductB: First Product B>]> Since product A and B both have price, I thought I could … -
PostGIS built for PostgreSQL 13.0 cannot be loaded in PostgreSQL 14.2
I am running arch Linux, I installed postgresql and postgis to work with it in my Django project, but whenever i try to migrate my models i get this error PostGIS built for PostgreSQL 13.0 cannot be loaded in PostgreSQL 14.2 can anyone tell me what's the problem here please -
Django while True try loop in createview
I hope I am not being a little paranoid but I am trying to make that when there is a record or customer number the next record is different from the previous one, the reason why I do it this way is because there will be many people capturing data at the same time every day and I do not want to throw a 404 error or something like that but on the contrary, in case there is already a record in the database retry and retry and retry again. This is an example that I need to conclude to finish well my script, obviously before it makes a request to the database to verify the last record. I know it is possible to do this with function based views but at the moment I am testing class based views, I have been doing this for several hours. Any help is very important to me. Thanks guys. models.py from django.db import models # Create your models here. class Empresa(models.Model): nombre = models.CharField(max_length=20) numero = models.IntegerField(unique=True) views.py from dataclasses import field from django.shortcuts import render from django.views.generic import * from aplicacion.models import Empresa # Create your views here. class CrearEmpresa(CreateView): model … -
Whats the correct structure for Django templates?
I have a project in Django called: "my_site", and an app called "blog", I'm trying to render the "index.html" inside the path: my_site/blog/templates/blog/index.html. But keep getting this error: Template-loader postmortem Django tried loadi ng these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\blog\templates\index.html (Source does not exist) The view: def index(request): return render(request, 'index.html') the urls.py: urlpatterns = [ path('', views.index), path('posts', views.show_all_posts), path('posts/<slug:slug>', views.show_post) ] If i move the index.html outside the blog folder, like in this example: my_site/blog/templates/index.html the code runs and the index.html renders without problem, but i was taught that the correct structure is to create a folder inside templates with the same name of the app. So could anyone please explain me the way i should structure my files? -
Django REST Framework; ImproperlyConfigured; Could not resolve URL for hyperlinked relationship
Am trying to use DRF to make an election tracker; getting on what was supposed to be fairly simple ViewSet list and retrieve endpoints; django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "election-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Model Snippet... class Election(models.Model): _id = models.CharField( name="id", primary_key=True, validators=[election_ids.validate], max_length=32 ) date = ComputedDateField(compute_from="_date") # not relevant parent = models.ForeignKey( to="self", on_delete=models.CASCADE, default=None, null=True ) Serializers class ElectionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Election # Removing the 'url' from below stops the ImproperlyConfigured error on retrieve calls fields = ["url", "org", "date", "constituency", "parent"] read_only_fields = ["url"] depth=1 ViewSet class ElectionViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint that allows elections to be viewed or edited. """ lookup_field = 'id' lookup_value_regex = '[a-z0-9.\-_]+' # this might be the culprit, see below queryset = Election.objects.all().order_by("-date") serializer_class = ElectionSerializer permission_classes = [permissions.AllowAny] and relevant urls.py app_name = "counts" api_router = routers.DefaultRouter() api_router.register(r"users", UserViewSet, "users") api_router.register(r"groups", GroupViewSet, "groups") api_router.register(r"elections", ElectionViewSet, "elections") api_router.register(r"candidates", CandidateViewSet, "candidates") api_router.register(r"stages", StageViewSet, "stages") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("", … -
Is it possible to use f-strings with Concat(), Value() and F()
I have a varchar column whose values I would like to update. Here is what I have tried so far: for item in Item.objects.filter(): some_items = get_some_items(item) Item.objects.filter(field=item.field).difference(some_items).update( field=Concat( Value(settings.PREFIX), Value(f"{F('id'):>010d}") ) ) Which gives me TypeError: unsupported format string passed to F.__format__ I need help on how I can achieve this if possible. -
Filtering numbers from a django list
In my database I have a list of users, each one has an id, this id is CharField, it can contain either a string containing a number (e.g "058") or a string containing something like this "0Y5" I want to filter the list of users to have only the ones that have an id that contain a valid number, like "005", "011", "122", I tried this but it seems not working: users = User.objects.filter(id.isnumeric == True) -
Django Models objects cannot find declaration to go to
I have a simple django app. Inside the models.py folder i have: class TestModel(models.Model): name = models.CharField(max_length=300) def get_all(self): all = TestModel.objects.all() return all Even though I have instances of TestModel in my database (PostgreSQL), the function get_all returns None. PyCharm helped me in narrowing down the problem by marking objects and telling me that it Cannot find a declaration to go to. If I create the project with PyCharm Professional through the UI, this problem does not occur. As soon as I open the application through PyCharm Community, the problem appears and does NOT go away by switching back to Professional. Django version - 3.2.9 and 4.0.0 tested Questions: How to make the Django recognize objects by using PyCharm Community? What is the cause for this strange behaviour? -
Exporting a django template table to xlsx
I'm trying to use django template for the first time and I need to export some data. How can I export a table in my django template to a .xlsx file? Is there any method? here is my views.py: from django.shortcuts import render import requests from .utils import most_frequent, get_json_values, get_max_dict def launches(request): """main request. Retrieve the year that had most launches""" response_launches = requests.get('https://api.spacexdata.com/v3/launches? filter=launch_year') launches = response_launches.json() launch_years = get_json_values('launch_year',launches) result_launches = most_frequent(launch_years) """retrieve the launch site most used for launches """ response_sites = requests.get('https://api.spacexdata.com/v3/launches? filter=launch_site') sites = response_sites.json() launch_sites = get_json_values("launch_site", sites) result_sites = get_max_dict(launch_sites,'site_id') """retrieve the number of launches between 2019 and 2021""" response_2019_2021 = requests.get('https://api.spacexdata.com/v3/launches? start=2019&end=2021') launches_2019_2021 = response_2019_2021.json() result_2019_2021 = len(launches_2019_2021) data = { "year_most_launches": str(result_launches), "launch_sites":result_sites, "launches_2019_2021":str(result_2019_2021) } return render(request,"main/launches.html", {"data":data}) And that's my table inside my template: <table class="table"> <thead> <tr> <th>Year with most launches</th> <th>Launch site with most launches</th> <th>Number of launches between 2019 and 2021</th> </tr> </thead> <tbody> <tr> {% for element in data.values %} <td>{{ element }}</td> {% endfor %} </tr> </tbody> </table> I couldn't find a way to do it so any help is really appreciated! -
No module named 'application' deploying Django 4.0 to AWS Beanstalk
When I try to deploy my project to AWS beanstalk I keep on getting the same error in my logs "ModuleNotFoundError: No module named 'application'". Because of this I get 502 Bad Request errors. I am using Django 4.0. The application runs fine when I run "python manage.py runserver" on the virtual-env. I have followed all the steps described in the tutorial which Amazon provides, yet without success. Of course I have added my server to the ALLOWED_HOSTS, but I don't think that is the problem. Is there something that changed in Django 4.0.4 that could've changed things? In my .elasticbeanstalk/config.yml file I have the line "default_platform: Python 3.8 running on 64bit Amazon Linux 2", which should be compatible with Django 4.0.4. One other thing I have tried is following the same steps from the tutorial again on a new region, with a new application and environment, but this was also not successful. My .ebextensions/django.config file is the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: nameofmyproject.wsgi:application The WSGIPath refers to the wsgi, which is located in nameofmyproject/wsgi.py, which looks like the following: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nameofmyproject.settings') application = get_wsgi_application() -
Accessing a field from a model linked to another model with get_context_data()
I have the following models in my Django app: Model User class User(AbstractBaseUser, PermissionsMixin): username = models.CharField('username', max_length=30, blank=True) email = models.EmailField('Adresse mail', unique=True) first_name = models.CharField('Prénom', max_length=30, blank=True) last_name = models.CharField('Nom', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) company = models.ForeignKey('Company', on_delete=DO_NOTHING, blank=True, null=True) Model Company class Company(models.Model): name = models.CharField(max_length=200, blank=False) transporters = models.ManyToManyField(Transporter, blank=True) Model Transporter class Transporter(models.Model): name = models.CharField(max_length=100) avatar = models.ImageField(blank=True, null=True) Model Supplement class Supplement(models.Model): transporter = models.ForeignKey(Transporter, on_delete=DO_NOTHING, blank=True, null=True) company = models.ForeignKey(Company, on_delete=DO_NOTHING, blank=True, null=True) header_row = models.IntegerField(blank=True) Starting from the user, I would like to access the field header_row in get_context_data(). In my app, the user belongs to a company and the 'supplement' is attached to a Company. Here's what I came with in views.py : class UserSupplementView(TemplateView): model = User template_name = 'tool/try.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user context['supplements'] = user.company.supplement.header_row print(context['supplements']) return context But it's not working and I have the following error message: 'Company' object has no attribute 'supplement' But if I go with context['supplements'] = user.company.supplement_set.all() , I can actually retrieve part of the data. Could you please help me to retrieve the header_row field? -
Chart JS Angular how to display list of data in a line chart
Its my first time using any chart in programming so sorry if this is really simple and im just being an idiot. So I have created a really basic chart using ChartJS in angular. loadChart(): void { new Chart(this.chart,{ type:'line', data: { datasets: [ { data:data:[30, 60, 40, 50, 40, 55, 85, 65, 75, 50, 70], label:"Series 1", backgroundColor: '#007bff', tension: 0.3, } ], labels:['17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', ], }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, } } } }) } I have a get method to my rest api that responds with a bunch of data such as these detections. [ { "DetectionId": 2, "CityId": 2, "TimeUpdated": "2018-11-20T21:58:44.767594Z", "FPercent": 22, }, { "DetectionId": 3, "CityId": 2, "TimeUpdated": "2016-11-20T21:58:44.767594Z", "Percent": 22, } ] How can I add this data to my chart so that it displays each detection as a dot on the line graph. Ideally I would like to plot percent on the Y axis and Timeupdated on the x axis. Any help or advice would be greatly appreciated I've tried a few tutorials but none have worked so far. Also is there any way I can … -
DJango testing multiple database application
I have django application which has two database defaultdb and externdb DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'TEST': { 'NAME': 'test_{0}'.format(config("DB_NAME")), 'MIRROR': "default", }, }, 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config("DB_EXTERN_NAME"), 'USER': config("DB_EXTERN_USER"), 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': config("DB_EXTERN_HOST"), 'PORT': config("DB_EXTERN_PORT"), 'TEST': { 'NAME': 'test_{0}'.format(config("DB_EXTERN_NAME")), 'MIRROR': "extern", }, } } The application works well but when testing ,this error occurs below when trying to access the extern database from extern_db.models import TBasicInfo class HelpViewTest(TestCase): def test_api(self): tb = TBasicInfo.objects.get(info_id=10352) This error occurs AssertionError: Database queries to 'extern' are not allowed in this test. Add 'extern' to defapp.tests.HelpViewTest.databases to ensure proper test isolation and silence this failure. which setting should I check?? -
What are Django's "__init__.py" empty files for? [duplicate]
When i started with a Django template, I saw two __init__.py files. When I looked into, they was empty. What are they for? Or it was a mistake from the template creator? -
How can I fix an error creating newPost in django?
I'm trying to make a new post, but I get "Followers matching query does not exist" as an error. I don't know how to fix it. Could someone help me to solve it?. Attached files. All this done in Django. models.py class Followers(models.Model): user = models.ForeignKey (User, on_delete = models.CASCADE, related_name = "followers") follower = models.ManyToManyField (User, related_name = "following") def __str__(self): return f"{self.user}" class Post(models.Model): content = models.CharField (max_length = 280) created_date = models.DateTimeField (default = timezone.now) creator = models.ForeignKey (User, on_delete = models.CASCADE, related_name = "posts") likes = models.ManyToManyField (User, related_name = "liked_posts") def __str__(self): return f"{self.id}: {self.creator}" views.py @login_required def newPost(request): if request.method == "POST": form = Post (content = request.POST['content']) form.creator = Followers.objects.get (user = request.user) form.save() else: return render (request, "network/index.html") return HttpResponseRedirect (reverse("index")) newPost.html {% for post in posts %} <div class="card-body" style="border: 1px solid rgba(0,0,0,.1);"> <strong><a style="font-size: 20px; color: black;" href="#">{{post.creator}}</a></strong> · <a style="font-size: 14px;">{{post.created_date}}</a> <a href="#" style="font-size: 14px; float: right;">Editar</a> <br>{{post.content}} <br> <a href="#" style="color: black;"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16"> <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 …