Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic table in django from user
How to create dynamic models in django rest framework? Is there any chance to create dynamic models with APIs Any examples please send me thanks in advance.. Requirement is need create table name and fields in frontend we are getting the data and store in to the db create db structure get the table name and fields create table in backend & store to 4)this code don't update or add into the models 5)store the data into the tables 4)get the data into the tables using orm or any raw queries I tried everything but not working -
What could be causing the Django session to not properly store previous values when handling requests from Angular for view counts on blog posts?
Django session may not be getting previous store value by angular GET method. i try to doing view count on blog post. but one user give only one view count. in view.py file def get(self, request, id=None): obj = Model.objects.get(id=id) serializer = self.serializer_class(obj) session = SessionStore(request.session.session_key) viewed_objs = session.get('viewed_objs', []) if id not in viewed_objs: obj.view_count = obj.view_count + 1 obj.save() viewed_objs.append(id) session['viewed_objs'] = viewed_objs session.save() return Response(serializer.data, status=status.HTTP_200_OK) else: serialized_data = serializer.data serialized_data['message'] = 'View count not updated. Object already viewed by this user.' return Response(serialized_data, status=status.HTTP_200_OK) this code work properly if i send request by postman. when i same requested by angular that time everytime add viewcount of same user. problem is angular send request to django backend that time django session not work properly. i added in settings.py file CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200' ] CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', ] i do all of them still i am not gating previous store value in angular request -
My Django website is unreachable and i don't see logs of Django in Docker
I'm working on Django website, and while deploying it on Linux Ubuntu server i've faced some problems: I made a dockerfile (and docker compose file), pushed it into Docker Hub, pulled it from my Linux server, launched this docker image via docker-compose, and then i only see logs of PostgreSQL (i don't even see any errors from Django side). I also try to reach this website from other computers, but it gives me "ERR_CONNECTION_TIMED_OUT" error. here's my Dockerfile code: FROM python:3.10 ENV PYTHONUNBUFFERED 0 WORKDIR /code COPY ./requirements.txt . RUN pip install --upgrade pip && pip install --upgrade setuptools wheel RUN pip install -r requirements.txt COPY . . EXPOSE 8000 here's my docker-compose code: version: '3.9' services: db: image: postgres volumes: - type: volume source: pg_data target: /var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 5432:5432 django: image: django-docker:0.0.1 build: . command: sh -c "gunicorn --bind 0.0.0.0:8000 outtask.wsgi:application" # sh -c "python3 -u outtask/manage.py runserver 0.0.0.0:8000" volumes: - type: bind source: . target: /outtask - type: volume source: static_data target: /outtask/static ports: - "8000:8000" environment: - DJANGO_SETTINGS_MODULE=outtask.settings depends_on: - db volumes: pg_data: static_data: Code of settings.py you can look up with this link (don't look at strange placement … -
How can I remove background color from crispy-forms in django
I'm using using crispy forms in my django project with bootstrap5 template pack. And want to change the graphical button behavior and remove abckground color. CRISPY_TEMPLATE_PACK = "bootstrap5" CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" I want to create a submit button. This is automatic adding btn-primary class. Can I somehow disable this behavior as my current buttons should not have any background color ? In the second button I removed the background color by removing btn-primary class. But overwriting with css_class does not help. btn and btn-primary is added automatically. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = "POST" self.helper.add_input(Submit("submit", "Abschicken", css_class="btn btn-outline-theme btn-lg d-block w-100 fw-500 mb-3")) -
Custom Authentication django
I have an app called cAdmin which for company users administration. And have Django superuser for create this company admins , which is stored in User Model as well. I have a custom backend called MyCustomAuthBackend and it only check CompanyAdmin model credentials . But the problems is whenever i try to login using User model credentials also allows . The reason that i foun is if the first backend fails it jumps over to next backend which is ModelBackend. How to stop when the first backend fails to jump to second back end in this specific app cAdmin. from django.contrib.auth.backends import BaseBackend from .models import CompanyAdmin from django.contrib.auth.hashers import make_password,check_password class MyCustomAuthBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = CompanyAdmin.objects.get(adminName=username) print(user.adminPassword," ",make_password(password)) if check_password(password, user.adminPassword): print("worked password", user.adminPassword, password) #user.is_authenticated = True print(user,"printer duser") return user except CompanyAdmin.DoesNotExist: return None return None and the view is given below, from django.shortcuts import render,HttpResponse from django.views.decorators.cache import cache_control from User.models import TicketDetails,Tickets,Category from cAdmin.decorators import signin_required #from cAdmin.backends import authenticate from django.contrib.auth import authenticate,login,logout @cache_control(no_cache=True, must_revalidate=True, no_store=True) def Login(request,id=None): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] print("login view password") user=authenticate(request,username=username,password=password) print(user) if user: print(user) login(request,user) context … -
Django ApiTestCase Leak
I am testing Api Endpoints in Django. We have code from django.core.management import call_command from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from account.models import Member, Organization, PhoneNumber from authorization.models import AuthSMSCode class SetUp(APITestCase): @classmethod def setUpTestData(cls): # super().setUpClass() cls.username = 'sudo' cls.member = Member.objects.create_user(first_name='DefaultUser', email='default@gmail.com') cls.organization = Organization.objects.create(name="Google", legal_address='1040 Brussels') cls.member.organizations.add(cls.organization) cls.member.save() cls.organization.save() cls.phone_number = PhoneNumber.objects.create(number='9999999999', member=cls.member) code = 12345 cls.smscode = AuthSMSCode.objects.create(value=code, phone_number=cls.phone_number) Token.objects.create(user=cls.member) call_command('create_default_roles') class ApiTestCaseGroups(SetUp, APITestCase): def test_authorized(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.member.auth_token.key) url = ... response = self.client.get(url, format='json', REMOTE_USER=self.username) expected_output = ... response_result = response.json() self.maxDiff = None self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response_result, expected_output) class ApiTestCaseMembers(SetUp, APITestCase): def test_authorized(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.member.auth_token.key) url = ..... response = self.client.get(url, format='json', REMOTE_USER=self.username) expected_output = ... response_result = response.json() self.maxDiff = None self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response_result, expected_output) If we run ApiTestCaseGroups and ApitTestCaseMembers separately as classes, they work fine. But when I run the whole file as a test it fails on test №2 ApiTestCaseMembers because object is empty (it returnrs code 200, so we authentificate but there is no object inside response_result). I saw some similar questions around, but those solutions did not work here. In what direction should we go to solve the issue? -
How do I integrate Next.js template with my existing Django Application?
I have been working on my Django app. Currently it has a simple HTML hero page for the front end. I have purchased this https://tailwindui.com/templates/salient template from Tailwind. I would like to integrate this into my existing django project. I only intend to use it as a marketing site. Can someone guide me as to what I need to do? Cheers -
Django model relationship for different queries
Is there a better way to this? and is it a correct way to do? I want to be able to tie the user field to the Django session's user ID. Be able to get all events for the user who is logged in. Be able to get all orders for the event user selected selected. As the site owner/admin be able run queries for all user and their events and orders. class User(models.Model): user_name = models.CharField(max_length=25) user_age = models.PositiveSmallIntegerField() class Event(models.Model): user_name = models.ForeignKey(User, to_field='user_name', on_delete=models.CASCADE) event_name = models.CharField(max_length=100) class Order(models.Model): event_name = models.ForeignKey(Event, to_field='event_name', on_delete=models.CASCADE) order_number = models.BigIntegerField() order_type = models.CharField(max_length=25) -
Create Document field inside Django elastic search for calculate properties
I have three models inside my Django model class A(BaseModel): b = models.ForeignKey(B, null=True, blank=True, on_delete=models.SET_NULL) c = models.ForeignKey(C, null=True, blank=True, on_delete=models.SET_NULL) @property def tags(self): tags = [] if self.c: tags.extend(self.c.tags.all()) if self.document: tags.extend(self.b.tags.all()) return tags class B(BaseModel): tags = GenericRelation('tags.Tag') class Tag(BaseModel): definition = models.ForeignKey(TagDefinition, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') task_id = models.CharField(max_length=150, null=True, blank=False) task_exception = models.TextField(null=True, blank=True) objects = TagManager() In Elastic search I would like to create Document based on model A All other fields are working well, but calculated field tags are not. @registry.register_document class AkDocument(Document): tags = fields.ListField(fields.ObjectField(properties={ 'definition': fields.ObjectField(properties={ 'friendly_name': fields.KeywordField(), 'code': fields.KeywordField(), 'variant': fields.KeywordField(), }), 'task_id': fields.KeywordField(), 'task_exception': fields.KeywordField(), })) This will only return a {} even though tags are inside. So if I check: >>> ADocument().get_queryset()[0].tags [<Tag: Tag object (1502)>] >>> ADocument().search().execute()[0].tags {} How to construct this field so that it will return correct results? -
Is there a way to make my authentication accept both email or username values for user log-in
I am working on a django authentication project, where I want to authenticate using both email and username for authentication. The model is class LinksUser(AbstractBaseUser, PermissionsMixin): objects = LinksUserManager() full_name = models.CharField(max_length=200, blank=False) email = models.EmailField(_("email address"), unique=True) username = models.CharField(_("username"), unique=True, max_length=20) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = "username" EMAIL_FIELD = "email" REQUIRED_FIELDS = ['email'] def __str__(self): return self.email In addition I have created a manager file which is class LinksUserManager(BaseUserManager): """ Custom user-model manager where the email and username are identifiers for authentication """ def create_user(self, email, username, password, **extra_fields): if not username: raise ValueError('Username must be set') if not email: raise ValueError('Email must be set') email = self.normalize_email(email) user = self.model(username=username, email=email) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(username, email, password, **extra_fields)``` Finally, I wrote an authentication code of from .models import LinksUser class LinkUserBackend(object): """ Model backend that attempts to allow a user to log in with either the username or the email address """ def authenticate(self, request, username=None, password=None): try: user = LinksUser.objects.get(email=username) except … -
No module named 'pymysql'
I tried to access to django by using mysql. my manage.py file below seems like accessable to 'pymysql. and I set like settings below. manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import pymysql pymysql.install_as_MySQLdb() - settings.py 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabase', 'USER': 'user02', 'PASSWORD': '12345678', 'HOST': 'localhost', 'PORT': '3306', } and also installed successfully for [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/xL4nb.png How can I work arrange the problem ' import pymysql ModuleNotFoundError: No module named 'pymysql' in my project? I tried with this document but couldn't.. https://stackoverflow.com/questions/33446347/no-module-named-pymysql -
No Module named '_cffi_backend' while using cryptography
I'm using the "cryptography" library in my Django web app and facing 'Module Not Found Error: No Module named '_cffi_backend' in my server log. I've upgraded my Python version from Python3.6 to Python3.9 and using a virtual environment. I've uninstalled all related libraries (i.e. cryptography, cffi, paramiko and etc) and reinstalled them again but still facing the same error. This error is happening after the below line in the terminal. from cryptography.hazmat.bindings._padding import lib Below are my environment details RHEL7.9, Python3.9, Django-3.11, cryptography-3.3.1, cffi-1.15.1 -
Having problems updating the database of a Django project after HTML changes
I am trying to write a Django app that has a counter that increases on a button press, and decreases on another. I want this to save to the database (ideally) on each change. I have been able to update the HTML file from a separate JavaScript file by calling a js function via onclick and getting the data via JSON.parse, and changing the number with counter.innerHTML = new_number. However, I'm stumped on how to proceed. From what I've found Ajax seems to be my only option, but I am not sure how to get started with integrating it into my code. Below is a part of my html file and my JavaScript file. Any help would be fantastic Hunt.html <div class="column"> <div class="card" style="width: auto;border-style:solid; border-color:black; padding: 5px; background-color:rgb(50, 50, 50);"> <div class="card-body" style="color:rgb(172,238,239); background-color:rgb(50, 50, 50); "> <h5 id = "Encounters" class="card-title" style="font-size: 36px;">Encounters: {{currentHunt.count}}</h5> </div> <button onclick = "incrementCounter()" class="button" id="my_button">+</button> <button class="button1">-</button> </div> </div> main.js var count = JSON.parse(document.getElementById('count').textContent); var increment = JSON.parse(document.getElementById('increment').textContent); function incrementCounter() { var counter = document.getElementById('Encounters'); count += increment; var encounters = "Encounters: "; counter.innerHTML = encounters.concat(count); } -
why form data is not passing to views.py?
html form **<form method="POST" action="/thanks"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="Email@something.com"> </div> <div class="form-group"> <label for="phone">Phone</label> <input type="number" class="form-control" id="phone" name="phone" placeholder="number"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">What type of blog you need?</label> <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>** in views.py it prints nothing with if condition. Without if-condition, it prints none **if request.method == 'POST': name = request.POST.get('name') print(name)** -
Deploy a Django + sqlServer project using Apache
¿How can i deploy a Django project that uses sqlServer in apache? i created a project in Django and i want to put it in a azure virtual machine and deploy it with apache, but i have some issues because sqlServer isn´t supported for this framework, i have a database adapter like django-pyodbc, it works in my local but when i try to run it in a virtual machine than have Apache I get some errors , so ¿What is the best way to do this? here is what the apache error log shows : mod_wsgi (pid=41732): Failed to exec Python script file '/var/www/html/Agroweb/agroweb/wsgi.py'. (pid=41732): Exception occurred processing WSGI script '/var/www/html/Agroweb/agroweb/wsgi.py'. Traceback (most recent call last): File "/var/www/html/Agroweb/agroweb/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi caught SIGTERM, shutting down Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/2.7 configured -- resuming normal operations Command line: '/usr/sbin/apache2' -
How to use logging with Django?
I try to log variables to the console, but it doesn't show anything. Each competitor is assigned to a group via Foreign Key. I want to log in the list of "flname" within each group. For example, one of the Foreign key is "blue". How do I log in all of the "flname" within that group? Any suggestion? Thanks, admin.py from django.contrib import admin from .models import Group, Competitors import logging class MemberAdmin(admin.ModelAdmin): list_display = ("flname", "Weight", "rank", "Group_FK", "point") def __str__(self): return self.Group_FK admin.site.unregister(Competitors) admin.site.register(Competitors, MemberAdmin) class GroupCompetitorInline(admin.TabularInline): model = Competitors readonly_fields = ('flname', 'Weight', 'rank',) extra = 0 class GroupAdmin(admin.ModelAdmin): inlines = [GroupCompetitorInline] admin.site.register(Group, GroupAdmin) def logging(request): flnames = Competitors.objects.filter(Group_FK=Group.objects.get(pk='___').values_list('flname', flat=True)) logging.warning('flnames') settings.py FORMATTERS = ( { "verbose": { "format": "{levelname} {asctime:s} {threadName} {thread:d} {module} {filename} {lineno:d} {name} {funcName} {process:d} {message}", "style": "{", }, "simple": { "format": "{levelname} {asctime:s} {module} {filename} {lineno:d} {funcName} {message}", "style": "{", }, }, ) HANDLERS = { "console_handler": { "class": "logging.StreamHandler", "formatter": "simple", }, "my_handler": { "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/blogthedata.log", "mode": "a", "encoding": "utf-8", "formatter": "simple", "backupCount": 5, "maxBytes": 1024 * 1024 * 5, # 5 MB }, "my_handler_detailed": { "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/blogthedata_detailed.log", "mode": "a", "formatter": "verbose", "backupCount": 5, "maxBytes": 1024 * … -
In which format should I send the date data?
So I have a Django Flutter setup where I run an app that gets data from the a rest api server on my pc. I created a serilizer for creating users in Django, here is the code: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['first_name', 'last_name', 'date_of_birth', 'email', 'password', 'gender', 'date_of_contamination', 'cluster_id_id'] And knowing that this is my user model: class User(models.Model): user_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() email = models.EmailField(max_length=254, unique=True) password = models.CharField(max_length=50) cronic_disease_1 = models.CharField(max_length=50, null=True) cronic_disease_2 = models.CharField(max_length=50, null=True) cronic_disease_3 = models.CharField(max_length=50, null=True) cronic_disease_4 = models.CharField(max_length=50, null=True) cronic_disease_5 = models.CharField(max_length=50, null=True) gender = models.CharField(max_length=50) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) cluster_id = models.ForeignKey('Cluster', on_delete=models.CASCADE) if_transmit = models.BooleanField(null=True) date_of_contamination = models.DateField(null=True) recommandation = models.FloatField(null=True) online = models.BooleanField(null=True) class Meta: constraints = [ models.CheckConstraint(check=models.Q(date_of_birth__lte=datetime.date.today()), name='no_future_date_of_birth') ] After creating a post request api url that works (tested it with Postman) I tried to create a post request to send data from Flutter, here is my post request method: static Future<bool> postRegisterUser({ required String email, required String password, required String firstName, required String lastName, required DateTime dateOfBirth, required Gender gender, DateTime? dateOfContamination, }) async { Map<String, dynamic> data = { 'first_name': firstName, … -
What is the best way to filter and sort data in react and DRF
I have a back-end built using Django Rest Framework and front-end served using React. I'm having a Filter component and Sort By component. I receive the products data as a json from back-end. I want to be able to filter by few fields such as category, brand, price etc and sort based on fields as well like ascending category, descending price etc. Basically i'd want my url to look like this {{baseUrl}}/products?category=a&category=b&brand=c&sort=category_desc My question is What is the best way to filter data i.e should i send data to back-end to filter using django-filters or filter using a javascript array.filter() ? Should i sort using django-filter's OrderFilter or custom javascript's array.sort() How to synchronise the query params in front-end with both filters and sortby conditions. I'm new to this, so if there is any blog post or document i can go through, that would be really helpful too along with your inputs. Thanks in advance! -
django queryset .first() not rendering on html
I am only learning django so any guide would be much appreciated. I am creating an app where authenticated users can like other posts. On one of the pages, I would like to render and show the post with most likes. Please see my code below: models.py: class Enter(models.Model): title = models.CharField( max_length=200, unique=True, null=False, blank=False) slug = models.SlugField( max_length=200, unique=True, null=False, blank=False) competitor = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_enter') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', null=False, blank=False) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='post_likes', blank=True) class Meta: ordering = ['-created_on'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Enter, self).save(*args, **kwargs) def __str__(self): return self.title def number_of_likes(self): return self.likes.count() views.py: class CurrentOrderList(generic.ListView): model = Enter queryset = Enter.objects.filter(status=1).order_by('likes')[0] template_name = 'competition.html' competition.html: <div class="container-fluid"> {% for entry in enter_list %} <div class="row justify-content-center mt-4"> <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <div> <img class="card-img-top" src=" {{ entry.featured_image.url }}"> <div> <p class="competitor text-muted">By: {{ entry.competitor }}</p> </div> </div> <h2 class="card-title">{{ entry.title }}</h2> <hr /> <p class="card-text text-muted h6">{{ entry.created_on}} <i class="far fa-heart"></i> {{ entry.number_of_likes }}</p> </div> </div> </div> </div> {% endfor %} </div> If I remove [0] (or .first()) from the views.py list does get … -
Django Docstring implementation
I have a Django project, I'm putting comments and google-style docstrings for better understanding. My question is, Is it okay to mention other methods or classes in a docstring within a function or a class-based view? That's to say, something like this: class SearchFoodView(ListView): """Display a list of foods based on search query. Returns: ListView: An instance of ListView with the paginated search results. Notes: Due to `show_foods()`, `show_by_category()`, and `SearchFoodView` using the same template (`products-list.html`) to display the list, the context variable name `page_obj` is utilized for consistency across the views. """ model = Food template_name = 'foods/food_search.html' context_object_name = 'page_obj' paginate_by = 5 Specifically in the 'Notes' section, I'm explaining the reason behind naming the context_object_name as 'page_obj' to provide clarification. Is this a good or bad practice?, or should I consider mentioning it as a comment within the view instead? or somewhere else? I really need to clarify this. -
Make a <td> clickable and get the value in javascript
I'm trying to make a <td> clickable and get the value to javascript. I've got multiple <td> generated by my Django backend, one example: <td class="hostname"><a href="javascript:void(0)" onclick="clientInfo();">Client001</a></td> When I click it triggers the JavaScript function clientInfo() { var $row = $(this).closest("tr"); var $hostname = $row.find("hostname").text(); alert($hostname); } but the $hostname stays empty. The JS works with a button in a <td> the only thing that differs is the JS call with onClick(). -
Two backends, one DB - what's the best way to integrate data with Django?
Currently I'm working in a project that will add a functionality to a legacy application. For a number of reasons that are completely out of my control, this functionality will resides in a different backend. Not only that, each backend is actually in a different programming language (legacy is ruby, using Rails, new is Python, using Django), and different architectures (legacy is a monolithic app, django will provide a Rest API for a React frontend). So far, so good. I've already solved how to integrate user's sessions, and mapped each table as a django model using the lifesaver command python manage.py inspectdb > legacy_models.py. Now, I've got a bigger issue in my hands. Some of the old tables are not normalized, or there're missing fields which I'll need for the new application. I can't really mess with the old tables and create new fields, alter relationships or anything like that, since this legacy app is maintained by a separate corporation and we can't really depends on changes by their side, nor can we guarantee that changing the old tables won't mess with anything in this application. Therefore, I've took another route, and decided to create tables on Django that'll extend … -
How to make multiple APIs in parallel using Python Django?
Currently, I have 2 API enpoints. The first API enpoint takes in a file as input and performs some calculations that take up to 30 minutes. The second API endpoint is a healthcheck that returns the status of the first API. Possible healthchecks are 15% complete, 25% complete, 50% complete, 75% complete, 90% complete and 100% complete. Using Python I want to write code that calls the first API and then every 10 seconds calls the second API and returns the percentage complete. Then I would like to end the healthcheck calls once 100% has been completed. This is all code used in a Django project, where I would like the UI to get updated. Without the healthcheck, the code for that constant update looks something like: return render(request, 'processing.html', context). The code that I was thinking I could do this with would be something like the one below. That being said, I'm not sure if I'm handling the parallel asynchronous tasks correctly. I was thinking if multiprocessing or threading would be a good approach here but I'm not sure of the exact syntax. import requests import time async def first_api(body, api_url): async with aiohttp.ClientSession() as session: async with session.post(api_url, … -
Implementing medium editor in a django app
How can I use https://github.com/yabwe/medium-editor in my django app, I try creating a form with: <script src="https://cdn.jsdelivr.net/npm/medium-editor@latest/dist/js/medium-editor.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/medium-editor@latest/dist/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <script>var editor = new MediumEditor('.editable');</script> <div class="editable" contenteditable="true"></div> But nothing shows up I tried to enter it manually into my project but nothing works. -
Accessing Django admin site from browser says refused to connect
I run my app in vscode debug. The debug config is as follows: { "name": "bodhitree", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", "0.0.0.0:3000" ], "django": true, "justMyCode": false } This simply seem to run runserver 0.0.0.0:3000. Earlier I was able to access django admin site. But now I am not able access it. The browser says "refused to connect". I ensured that 'django.contrib.admin' is present in INSTALLED_APPS of settings.py. What could be the problem? There are four unapplied migrations. Can this be an issue? Cant I run django admin site without applying those migrations? Or am I missing something else?