Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sorting django-mptt record by complex string field as number
I'm using django-mptt to build a hierarchical structure. There is a field "task_id", that represents task id, in the following format "task.subtask.subtask", number of subtasks is infinite. To sort tasks, I'm using standard code order_insertion_by = ['task_id'] It works well, but the fields are sorted as string, i.e. 1.10, 1.2, 1.3, etc. How can I make them sort as a number instead, so it will go 1.2, 1.2, 1.10? -
postgresql db in ubuntu
how to install , create postqresql db and connect to the project in ubuntu I cant do this ...................................................................................................................................................................................................... sudo -u postgres psql [sudo] password for narjes: could not change directory to "/home/narjes/Documents/my_city/my_city": Permission denied psql (14.9 (Ubuntu 14.9-0ubuntu0.22.04.1)) Type "help" for help. postgres=# createuser narjes postgres-# createdb dbsh postgres-# psql postgres-# alter user narjes with encrypted password '123456'; ERROR: syntax error at or near "createuser" LINE 1: createuser narjes ^ postgres=# createuser narjes postgres-# -
Problem with uploading images/files in DRF
I have a Post model which has and image field and a file field. I created a model serializer for it to use it to create new Post objects in an APIView. model: class Post(models.Model): TEXT = "TXT" IMAGE = "IMG" VIDEO = "VID" REPOST = "REP" POST_TYPE_CHOICES = [ (TEXT, "Text"), (IMAGE, "Image"), (VIDEO, "Video"), (REPOST, "Repost"), ] user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") body = models.TextField(max_length=4000, null=True, blank=True) image = models.ImageField(null=True, blank=True) video = models.FileField( validators=[ FileExtensionValidator( allowed_extensions=["MOV", "avi", "mp4", "webm", "mkv"] ) ], null=True, blank=True, ) post_type = models.CharField(max_length=3, choices=POST_TYPE_CHOICES, default=TEXT) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) tags = models.ManyToManyField(Tag, related_name="posts", blank=True) serializer: class PostCreateSeriazlier(serializers.ModelSerializer): tags = serializers.CharField(required=False) class Meta: model = Post fields = ("body", "image", "video", "tags") extra_kwargs = { "body": {"required": True}, } view: class PostCreateAPIView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): serializer = PostCreateSeriazlier(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data post = Post.objects.create( user=request.user, body=data["body"], image=data.get("image"), video=data.get("video"), ) post.tags.set(get_tags_list(data.get("tags", ""))) # a function to create a list of Tag objects out of a string post.save() return Response(status=status.HTTP_200_OK) When I upload an image, this error is raised: ValueError: "<Post: None - foo - IMG>" needs to have a value for field "id" before this many-to-many relationship can … -
Forbidden (Referer checking failed - no Referer.): /callback/
I want to get a post request from a third-party that deals with payments and I want to get payment transactions from their site through and endpoint called callback. I want to save the transactions in my database but I am getting the following error.Forbidden (Referer checking failed - no Referer.): /callback/ I have enabled the CSRF_ALLOWED_ORIGIN and also used the csrf_exempt decorator in the view that will handle post request from the callback but I am getting the error. How do I go about this issue? -
How to pass foreign key model instance from django to reactjs using axios
I have the address model which is basically foreign key aggregation to different other models. And user Model that has an address ID. every user has an address. and every address is combination of other parameters. Now, i want to access these address parameters from user object instance. Models.py class AddressType(models.Model): add_type_name = models.CharField(_("Address Type"), max_length=30) add_type_code = models.CharField(_("Address Type Code "), max_length=2) def __str__(self): return self.add_type_name class AddressProvince(models.Model): add_prov_name = models.CharField(_("Province Name"), max_length=20) def __str__(self): return self.add_prov_name class AddressBranch(models.Model): add_branch_name = models.CharField(_("Branch Name"), max_length=100) add_branch_code = models.CharField(_("Branch Code"), max_length=10) def __str__(self): return self.add_branch_name class AddressDepartment(models.Model): add_dept_name = models.CharField(_("Department Name"), max_length=150) add_dept_code = models.CharField(_("Department Code "), max_length=5) add_dept_floor = models.PositiveIntegerField(_("Department Floor"), default=0) def __str__(self): return self.add_dept_name class AddressContact(models.Model): add_cont_name = models.CharField(_("Contact Name"), max_length=200) add_cont_position = models.CharField(_("Contact Position"), max_length=200) def __str__(self): return self.add_cont_name class AddressSection(models.Model): add_sec_name = models.CharField(_("Section Name"), max_length=250) class Meta: verbose_name_plural = "Address Section" def __str__(self): return self.add_sec_name class Address(models.Model): add_type = models.ForeignKey(AddressType, on_delete=models.CASCADE, blank=True, null=True, related_name="address_type") add_prov = models.ForeignKey(AddressProvince, on_delete=models.CASCADE, blank=True, null=True,related_name="address_province") add_branch = models.ForeignKey(AddressBranch, on_delete=models.CASCADE, blank=True, null=True,related_name="address_branch") add_dept = models.ForeignKey(AddressDepartment, on_delete=models.CASCADE,blank=True, null=True, related_name="address_department") add_contact = models.ForeignKey(AddressContact, on_delete=models.CASCADE,blank=True, null=True, related_name="address_contact") add_section = models.ForeignKey(AddressSection, on_delete=models.CASCADE,blank=True, null=True, related_name="address_section") add_is_sys = models.BooleanField(_("Is System User?"), default=False) def __str__(self): return self.add_section.add_sec_name class UserGroup(models.Model): … -
Django ValueError - didn't return an HttpResponse object. It returned None instead
I am new to Django Framework. I just want to save employee data using a form. But I always get this error no matter what I adjust in my code. ValueError at /employees/create_employee/ The view employees.views.create_employee didn't return an HttpResponse object. It returned None instead. Here are my codes: Project folder: models.py - employees from django.db import models from datetime import date # Create your models here. class Employee(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) sex = models.CharField(max_length=20) position = models.CharField(max_length=100) division = models.CharField(max_length=50) created_at = models.DateField(default=date.today) updated_at = models.DateField(default=date.today) employees/forms.py from django import forms from .models import Employee class EmployeeForm(forms.ModelForm): class Meta: model = Employee exclude = ['created_at', 'updated_at'] employees/views.py from django.shortcuts import render, redirect from .forms import EmployeeForm # Create your views here. def create_employee(request): if request.method == 'POST': form = EmployeeForm(request.POST) if form.is_valid(): form.save() return redirect('employee_list') # redirect to list view or another page else: return render(request, 'employee_form.html', {'form':form}) employees/templates/employees/employee_form.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Create Employee</title> </head> <body> <h1>Create Employee</h1> <form method='post'> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> employees/urls.py from django.urls import path from . import views urlpatterns = [ path('create_employee/', views.create_employee, name='create_employee'), ] -
Access request or request.user in celery task
I am trying to access request.user in django celery task function but it is unable to access as the function is not accepting any request instance, so How can I access it? @shared_task def run_everyday(): return 0 I have configured that celery function in settings.py to run every day like CELERY_BEAT_SCHEDULE = { "run_day": { "task": "blog.tasks.run_everyday", "schedule": crontab(hour=10, minute=5), }, } I tried by defining another function to return request as result but another function needs to pass the request already like @shared_task def run_everyday(): user = get_request_user() return 0 def get_request_user(request): return request.user It shows request is not defined so How exactly can I access it? Do I need to created a middleware to get the request.user in celery task view? If yes, will that be efficient? -
Superuser gets created in the database but I can't login in Django Admin
class UserManager(BaseUserManager): # Manager class for users def create_user(self, email, password=None, **extra_fields): # Method for creating user if not email: raise ValueError("User must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): # autoslugfield """Create and return a new superuser.""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # Custom User Model for the system class User(AbstractBaseUser, PermissionsMixin): "Users in the system" uid = models.UUIDField(default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone_number = models.CharField(max_length=20) slug = AutoSlugField(unique=True, populate_from="name") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = "email" When I create a django superuser, a user gets created with value 1 in the fields is_superuser, is_active and is_staff. But when I try to login in the django admin with the credentials, this following error occurs saying - "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." (I've attached a screenshot as well). I have tried several approaches but nothing works. Kindly someone help me. Thank you very much. The following link is the screenshot: Can't Login to Django Admin after … -
cookie cutter template docker crash when i run my api which get data from google api or any other third party api?
i have a django api where i used cookiecutter template for rapid development also i used docker to run there apis now the problem is - i have a one api in which i calling a one trirdparty google api for get some data then save it to my database and return api response as a result what some time crash i see the errror is my docker is reload automatic while api is prograsss ? now but should i do for it give me proper solution | * Restarting with watchdog (inotify) | 2023-09-26 06:58:26.032 UTC [50] LOG: unexpected EOF on client connection with an open transaction | Performing system checks... i try to call a third party api and get that data and to database -
Nginx Loadbalancer return 404
this is my nginx conf file upstream django_servers { server serverone.domain.com:80; server servertwo.domain.com:80; } server { server_name server.domain.com; location /apiservice/api/ { proxy_pass http://django_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } when I call the URLs directly from the browser it works fine(https://serverone.domain.com/apiservice/api/). but if I use the load balancer it returns 404. I am using the Django framework location /apiservice/api/ { include proxy_params; proxy_pass http://unix:/root/backend/app.sock; proxy_pass_request_headers on; proxy_connect_timeout 75s; proxy_read_timeout 300s; } this is the service nginx conf -
I want to add a DRF API route only for testing (override_settings), getting 404
I want the following test to pass, but I am always getting a 404 Error. But I would expect the "get all" request to return all users. import json from django.test.utils import override_settings from django.urls import path, include from rest_framework import routers from frontend.tests.mocks import views from django.test import TestCase app_name = 'frontend' router = routers.SimpleRouter() router.register('api/', views.UserModelViewSet) urlpatterns = [ path('', include(router.urls)), ] @override_settings(ROOT_URLCONF=__name__) class TestJsonSchemaSerializer(TestCase): # APITest doesn't work either def test_custom_serializer(self): resp = self.client.get('/frontend/api/') self.assertEquals(resp.status_code, 200) print(resp.status_code, json.dumps(resp.json())) -
static files not found error in nginix after a correct path mentiond
server { listen 443 ssl; # Listen on port 443 for HTTPS traffic server_name 54.198.4.208; # Replace with your actual domain name or IP address # SSL/TLS Certificate Configuration ssl_certificate /etc/nginx/selfsigned.crt; # Path to self-signed SSL certificate ssl_certificate_key /etc/nginx/selfsigned.key; # Path to self-signed SSL certificate key # Location Blocks for Handling Requests location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/logins/staticfiles/; # Path to the root directory of your Django project } location / { proxy_pass https://54.198.4.208:8000; # Replace with your Django app's IP and port proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } this is my nginix configuration and when i tried http://54.198.4.208:8000/static/style.css this url i got file not found 404 error all my static files are present at the correct directory even i tried to open a static file manually by this path and i got staitc files at right path also i checked with permissions also everything is fine but still its not working i tried manually to see wether the path has static files or but it has all static files at correct loaction -
Trying to add data using postman, when having nested serializer
i have two models students and marks, i've list of students i need to add marks using postman in a nested serializer class. How can i select already existing student? Models.py class Student(models.Model): name = models.CharField(max_length=50, null=False, blank=False) roll_no = models.CharField(max_length=5, null=False, blank=False) mobile_no = PhoneNumberField(null=False, blank=False, unique=True) mail_id = models.EmailField(null=False, blank=False) def __str__(self): return self.name class Marks(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) maths = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) science = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) social = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) def __str__(self): return str(self.student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' class MarksSerializer(serializers.ModelSerializer): student = StudentSerializer() class Meta: model = Marks fields = '__all__' if i give dictionary i'm creating new student, i dont want to create on i want to select existing student, How can i do that? how to send data through postman, when you have a nested serializer class? -
Reverse for 'new_entry' with arguments '(")' not found. 1 pattern tried: ['new_entry'/int:topic_id>/']
I am receiving this error when i run my program. The error is said to occur in my topic.html but i am unsure what I typed in wrong for topic_id to return with an empty string. views.py from django.shortcuts import render, redirect from .models import Topic from .forms import TopicForm, EntryForm Create your views here. def index(request): """The home page for Test log""" return render(request, 'test_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'test_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'test_logs/topic.html', context) def new_topic(request): """Add new topic""" if request.method != 'POST': \#No data submitted; create a blank form. form = TopicForm() else: \# POST data submitted; process data. form = TopicForm(request.POST) if form.is_valid(): form.save() return redirect('test_logs:topics') context = {'form': form} return render(request, 'test_logs/new_topic.html', context) def new_entry(request, topic_id): """Add a new entry for a particular topic""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_vaild(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return … -
Theme Customize on Django CMS [closed]
Hello I'm trying to find cms like WordPress on django -
How to protect or secure API routes access Django Rest_framework? [duplicate]
I built my personal website with ReactJS on the client side and Django with Rest_framework for API, Django is serving staticfiles. My personal website has nothing crazy just one API that handles the email. If someone want to get in contact with me then they can fill the form with their email name etc, however. I was able to get access to that api by use typing in the url https:.//www.personalwebsiteurl.com/api/contact-by-email, see screenshot below. Ever since, i got hired as an intern at a small company working with MEAN Stack, i totally forgot most of Django workaround. Thus, how could i secure access to this api/route or if this could potentially cause a security incident on my website? Thank you in advance, not necessarily looking for an a solution with the code but rather than a guide to come up with solution this is my urls.py under api module this is my urls.py under the server -
AxiosError: Network Error in React Native and Django
I am new in Django and React Native. Im using Django rest framework to connect my front end to backend. and I am using "axios" in sending request to django I am trying send URL in django. After receiving, the django will give the length of the url as a response to the react native. I access the path of django in my browser and I think it works fine However, the react native shows "[AxiosError: Network Error]". Your help is deeply appreacited. React Native It sends URL to django const [countChar, setcountChar] = useState() const sendData = async() =>{ const url = "Hello" const response = await axios.post( 'http://127.0.0.1:8000/validationServer/validate/', { url } ); setcountChar(response.data.character_count); console.log(countChar) } <TouchableOpacity style={{backgroundColor:"white" ,padding:20}} onPress={ () => sendData()}> <Text>Send</Text> </TouchableOpacity> validationServer/ view.py from rest_framework.decorators import api_view from rest_framework.response import Response from .serializer import UrlSerializer @api_view(['POST']) def validation (request): if request.method == 'POST': serializer = UrlSerializer(data=request.data) if serializer.is_valid(): url = serializer.validated_data['url'] character_count = len(url) return Response({'character_count': character_count}) return Response(serializer.errors, status=400) validationServer/ serializer.py from rest_framework import serializers class UrlSerializer(serializers.Serializer): url = serializers.CharField(max_length=2048) validationServer /urls.py from django.urls import path from . import views urlpatterns = [ path ("validate/",views.validation, name='url-character') ] // main / urls.py from django.contrib import … -
How to fix port error when creating Django backend service on Google Cloud Run?
I have a Django REST backend image in which I tried to create a service for it on Google Cloud Run. In the Google Cloud Run, I set the port to 6000, and when I tried to create it, it showed these errors: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to MySQL server on '35.226.227.51' (115)") The user-provided container failed to start and listen on the port defined provided by the PORT=6000 environment variable. Default STARTUP TCP probe failed 1 time consecutively for container "backend" on port 6000. The instance was not started. The last 2 layers on the Dockerfile of my backend are: EXPOSE 6000 CMD python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:6000 I am not sure how to fix this for this is my first time trying to deploy a website. For the database error, I have checked the database credentials and configured my Django settings.py to connect to my Google Cloud SQL, MySQL instance with the public IP address as shown and made sure the configuration is correct, but not really sure why it is showing that error. Any help would be … -
Django/DRF GET list of objects including object with FK to that object
I have an API endpoint that returns a list of objects (Orders). class Order(models.Model): item_name = models.CharField(max_length=120) Each of these Orders also has multiple associated Statuses, which acts similar to tracking the location of a package. A new one is created whenever the status changes, with the new status and a timestamp. class OrderStatus(models.Model): status = models.CharField(max_length=30) timestamp = models.DateTimeField(auto_now_add=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="order_statuses") When I query a list of the current Orders, I want to return the most recent OrderStatus associated with it. Such as this: { "count": 2, "next": null, "previous": null, "results": [ { "item_name": "Something", "order_status": { "status": "Processing" "timestamp": "2023-09-25T12:31:12Z" } }, { "item_name": "Other Thing", "order_status": { "status": "Completed" "timestamp": "2023-08-15T10:41:32Z" } } ] } I have tried using prefetch_related() in my View, but that seems to be for the reverse situation (When the query is for the object that has the FK in it's class definition - which here would be if I wanted to list the fields on Order when I query for the OrderStatus). -
Google Charts - Very Slow Loading Time
I'm relatively new to web development and I like the look of Google Charts. I wanna load some Django data with it, but the load time is extremely slow. I have a simple chart here with only a single point. It takes 3-5 seconds to appear, after everything else on the webpage has already shown up. Am I doing anything wrong or could something be causing the lag? // chart google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data = new google.visualization.DataTable(); data.addColumn('date', 'Year'); data.addColumn('number', 'Msgs'); data.addRow([new Date('2023-08-25'), 5]) var options = { hAxis: { title: 'Time' }, vAxis: { title: 'Number of Messages' }, backgroundColor: '#2C2F33' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } Thank you. -
Django - Any ideas on how to mimic the way Amazon handles their progress bar? [closed]
I have tried using Bootstap, which can produce a strait line. But I like the way Amazon's progress bar has node bubbles that show a checkmark in them when it reaches a certain point. I have considered just using a preset image, but if I have like 6 nodes minimum, with multiple options that those nodes can be, that can be a lot of image files. And if something were to change in the flow, it could potentially be a lot of work to update these files. So looking for an alternative -
Getting invalid_grant when trying to exchange tokens using Django-oauth-toolkit
I am trying to use the django-oauth-toolkit but continually hitting an invalid_grant error. I believe I have followed the instructions at https://django-oauth-toolkit.readthedocs.io/en/latest/getting_started.html#oauth2-authorization-grants to the letter. I have created the following script to test with (mostly just extracted the code mentioned in the above page: import random import string import base64 import hashlib code_verifier = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(43, 128))) code_verifier = base64.urlsafe_b64encode(code_verifier.encode('utf-8')) code_challenge = hashlib.sha256(code_verifier).digest() code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8').replace('=', '') client_id = input("Enter client id: ") client_secret = input("Enter client secret: ") redirect_url = input("Enter callback url: ") print(f'vist http://127.0.0.1:8000/o/authorize/?response_type=code&code_challenge={code_challenge}&code_challenge_method=S256&client_id={client_id}&redirect_uri={redirect_url}') code = input("Enter code: ") print(f'enter: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id={client_id}" -d "client_secret={client_secret}" -d "code={code}" -d "code_verifier={code_verifier}" -d "redirect_uri={redirect_url}" -d "grant_type=authorization_code"') The following shows the output (I haven't redacted the details, they are only temporary): (venv) (base) peter@Peters-MacBook-Air Intra-Site % python api_test.py Enter client id: sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N Enter client secret: GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng Enter callback url: https://192.168.1.44/authenticate/callback vist http://127.0.0.1:8000/o/authorize/?response_type=code&code_challenge=WiaJdysQ6aFnmkaO8yztt9kPBGUj-aqZSFVgmWYRBlU&code_challenge_method=S256&client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N&redirect_uri=https://192.168.1.44/authenticate/callback Enter code: hrLeADVEmQF8mDLKJXhAZJRQ2dElV7 enter: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N" -d "client_secret=GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng" -d "code=hrLeADVEmQF8mDLKJXhAZJRQ2dElV7" -d "code_verifier=b'UDZGREwyR0ZVMjNCTzRBQlFaVlBUQk9TWkVRUDlCQzFSUTY1MkFNMUUzRTVCRVBNNlkwR0k4UEtGMUhaVVlTVkQ0QVowMzJUR0xLTDQ1U0VNOEtaWVcxT0tP'" -d "redirect_uri=https://192.168.1.44/authenticate/callback" -d "grant_type=authorization_code" (venv) (base) peter@Peters-MacBook-Air Intra-Site % curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N" -d "client_secret=GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng" … -
Query child objects through parent model - Django
Is it possible to query all child objects through parent model and eventually get the subclass of every element in the queryset. models.py class employee(models.model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) def __str__(self): return self.first_name class teacher(employee): school=models.CharField(max_length=30) district=models.CharField(max_length=30) subject=models.CharField(max_length=30) class doctor(employee): hospital=models.CharField(max_length=30) specialty=models.CharField(max_length=30) If I make a query to get all employees queryset = employee.objects.all() How to get every employee's subclass without making queries for subclasses. Is the subclass repesented with a field in the parent model -
WebSocket with Django and Expo not working
I am building an expo app that uses Django for backend. For the app I need to use WebSocket. But when I try to connect to the WebSocket on my Django project, I get Not Found: /ws/ [25/Sep/2023 19:34:58] "GET /ws/ HTTP/1.1" 404 2678 This is my Expo code: const socket = React.useRef(new WebSocket('ws://myIP:8000/ws/')).current; console.log(socket) if (socket) { // Now you can safely work with the WebSocket object } else { console.error('WebSocket is undefined.'); } socket.onmessage = (event) => { console.log(event.data) // Handle incoming messages from the WebSocket server }; socket.onopen = () => { // WebSocket connection opened console.log("opened") }; socket.onclose = (event) => { // WebSocket connection closed }; socket.onerror = (error) => { // Handle WebSocket errors console.log("error") }; This is my Django code: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'channels', ] ASGI_APPLICATION = 'API.routing.application' routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from .consumers import YourWebSocketConsumer from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "API.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( [ path("ws/", YourWebSocketConsumer.as_asgi()), # Add more WebSocket consumers and paths as needed ] ), }) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class YourWebSocketConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async … -
Migrating an application with subdomains to a single URL
I currently have an application that uses django-tenants with subdomains for each tenant (tenant1.domain.com, tenant2.domain.com...) It uses individual authentication, the auth models are in the schemas So my question is: Is it possible to migrate to a single URL model both for authentication and navigation? I tried many solutions, some managed to authenticate my user, but none managed to make me navigate in a tenant using a "schema-free" URL In short none maintained/created a session