Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - annotate based on the count of a foreignkey?
I have the three models below: class User(AbstractBaseUser): ... thing_prefer = models.ForeignKey(thing, on_delete=models.SET_NULL, null=True) class ThingType(models.Model): name = models.CharField() class Thing(models.Model): type = models.ForeignKey(ThingType, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField() # this would have choices defined I currently am using a ListView to list ThingTypes, and I am currently annotating each ThingType with the number of Things with different states, as below: def get_queryset(self) -> QuerySet: queryset = ThingType.objects.all().annotate( count_good=Count( "thing", filter=Q( thing__state="good", ), ), ) .order_by("name") ) return queryset How would I extend this to include the count of Users that have set their thing_prefer to a Thing which references ThingType? (Or, for each ThingType returned, how would I annotate with the number of Users that have set their thing_prefer to a Thing that references the ThingType being investigated?) Thank you! -
Django & docker-compose - psycopg2 connection error
I am trying to run a simple Django app with PostgreSQL using docker-compose. The PostgreSQL container runs fine and is accessible but I am unable to reach it from inside the Django container using python. Here is my docker-compose.yaml: version: "3" services: db: image: "postgres" restart: always environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} volumes: - pgdata:/var/lib/postgresql/data django: build: ./qc_django ports: - "8080:8080" environment: - DB_NAME=django - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_HOST=db - DB_PORT=5432 - DEBUG=True depends_on: - db volumes: pgdata: Here are the database settings inside of the Django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } The error it spits out after a minute or so: django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "db" (172.21.0.2) and accepting TCP/IP connections on port 5432? -
Django: redirection if user is logged
Although there are many questions of this type, the answers that the collaborators have given do not work for me in any case. I need to prevent logged in users from accessing the login page. urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), views.py def user_login(request): if request.user.is_authenticated: return HttpResponseRedirect('dashboard') settings.py LOGIN_REDIRECT_URL = 'dashboard' But it does not work. Please, help. Thanks!! -
How to use sudo command via PuTTY
I'm trying to depoly django app on a hosted server. My local PC has Windows as OS so I'm using PuTTY to connect to the server (which has GNU/Linux). Once I connect to the server, I install Python and setup vierualenv, but when i try to install the postgresql I receive the error ModuleNotFoundError: No module named '_ctypes' I know that it's quite a common problem mentioned in numerous threads (for example, Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing) which can be solved by intalling "libffi-dev" by the command sudo apt-get install libffi-dev However, when I try to use the sudo command I receive the following error: -bash: sudo: command not found I tried to find a solution, but my experience with Linux is rather limited. From what I found, it may be caused by me not being logged as a superuser, but I could not find clear instruction how to enable it when I access Linux server via SSH (PuTTY) from Windows. Does anyone know a way how could access sudo command or how to install "libffi-dev" in a way which does not require sudo commands?Thank you in advance for any help. -
İn Django, how to make a div visible after only when scrolled down to some px
I am new to Django. I am building a website which has a side-bar but I want it to be seen when user scrolled a bit. In my opinion, I can do it with writing some css codes such as an "if statement on html code using "!important" " The main problem is to make it, I need something which will trigger the if statatement. How can I put down on codes the triggering part ? To be clearer, how can I write the code which says when scrollbar goes down 200px. As I said I am new to Django and also new to web development. I have not learned javascript or jquery yet.Can it be done without these ? Thank you. -
Not getting fields prefilled with previous values while editing a form in django
I have a form(EditProfileForm) which I created to edit the profile details. My issue is that whenever I go to the EditProfileForm page in the browser the fields are not filled with previous values which I gave while making the profile for the first time, I have to fill the entire form however if I make some change in the value then the change is being made successfully. my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pic.jpg', upload_to='profile_pictures') location = models.CharField(max_length=100, blank=True, null=True) bio = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.user.username my EditProfileForm in forms.py: class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['image', 'location', 'bio'] my two views regarding profile and edit profile: @login_required def profile_page(request): user = request.user posts = Post.objects.filter(author=user) posts_count = posts.count() profile = Profile.objects.get(user=user) return render(request, 'blog_app/profile.html', {'user': user, 'posts_count': posts_count, 'profile': profile}) def edit_profile(request, id): profile = Profile.objects.get(id=id) if request.method == 'GET': form = EditProfileForm(request.FILES, instance=profile) else: form = EditProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): # deleting old uploaded image. image_path = profile.image.path if os.path.exists(image_path): os.remove(image_path) # the `form.save` will also update the newest image & path. form.save() return redirect('profile') return render(request, 'blog_app/edit_profile.html', {'profile': profile, 'form': form}) my two urls … -
Why do I have a 'KeyError' error when using when using Django's coverage tool
Im developing a django API. Now im doing some tests on the endpoints and when i execute 'python manage.py test' everything goes well. But when i use the flag '--with-coverage' or 'coverage run --source='.' manage.py test app && coverage report' i get the error 'KeyError: 'BREAK_LOOP'. Someone can help me? -
django models distinct is still returning duplicates
Im stumped ... and its probably obvious but i cannot seem to get distinct to remove the duplicates here q = SubscriberPhoneNumber.objects.values_list('phone_number',flat=True).order_by('phone_number').distinct('phone_number') print(q) <QuerySet ['9711231234', '5095551212', '9994441212', '9994441212', '9711231234']> as you can see 9711231234 appears twice (as does 9994441212) (note these are not real phone numbers...) here is the model class SubscriberPhoneNumber(models.Model): subscriber = models.ForeignKey(SystemStatusSubscriber, on_delete=models.CASCADE) phone_number = EncryptedCharField(max_length=24, **null) country_code = models.CharField(max_length=8, default='+1') I feel like im losing my mind ... and dont understand why distinct is not eliminating the duplicates (I really want distinct on country_code and phone_number but just included phone_number to simplify the problem) (I also do not need values_list but thought that might help select only the columns i am interested in) (note that i can certainly cast the result to set to get unique values... but i feel like distinct is the right way to approach this, and cannot figure out how to make it work... ) -
Django Password Decrypt in PHP (with salt and cypher)
in Django we have a hashed password like "pbkdf2_sha256$150000$wRUxY0PmiVfeGva48bzZTtaCKG5QgYNzr8VRw/ezSwEQptgqg=" and a password cypher like "gAAAAABgXg4aYTztisoQEduXbaYX81hY_xEStrI2IHewIKcBxLWAtX8uY8SxzujRhm84LzgKzSJ6Zu5i8wKoL8mUvNvSmKGAQg==" and a salt like "-GcGi6r3TmMNz5cD8Cagpfli3Es-hz_s3hda5vr5G60=" in Python i decrypt password with Fernet Library like f = Fernet(salt) password = f.decrypt(bytes(password_cypher.encode())).decode() as anyone can see we just using cypher and salt. and question is how Decrypt like this method in php...? (Laravel & PHP) -
Django ORM date field wrong output
I want to select the objects that date field equal to the latest date in the model. So I pick the latest date by >>> latest_date = StockPrice.objects.latest('date').date >>> latest_date datetime.date(2021, 4, 9) but the latest date in my model is 2021-4-13. then I tried this >>> StockPrice.objects.filter(date=latest_date) <QuerySet []> I use latest_date just got, but nothing show after filtering Can't figure it out how does this happened. ./models.py class StockPrice(models.Model): date = models.DateField() symbol = models.IntegerField() open = models.FloatField() high = models.FloatField() low = models.FloatField() close = models.FloatField() shares = models.IntegerField() volume = models.IntegerField() pe = models.FloatField() pb = models.FloatField() yield_rate = models.FloatField() *** [click to data inserted to the model][1] [1]: https://raw.githubusercontent.com/ycy-tw/python-django-stock/main/demodata/stockprice.csv -
Django NameError:name 'request' is not defined [closed]
I am getting this error on writing the below code: return render(request, 'index.html') This is the error: return render(request, 'index.html') NameError: name 'request' is not defined PS: I was not able to find a solution on this that's why I am posting this question -
Create a custom function as a filter in proxy model, django admin
I need help to convert CashInhandAdmin->expense as a filter (high and low), have tried below filter but failed because proxy model is inherited from user_profile model but want to filter expense sum that is different model. Filter class ExpenseFilter(admin.SimpleListFilter): title = 'Expense' parameter_name = 'Expense' def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. """ return (("low", "Filter by low amount"), ("high", "Filter by high amount")) def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ if self.value() == "low_price": return queryset.order_by("expense") elif self.value() == "high_price": return queryset.order_by("-expense") else: return queryset.all() Model class CashInhand(user_profile): class Meta: proxy = True verbose_name = "Cash In Hand" verbose_name_plural = "Cash In Hand" Admin class CashInhandAdmin(admin.ModelAdmin, admin.SimpleListFilter): def get_queryset(self, request): print(request.GET.get("Expense")) qs = super(CashInhandAdmin, self).get_queryset(request) return qs.filter(employee__isnull=False).distinct("employee_id").order_by("employee_id") def has_delete_permission(self, request, obj=None): return False def expense(obj): exp = models.Expense.objects.filter(created_by_id=obj.employee, status='1').annotate( as_float=Cast('amount', FloatField())).aggregate(Sum("as_float")) if exp["as_float__sum"]: return int(math.ceil(exp["as_float__sum"])) else: return str(0) list_display = (expense,) list_filter = … -
getting number of days between twoo dates
I don't figure out how to get the number of days betwen twoo dates: this is the models I have : class Reservation(models.Model): """A typical class defining a reservation model.""" # Fields id_reservation = models.BigAutoField(primary_key=True) start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) client_id = models.ForeignKey(Client, on_delete=models.CASCADE) chambre_id = models.ForeignKey(Chamber, on_delete=models.CASCADE) # Metadata class Meta: ordering = ['-end_date'] # Methods def get_absolute_url(self): """Returns the url to access a particular instance of MyModelName.""" return reverse('model-detail-view', args=[str(self.id_reservation)]) def __str__(self): return self.id_reservation and try to calculate the days between the end_date and the start_date in my generic view: class ReservationsListView(generic.ListView): """ReservationsListView: produce a list of all Reservations """ model = Reservation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['periode'] = Reservation.end_date-Reservation.start_date return context can please help doing this. -
Django-tables2 URL Link from multiple foreign key not working
I'm working on a site using Django and need help with data flow and accessing the foreign key data. models.py class Boards(models.Model): board_no = models.CharField('Board No', max_length=10, unique=True) board_name = models.CharField('Board Name', max_length=100) class BoardLocations(models.Model): board = models.ForeignKey(Boards, on_delete=models.CASCADE, related_name='board') location_code = models.CharField('Location Code', max_length=10, null=True) class BoardContacts(models.Model): board_location = models.ForeignKey(BoardLocations, on_delete=models.CASCADE) contact_first_name = models.CharField('Contact First Name', max_length=100, null=True) contact_last_name = models.CharField('Contact Last Name', max_length=100, null=True) The BoardContacts are tied to a BoardLocation which all come from a Board. I'm displaying the list of BoardContacts properly through a django-tables2 as follows: List of Contacts The URL shows: http://127.0.0.1:8000/adm/boards/view_data_contact_list/6/ where 6 is Board.id. All fine. The Contact First Name link is defined as: tables.py class BoardContactsTableView(tables.Table): selection = tables.CheckBoxColumn(accessor='id') contact_first_name = tables.LinkColumn('view_board_contact', args=[A('id')], attrs=TABLE_VIEW_ATTRS) contact_last_name = tables.LinkColumn('view_board_contact', args=[A('id')], attrs=TABLE_VIEW_ATTRS) class Meta: model = BoardContacts template_name = TABLE_TEMPLATE_NAME attrs = TABLE_ATTRIBUTES ordering = ['contact_last_name'] fields = ('selection', 'contact_first_name', 'contact_last_name', 'contact_type', 'access_type', 'last_login', 'create_date') When I select Contact First Name or Last Name, the URL changes to: http://127.0.0.1:8000/adm/boards/view_data_contact/29/ because source indicates: <td ><a class="text-decoration-none fw-bold" style="color:gray" href="/adm/boards/view_data_contact/29/">Robert</a></td> But 29 is the BoardContacts.id. I need to maintain the Board.id of 6 within the URL so I can go back to the list of contacts … -
Which Framework django or react.js? [closed]
I am developing a web app (for admin & restaurants ) regarding food delivery (cloud kitchen) and an online grocery store. which framework should I use am confused, I have 2 options django and react.js .. can anyone guide me which is better and reliable.... thanks -
Django Concatenate charfields and parse it as Datetime
how are you? I have a model that has two fields named start_time and end_time, both are CharField, and this model has a relation to another model that has a field named date it is a DateField. It looks like this class A(models.Model): date = models.DateField() class B(models.Model): relation = models.ForeignKey(A) start_time = models.CharField() end_time = models.CharField() I need to query model B, using datetime values for example: B.models.filter(reconstructed_datetime="2021-04-19 15:02:00") where reconstructed_datetime is date (from model A) concatenated with start_time or end_time (from model B) I tryed something like this: B.objects.annotate( reconstructed_start=Concat( F('relation__date'), Value(' '), F('start_date'), output_field=CharField() ) ).annotate( reconstructed_start_datetime=Cast("reconstructed_start", DateTimeField()), ) But then I tried to filter .filter(reconstructed_start_datetime="2021-04-19 15:02:00") and it does not return my database record here "hora_inicio" is start_time. I suppose that use Cast does not work So, do you know a way to concatenate those model values and then make a query as datetime field? -
Django API sudden degrade in performance
I am working on a project where all REST API are implemented in django and UI is taken care by Vue.js. Since last week our dev and qa environments are facing long TTFB response time even for simple select queries to Postgres Database. To investigate this I added some logs to see how much time it takes to execute the query. Here is the code below import datetime from django.core.signals import request_started, request_finished from django.conf import settings class TenantListViewSet(APIView): """ API endpoint that returns all tenants present in member_master table in panto schema. """ @ldap_login_required @method_decorator(login_required) def get(self, request): settings.get_start_time = datetime.datetime.now() print(f'Total time from started to get begin {settings.get_start_time-settings.request_start_time}') errors = list() messages = list() try: settings.db_query_start_time = datetime.datetime.now() tenant_list_objects = list(MemberMaster.objects.all()) print(MemberMaster.objects.all().explain(verbose=True, analyze=True)) settings.db_query_end_time = datetime.datetime.now() print(f'Total time taken to execute DB query {settings.db_query_end_time-settings.db_query_start_time}') db_start = datetime.datetime.now() serializer = MemberMasterSerializer(tenant_list_objects, many=True) db_end = datetime.datetime.now() print(f'Total time taken to serialize data {db_end-db_start}') tenant_list = serializer.data response = result_service("tenant_list", tenant_list, errors, messages) settings.get_end_time = datetime.datetime.now() print(f'Total time taken to finish get call {settings.get_end_time-settings.get_start_time}') return JsonResponse(response.result["result_data"], status=response.result["status_code"]) except Exception as e: if isinstance(e, dict) and 'messages' in e: errors.extend(e.messages) else: errors.extend(e.args) response = result_service("tenant_list", [], errors, messages) return JsonResponse(response.result['result_data'], status=400) def … -
Add a random avatar to new user in Django UserCreationForm
I am trying to choose a random avatar from the database and add it to a user's account when they click on the 'Sign up' button on the registration page. I tried implementing this in my view but I keep getting the following error. > if file and not file._committed: AttributeError: 'UserAvatar' object > has no attribute '_committed' views.py def signup(request): ... user = form.save(commit=False) ... # query the avatars in the database and choose a random one for user avatar = UserAvatar.objects.all() random_avatar = random.choice(avatar) user.avatar = random_avatar ... user.save() ... form = CustomUserCreationForm() return render(request, 'signup.html', { "title": _('Sign up'), 'form': form, }) -
When running migrations on a new MSSQL server, I get the following error
Applying account.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ __init__.py", line 419, in execute_from_command_line utility.execute() File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ __init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ base.py", line 398, in execute output = self.handle(*args, **options) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/migrations/ex ecutor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i nitial=fake_initial) File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/migrations/ex ecutor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_ initial) File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/migrations/ex ecutor.py", line 230, in apply_migration migration_recorded = True File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/backends/base /schema.py", line 118, in __exit__ self.execute(sql) File "/usr/local/lib/python3.8/dist-packages/sql_server/pyodbc/schema.py", lin e 871, in execute sql = str(sql) File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/backends/ddl_ references.py", line 201, in __str__ return self.template % self.parts KeyError: 'include' This code has a problem with the part of my website that handles Online Users, I don't know exactly what is causing the problem, but if I try to run migrations a second time it says that a db named account_users already exists. If you need any other info please ask. -
Django - 403 Forbidden on media files
When using apache2 and django, I am unable to access media files, as I am getting 403 forbidden when trying to load them. I am fairly certain I have set up my config correctly (see below) but im not totally sure. Static files are loading totally fine. I have looked at the other similar posts on stack overflow, which showed to include the following: <Directory /var/www/website/media/> Order deny,allow Allow from all </Directory> The entire contents of my config is below. <VirtualHost *:443> ServerName www.websiteurl.uk ServerAlias www.websiteurl.uk SSLEngine on SSLCertificateFile /etc/ssl/crt/websiteurl.uk_ssl_certificate.cer SSLCertificateKeyFile /etc/ssl/crt/_.websiteurl.uk_private_key.key SSLCertificateChainFile /etc/ssl/crt/_.websiteurl.uk_ssl_certificate_INTERMEDIATE.cer DocumentRoot /var/www/ WSGIScriptAlias / /var/www/website/wsgi.py <Directory /var/www/website/> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media /var/wwww/website/media/ Alias /static /var/www/website/static/ <Directory /var/www/website/static> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /var/www/website/media/> Order deny,allow Allow from all </Directory> <Location /server-status> Require ip 84.167.178.229 SetHandler server-status </Location> </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet <VirtualHost *:80> ServerName www.websiteurl.uk ServerAlias www.websiteurl.uk Redirect permanent / https://websiteurl.uk/ </VirtualHost> -
Is there methods of having inline form and related form in the same update page
The case is, there is a company and its employees. On the company page, I should be able to add employees to the company. Additionally be able to update company models.py class Company(models.Model): name = models.CharField(max_length=100, null=True, blank=True) link = models.URLField(null=True, blank=True) description = models.TextField(null=True, blank=True) class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) address = models.TextField() company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.first_name forms.py class CompanyForm(forms.ModelForm): class Meta: model = Company fields = '__all__' EmployeeFormSet = inlineformset_factory(Company, Employee, fields=('first_name', 'last_name',), extra=1) views.py def inlineformset_view(request, company_id): try: company = Company.objects.get(pk=company_id) except Company.DoesNotExist: return render(request, 'formset_view.html', {}) context = { 'company': company } if request.method == 'POST': formset = EmployeeFormSet(request.POST, request.FILES, instance=company) company_form = CompanyForm(request.POST, request.FILES) if formset.is_valid() or company.is_valid(): cd = formset.cleaned_data print(cd) company.save() formset.save() company = Company.objects.get(pk=company_id) context = { 'company': company, 'formset': formset, 'company_form': company_form } else: formset = EmployeeFormSet(instance=company) company_form = CompanyForm(instance=company) context = { 'formset': formset, 'company_form': company_form } return render(request, 'inlineformset_view.html', context) The problem I am having I am not able to post the data for the employee inline form and company form. I am having the same empty models when the forms is posted. -
Video and audio calling app using Python webrtc
I am doing an internship where they have asked me to build a video and audio calling feature for their chatting app using python. Can anyone guide me how can I build this feature using python ? -
Add a message on all views in Django
I'd like to use the Django messages functionality to show a message to users visiting our website. The idea is to show it on the first page they view and then not show it again for the rest of the user session. I'm thinking it will work a bit like this: if request.session.get('show_welcome_message', True): messages.info(request, 'Welcome to our site!') request.session['show_welcome_message'] = False My question is, where's the best place to add this to have it show on all website pages? And, is there a better way to do something like this that makes use of Django's native messaging to display a message to users that they don't see again on the same session if they close the message? -
How to change graph in django template on form submit
I have a django template as follows <div class="container"> <section class="main"> <h1>Check the chart below</h1> <form> {% csrf_token %} <div class="switch"> <input id="chk" type="checkbox" class="switch-input" /> <label for="chk" class="switch-label">Switch</label> </div> </form> <div class="main_graph"> {% if main_graph %} {{ main_graph.0|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> </section> </div> <script type="text/javascript"> $(document).on('click', '#chk', function (e) { $.ajax({ type: 'POST', url: '/home', data: { chk: $('#chk').prop('checked'), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { if (data.success == true) { // if true (1) location.reload(true); } } }); }) </script> This is my views def home(request): const_list = pd.read_csv('./const.csv').Const.unique() part_list = pd.read_csv('./part_list.csv').abbr.unique() all_list = pd.read_csv('./all_list.csv').All.unique() chked=request.POST.get('chk', '') if chked == 'true': print(chked) my_graph = main_graph(all_list, len(const_list)) else: print('this is a test') my_graph = main_graph(part_list, len(const_list)) context={'main_graph':my_graph, 'const': const_list} return render(request, 'home.html', context) The main_graph function takes a list and an int value as parameters for creating a bar graph with plotly. The list will be for populating the y-axis and the int value is a range for the x-axis. The graph is created properly. Now I want to change the graph on the click of a button. For this purpose, I created a toggle switch which when clicked will … -
Is Django a good choice for web-dashboard that works with data from IoT devices and sensor devices?
I am a business owner and I would like to develop a web based service that uses the data from a number of sensors and IoT devices and analyze the data with scientific and mathematical methods. These data and their interpretations would be then be represented as reports, analytical summaries etc. My clients can login to the web dashboard and can see the reports and analytics. I would like to use to the flexibility and power of Python for data analytics, machine learning etc. My choice is Django for this purpose. I would like to know if I am making the right choice based on the following outcomes I need to serve more than 10k customers on a monthly basis I may have to scale up the resources and programming scopes significantly gradually I may have to opt for SPA(single page applications), rest APIs for additional functionalities and performance I may have to control the IoT devices according through the website Looking forward for your valuable insights Regards