Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to have a dropdown list containing multiple choices for Django models fields?
I'm a newbie to Django and having questions relate to models. Hope that everyone can shed some lights on this. Much appreciated! I'm defining a model, called Customer. It has a membership field with choices option. I want to register the model to Admin page where membership must be a dropdown list which allows customer to choose multiple choices (has a checkbox in front of each choice). So my questions are: Is there any way to do the task with Django models built-in items? If not, can I custom it and how? Please not that I want to the task with models only (not forms). Model: class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLD, 'Gold'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) Admin: class OrderAdmin(admin.ModelAdmin): model = Order list_display = ('placed_at', 'payment_status') admin.site.register(Order, OrderAdmin) I tried using multiselectfield.MultiSelectField but it only can create multiple choices, not in a dropdown list. -
Optimizing the Django model for large tables
Consider a bank with 1 million users and 1 billion transactions. Will all one billion transactions be placed in one table? Is 1-2 billion records normal or too much? If we want to see the transactions of a user, do we search this entire table every time? Is this the way it works or is there a better way? -
Frontend not communicating with Backend
I've got my final year web application project from someone who developed it from me, the front end is in react and backend is in python django with database sqlite. According to him the project is complete and error free and requires no changes to be made as he tested it thoroughly, now for some reasons i dont have his contact or whereabouts so i cant really contact him. I've exhausted all my options but my front end refuses to communicate with backend. Homepage loads fine. but it wont redirect to any other page, it just refreshes to homepage again, if i try to sign in it will always say invalid email or password. if i try to sign up it just refreshes back to homepage after hitting submit. I've done everything from ensuring cors relation, to running production builds, to ensuring urls.py is as it should be. It just wont work. I npm run build my front end and then copy build folder to my backend root directory. then i npm start my front end and py manage.py runserver my backend at the same time, they both compile without any errors and exceptions, my frontend also opens my homepage, … -
how do I make the link from database clickable and get the content of the url
this is my views.py from django.shortcuts import render, redirect from base.models import Prescription def orders(request): orders = Prescription.objects.all() return render(request, 'base/orders.html', { 'orders': orders, }) the link in question is the last one ( order.presc.url ) {% for order in orders %} <tr> <td>{{order.id}}</td> <td>{{order.phone}}</td> <td>{{order.presc}}</td> </tr> {% endfor %} -
Django celery - Task results in Django Admin is empty
I have followed the tutorial to setup the celery/redis relevant settings. the celery task can run successfully, but the "Task results" in django admin is empty with 0 record. here is my settings.py: CELERY_BROKER_URL = "redis://127.0.0.1:6379/0" result_backend = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = "django-db" # CELERY_CACHE_BACKEND = 'django-cache' CELERY_ACCEPT_CONTENT = ['application/json', ] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' # celery setting. CELERY_CACHE_BACKEND = 'default' # # django setting. # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', # 'LOCATION': 'my_cache_table', # } # } CELERY_TASK_TIME_LIMIT = 30*60 celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery('mysite',backend='redis://localhost:6379/1', broker='redis://localhost:6379/0') app.config_from_object("django.conf:settings") app.autodiscover_tasks() app.loader.override_backends['django-db'] = 'django_celery_results.backends.database:DatabaseBackend' @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') [2023-05-14 19:08:08,457: INFO/MainProcess] Received task: OnlinePricing.tasks.add[9c082207-ea07-4962-8bee-da3bce084564] [2023-05-14 19:08:11,467: INFO/MainProcess] Task OnlinePricing.tasks.add[9c082207-ea07-4962-8bee-da3bce084564] succeeded in 3.0159999999996217s: 8 the above task results were never stored in the database I guess. I have migrate the django_celery_results. What's the underlying cause of this empty record problem? -
@register.simple_tag vs @register.tag vs @register.inclusion_tag in Django Templates
The doc says about @register.simple_tag below: This function, which is a method of django.template.Library, takes a function that accepts any number of arguments, wraps it in a render function and the other necessary bits mentioned above and registers it with the template system. And, the doc only says about @register.tag below: Finally, register the tag with your module’s Library instance, as explained in writing custom template tags above. And, the doc says about @register.inclusion_tag below: Another common type of template tag is the type that displays some data by rendering another template. For example, Django’s admin interface uses custom template tags to display the buttons along the bottom of the “add/change” form pages. Those buttons always look the same, but the link targets change depending on the object being edited – so they’re a perfect case for using a small template that is filled with details from the current object. But, I don't understand what they are like so what is the difference between @register.simple_tag, @register.tag and @register.inclusion_tag in Django Templates? -
Django Rest Framework : null value in column "user_id" of relation "posts_post" violates not-null constraint
I am getting this error: IntegrityError at /myapi/posts/ null value in column "user_id" of relation "posts_post" violates not-null constraint DETAIL: Failing row contains (18, Osama's Post, This is osama's post, 2023-05-14 09:32:06.191629+00, #123, null) Basically I am working on a blog. I have created two APIs one is of user and another is post. But in when I try to insert a new blog post I get this eroor . Please help me to resolve this. My serializers.py from rest_framework import serializers from .models import Post #post imported from models class PostSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source = 'user.username') #the username will be current authorized user i,e user.username class Meta: model = Post fields = ('id', 'title', 'body', 'created', 'user', 'hashtags') My views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import permissions from .models import Post from .serializers import PostSerializer from django.contrib.auth.models import User # 1: Get list of all posts class PostListAPIView(APIView): #Base class = APIView permission_classes = [permissions.IsAuthenticated] #only authorized users can access this view def get(self, request, *args, **kwargs): #Get all posts posts = Post.objects.all() #Fetch all objects of post serializer = PostSerializer(posts, many = True) #serialize the … -
Switch value in Django models.BooleanField with class base view by click on button
Working on ToDo list as a practice project. this is link to GitHub This is my models.py: class Tag(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Task(models.Model): TASK_STATUS_CHOICES = [(False, 'Not done'), (True, 'Done')] content = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField( default=timezone.now, null=True, blank=True, help_text="Enter date and time in '2023-05-13 06:31' format" ) is_completed = models.BooleanField( default=False, choices=TASK_STATUS_CHOICES ) tags = models.ManyToManyField(Tag, related_name="tasks") class Meta: ordering = ["is_completed", "-created"] def __str__(self): return self.content I want to switch True/False value of **is_completed ** field by clicking on the button. In all examples I can find in interent, it's done with help of func base view, so I did it in like this: view.py: def task_complete_or_undo(request, pk): task = Task.objects.get(id=pk) task.is_completed = not task.is_completed task.save() return redirect("/") urls.py: path( "task/<int:pk>/task-status", task_complete_or_undo, name="task-status" ), index.html {% if task.is_completed %} <span style="color: green">{{ task.get_is_completed_display }}</span> <a href="{% url 'todo_list_app:task-status' pk=task.id %}" class="btn btn-secondary btn-sm link-to-page float-right"> Undo </a> {% else %} <span style="color: red">{{ task.get_is_completed_display }}</span> <a href="{% url 'todo_list_app:task-status' pk=task.id %}" class="btn btn-success btn-sm link-to-page float-right"> Complete </a> {% endif %} This works for me, but my mentor asked me to rewrite it in class base view. His advise is … -
phone field in Custom user model fills with first_name and last_name after registration in Django
Im trying to make signup view for my app and after i fill form user saves, but phone field fills with first name + second name. It validates phone correctly but then fills phone field in db with nonsense. models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from django.urls import reverse from .managers import CustomUserManager class AvitoUser(AbstractUser): username = None first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) phone = PhoneNumberField(_("phone number"), unique=True) USERNAME_FIELD = "phone" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def get_username(self): return f'{self.first_name} {self.last_name}' def get_absolute_url(self): return reverse('users:profile', kwargs={'pk': self.id}) def __str__(self): return f'AvitoUser№ {self.id} , f-s name: {self.first_name} {self.last_name}' forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from phonenumber_field.formfields import PhoneNumberField from django.contrib.auth import get_user_model AvitoUser = get_user_model() class RegisterForm(UserCreationForm): first_name = forms.CharField(label='First name', max_length=16) last_name = forms.CharField(label='Last name', max_length=16) phone = PhoneNumberField() class Meta: model = AvitoUser fields = ["first_name", "last_name", "phone", "password1", "password2",] views.py from django.views import generic from django.urls import reverse_lazy from django.contrib.auth import get_user_model from . import forms AvitoUser = get_user_model() ... class SignupView(generic.CreateView): model = AvitoUser form_class = forms.RegisterForm success_url = reverse_lazy('users:login') template_name = "registration/signup.html" ... managers.py from django.contrib.auth.base_user import … -
Django manage.py dumpdata command only dumping 2000 rows only per table
we are migrating the data of our django application to a new environment. Normally we would just be using the built in dumpdata management command to create a dump of all our tables and then load everything back into the new environment using loaddata. To be precise, we are using the following command to create the db dump without the auth.permissions and contenttypes tables: python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 2 > db.json We noticed, that the result only contains a maximum of 2000 rows per table. As some of our tables have got 8000-15.000 records, we are missing data, when importing the dump in the new environment. What we did / tried so far we tried different combinations of arguments for the dumpdata command we tried other formats like jsonl or xml we did not change anything in the we found out that it might be a limitation to the serializer running out of memory (we did not change the serializers) we found out that we might need to adapt the max_allowed_packets for our db Used Django Version and packages Django==3.2.15 mysql-connector-python==8.0.30 pyyaml==6.0 others Questions does anybody have a clue what we are not seeing … -
How to write group-by clause in Django of two tables
I have the following two tables in MySQL database. I want to find sum of withdraw, rakeback and deposits per player and show them in django template. I get a result but each dictionary of list repeat uname from primary key. Primary Key Table (Players) id uname fname lname 1 hajra Basit iqbal 2 newton Thomas Kirk Foreign Key Table (Transactions) Id Admin Tran_date tran_amount Tran_type Ply_id 1 van 2023-05-11 24 withdraw 2 2 musa 2023-03-28 14.2563 withdraw 2 3 zafar 2014-10-14 25.365 rakeback 2 4 Payoo 2002-08-12 63.25 deposit 2 5 zaman 2023-05-01 14.23 deposit 1 6 imran 2023-05-02 25.23 deposit 1 I have tried the following query data = Transaction.objects.values('uname', 'tran_type').order_by().annotate(Total=Sum('tran_amount')) Expected Result <QuerySet [{'uname': 'newton', 'tran_type': 'withdraw', 'Total': 38.256299999999996, 'tran_type': 'rakeback', 'Total': 25.365, 'tran_type': 'deposit', 'Total': 63.25}, {'uname': 'hajra', 'tran_type': 'withdraw', 'Total': 0.0, 'tran_type': 'rakeback', 'Total': 0.0, 'tran_type': 'deposit', 'Total': 39.46}] Or <QuerySet [{'newton', 'withdraw', 38.256299999999996, 'rakeback', 25.365, 'deposit', 63.25}, {'hajra', 'withdraw', 0.0, 'rakeback', 0.0, 'deposit', 39.46}] -
How can i iterate the product detial by section name in django template
Model class Section(models.Model): name = models.CharField(max_length=100) def __str__(self) : return self.name class Product(models.Model): total_quantity = models.IntegerField() availability = models.IntegerField() product_name = models.CharField(max_length=100) featured_image = models.CharField(max_length=100) price = models.IntegerField() discount = models.IntegerField() product_information = RichTextField() View def Home(request): product = Product.objects.filter(section__name = 'Top Deals Of The Day') context = { 'product' : product } return render(request, 'main/home.html', context) Im trying to iterate the product details by section name , my section name is Top features of the day. But its not working perfectly. Anyone help me to solve this HTML <div class="col-xl-6 col-lg-12"> <div class="single-features-item single-features-item-d b-radius mb-20"> {% for i in product %} {% if i.section == "Top Featured Products" %} <div class="row g-0 align-items-center"> <div class="col-md-6"> <div class="features-thum"> <div class="features-product-image w-img"> <a href="product-details.html"><img src="{{ i.featured_image }}" alt=""></a> </div> <div class="product__offer"> <span class="discount">-15%</span> </div> <div class="product-action"> <a href="#" class="icon-box icon-box-1" data-bs-toggle="modal" data-bs-target="#productModalId"> <i class="fal fa-eye"></i> <i class="fal fa-eye"></i> </a> <a href="#" class="icon-box icon-box-1"> <i class="fal fa-heart"></i> <i class="fal fa-heart"></i> </a> <a href="#" class="icon-box icon-box-1"> <i class="fal fa-layer-group"></i> <i class="fal fa-layer-group"></i> </a> </div> </div> </div> <div class="col-md-6"> <div class="product__content product__content-d"> <h6><a href="product-details.html">{{i.product_name}}</a></h6> <div class="rating mb-5"> <ul class="rating-d"> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i … -
unauthorized error when try to test login view in drf
i write a test for my login view in django rest framework. it's the test: class LoginViewTests(APITestCase): def setUp(self): self.user = User.objects.create_user( phone_number='09012345678', password='Test_1_Password' ) def test_login(self): url = reverse('login') data = { 'phone_number': '09012345678', 'password': 'Test_1_Password' } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_login_user_does_not_exist(self): url = reverse('login') data = {'phone_number': '09123456789', 'password': 'Test_1_Password'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) this is relevant view: class LoginView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) and serializer: class LoginSerializer(serializers.Serializer): phone_number = serializers.CharField(max_length=13, required=True) password = serializers.CharField(max_length=50, required=True, write_only=True) tokens = serializers.SerializerMethodField(read_only=True) def get_tokens(self, obj): user = User.objects.get(phone_number=obj['phone_number']) return { 'refresh': user.tokens()['refresh'], 'access': user.tokens()['access'] } class Meta: model = User fields = ['phone_number', 'password', 'tokens'] def validate(self, attrs): phone_number = attrs.get('phone_number', '') password = attrs.get('password', '') user = auth.authenticate(phone_number=phone_number, password=password) if not user: raise AuthenticationFailed('Invalid credentials') if not user.is_active: raise AuthenticationFailed('Account disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('phone number is not verified') return { 'phone_number': user.phone_number, 'tokens': user.tokens } when i test it by postman or swagger, login successful, but when i run the test, i get error 401 unauthorized. you can see, i didn't use IsAuthenticated permission i check everything … -
I need one Fast boilerplate using e pydantic and sqlite?
Is there who can give me a fastApi boiler plate code using sqlite, postgress and pydantic. In this boiler plate I want authorization and authentication. And role based authentication routing. -
Djanogo query existing DB table and model create
I'm trying to query data from my local DB and create an model in models.py using this command python manage.py inspectdb > AppName/models.py And i makemigration and migrate, I found Django auto create a field in migration file ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') Since my DB table doesn't exist 'id' this column, so as I refresh the web page and the error raises Exception Value:(1054, "Unknown column 'train_item_detail.id' in 'field list'") The problem is the table train_item_detail don't need the column 'id'. Any other solutoin except add the column id in my database? -
Flask doesnt show my content with my template
I just started my project install flask made actual temlate dir so for some reason but idk why it doesn't render my page? here Pycharm (some Hello World shit) from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return render_template("987.html") if __name__ == "__main__": app.run() Here you can see that server actualy loads my template, but for some reason adds that wired bis_register idk. My template: <!DOCTYPE html> <html> <head> <title>Windows XP Desktop</title> <link rel="stylesheet" href="style.css"> </head> <body> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { background-color: #1e90ff; } .taskbar { width: 100%; height: 28px; position: fixed; bottom: 0; background-color: #D4D0C8; display: flex; justify-content: left; border: 2px solid #FFFFFF; align-items: center; padding: 0 10px; z-index: 1; } .start-button { width: 57px; height: 24px; background-image: url('StartButton.png'); background-color: #808080; cursor: pointer; } .taskbar-icons { display: flex; } .taskbar-icon { width: 18px; height: 18px; margin: 0 5px; cursor: pointer; } .window { width: 950px; height: 650px; background-color: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 2px solid #D4D0C8; z-index: 2; } .window-button { width: 18px; height: 18px; background-image: url('XButton.png'); background-size: contain; background-repeat: no-repeat; margin: -2.5px 1px 1px auto; cursor: pointer; } .window-header { height: … -
indexing a table which keeps inserting data per day
I am using django for the backend and i used db_index = True for one field, the table keeps inserting data every 3 minutes(because a machine sends data with this period and django receives and stores is in related table) and now I am wondering if there is problem with this approach. i mean for indexing. Thanks -
Embedde excel file in django project
I want to show excel in my web django priject. csv is also an option. show the file itself, with option to read and edit inside. the data for the excel is used in my beb (no need to import a file for that) anybody knows how?? it should look like in the img all I found is to read data from xl files and import to a web, or the opposite... -
You cannot call this from an async context - use a thread or sync_to_async. in django channels
This is my code of django channels.How to obtain the data it gives the error You cannot call this from an async context - use a thread or sync_to_async. class WaitlistConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() try: asyncio.ensure_future(self.send_data()) except Exception as e: print(e) async def disconnect(self, close_code): self.task.cancel() async def send_data(self): while True: await asyncio.sleep(3) try: waitlist =await sync_to_async(Waitlist.objects.all)() print(waitlist) if waitlist.exists(): print("first name") data={"first_name":waitlist[0].first_name} else: data = {"first_name": "No one is waiting"} await self.send(json.dumps(data)) except Exception as e: print(e) -
Two social apps for one provider in django-allauth
Is it possible to have two social apps for one provider? Here is my use case: I want to have two social apps for the "Microsoft" provider. One will be for organizations only and the other one will be for consumers (any user with a Microsoft account). I know that I can set: SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'TENANT': 'organizations', } } to only allow the organization's users to authenticate. And for consumers, I can set it to consumers (which is the default value). But the problem is I am unable to find a proper way to implement this idea. If anyone have any idea how I can implement this? or whether this is possible or not? -
Showing property filter value in Django template
I have the follwoing models in my Django project: class File(models.Model): client = models.ForeignKey(User, on_delete=models.PROTECT, related_name='client_files') title = models.CharField(max_length=250, blank=True, null=True) ... class FileTracking(models.Model): file = models.ForeignKey(File, related_name='file_tracking', on_delete=models.CASCADE) description = models.CharField(max_length=250, null=True, blank=True) date = models.DateField(auto_now=False, auto_now_add=False) active = models.BooleanField(default=False) ... my view: class FileCurrentView(ListView): model = Filetemplate_name = 'files_current.html'def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: user=self.request.user current_files = files.filter(...) ... context["user"] = user context["current_files"]= current_files ... return context In my template, I want to show the description of the last active record. I tryied to create a property in the FileTracking model: @property def LastActiveTrack(self): result = self.objects.filter(active=1).order_by("-date")[0].title result_txt = str(result) if result: return result_txt return '' in my template: {% for file in current_files %} Title: {{file.title}} last Tracking: {{file.file_tracking.LastActiveTrack}} {% endif %} but i couldn't get the value of the LastActiveTrack in my template. any ideas?? -
Listing objects with the same foreign key
I am making an app for a BJJ tournament. I have a form to catch competitors' registration like name, weight, and rank. After that, the admin will create however many groups for competition as needed. Each competitor can only be in 1 group. How do I automatically list all competitors in a bracket after I list them there? Something like: Group 1: Eric W - 180 - Blue - 0 Bas L - 170 - Blue -2 etc.. Group 2: Donni F - 160 - Purple - 3 Sam C - 140 - Purple - 3 etc.. models.py class Group(models.Model): group_label = models.CharField(max_length=20, unique=True) def __str__(self): return self.group_label class Competitors(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)]) rank = models.CharField(max_length=255) Group_FK = models.ForeignKey(Group, blank=True, null=True, on_delete=models.CASCADE, to_field='group_label') point = models.IntegerField(default=0) admin.py class MemberAdmin(admin.ModelAdmin): list_display = ("flname", "Weight", "rank", "Group_FK", "point") admin.site.unregister(Competitors) admin.site.register(Competitors, MemberAdmin) def __str__(self): return f"{self.flname} {self.Weight}" class MemberAdmin(admin.ModelAdmin): list_display = ["group_label"] admin.site.unregister(Group) admin.site.register(Group, MemberAdmin) def __str__(self): return self.group_label I thought setting up the foreign key would do the trick.. -
Unusual dark mode option in Django Admin
I added the following code in my setting.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static', os.path.join(BASE_DIR, 'static') ] The app is able to find my .css file. However, it seems like the Django admin is not able to find its css files. And all of a sudden the following options show up in Django Admin. When I comment out the code, these dark mode options disappears and Django admin works properly. Is this a bug in the Django 4.2? Or did I setup my static directory incorrectly? -
Using Django (+DB), Gunicorn, and Socketio, I cannot access Django database from multiple threads
I'm attempting to set up the traditional Django deployment stack (Django, Gunicorn, NGINX). I am also using socketio, similar to the example in the python-socketio documentation. Unfortunately, the sockets do not play nice with the Django database. My code is essentially doing the following: from models import MyModel sio = sio.connect(async_mode = "eventlet") @sio.event def my_message(msg, sid): MyModel.create(...) I run gunicorn with the following: gunicorn -k eventlet --preload -w 1 django_socketio.wsgi:application I'm getting an error: django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140674673057408 and this is thread id 140674672989376. Essentially, the socket handler is being called from multiple threads. However, Django's ORM model doesn't support this, so it's throwing an error. How do I better support the Django ORM being accessed from multiple threads (or alternatively, make django and socketio play nicer together so this is not an issue)? NOTE: I've seen basically the same issue described here, but their solution (--preload) did not work for me. -
Django: How to make one-to-one relation with auth login and custom profile model?
I've implemented google login to my project, logs in correctly and makes a new row in the database for the user, but does not make a profile. I have one-to-one relation between the user and the profile, how can i add profile for the google logins? I'm getting error UserProfile matching query does not exist. when i try to view my profile on the page. This is the view for the profile page: class ProfileView(views.View): template_name = 'profile/profile.html' def get(self, request, pk): user = UserModel.objects.filter(pk=pk).get() profile = UserProfile.objects.filter(user_id=user.pk).get() context = { 'profile': profile } return render(request, self.template_name, context) the url: path('profile/<int:pk>/', views.ProfileView.as_view(), name='profile-page'), and the template: <li class='text-black text-xl mx-2 py-1.5 rounded-full bg-slate-300 shadow-2xl hover:bg-slate-400'> <a class="px-3 py-1.5" href="{% url 'profile-page' pk=request.user.pk %}"> <i class="fa-solid fa-user"> </i> </a> </li> I can get the error not to show but when i try to edit the profile it cannot do it since it has no relation with the profile model.