Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
give me return "None" when pass variable to antoher html page
still learn about django and want to try pass variable, i want to pass variable that i got from index.html to process.html, when i clicked the button give me value "None" not the value from video.id, views.py def process(request): context = { } videoid = request.POST.get('videoid',None) context['videoid'] = videoid print(videoid) print(context) return render(request, 'search/process.html', context) slice of my index.html code to pass the value of video.id index.html <form action="/process" method="POST" id="videoform"> {% csrf_token %} <a type="submit" name="videoid" value= "{{video.id}}" form="videoform" href="/process" class="btn btn-sm btn-outline-secondary" target="_blank">Test</a> </form> process.html <body> <h1>Event For {{ videoid }}</h1> <p>HELLO WORLD</p> </body> tested in index.html , i got the value video.id but None when pass to process.html ty, before for ur help -
how to automatically add tags to a post
Can you please tell me if there is a way to add instances of the ManytoMany class to django automatically everything. Add all tags that are to the post during its creation automatically, without selecting them manually. -
Value error. The view 'users.views.register' didn't return an HttpResponse object. It returned None instead
Python 3.8.5, Django 3.1.6 I'm learning python and django with book Python Crash Course: A Hands-On, Project-Based Introduction to Programming (Erik Matthes)enter image description here Now I cannot continue because I cannot find a solution to the problem. ValueError at /users/register/ The view users.views.register didn't return an HttpResponse object. It returned None instead. views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm def register(request): # return HttpResponseRedirect(reverse('index')) print(request.method) import pdb; pdb.set_trace() if request.method != "POST": form = UserCreationForm() else: print('\nelse\n') form = UserCreationForm(request.POST) print('\n'+str(form.is_valid())+'\n') if form.is_valid(): new_user = form.save() authenticated_user = authenticate(username=new_user.username, password=request.POST['password1'], confirm_password=request.POST['password2']) login(request, authenticated_user) return HttpResponseRedirect(reverse('index')) context = {'form': form} return render(request, 'users/register.html', context) urls.py from django.urls import re_path from django.contrib.auth.views import LoginView, LogoutView from django.views.generic import RedirectView from . import views urlpatterns = [ re_path(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'), re_path(r'^logout/$', LogoutView.as_view(template_name='learning_logs/index.html'), name='logout'), re_path(r'^register/$', views.register, name='register') ] register.html {% extends 'learning_logs/base.html' %} {% block content %} <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{form.as_p}} <button name="submit">Register</button> <input type="hidden" name="next" value="{% url 'index' %}" /> </form> {% endblock content %} Pls help me. I've been trying unsuccessfully to fix this for a week now. … -
upload images from postman using function in django rest framework
Model: class Department(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Employee(models.Model): department = models.ForeignKey(Department,on_delete=models.CASCADE,related_name='employee') name = models.CharField(max_length=100) address = models.CharField(max_length=100) image = models.ImageField(upload_to='employee_pic',null=True,blank=True) class Meta: ordering =('id','name') def __str__(self): return self.name Serializers.py class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id','name','address','image','department'] class DepartmentSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=True,read_only=True) class Meta: model = Department fields=['id','name','employee'] views.py @api_view(["GET","POST"]) def employeeList(request): if request.method == "GET": data = Employee.objects.all() all_data = EmployeeSerializer(data,many=True) return JsonResponse(all_data.data,safe=False) elif request.method == "POST": data = JSONParser().parse(request) new_data = EmployeeSerializer(data,request.data) if new_data.is_valid(): new_data.save() return JsonResponse(new_data.data,status = status.HTTP_201_CREATED) urls.py path('api/function/employee', views.employeeList, name='employee'), I need to post image from postman and in views.py i want to use function for image post. I want to create my views using function. I don't want to use class like ModelViewSet i would to use almost all function. Thanks in advance. -
Django custom command: AttributeError: 'Settings' object has no attribute 'setmodule'
I'm currently working on a webscraper with Scrapy and the data is stored in Django. When i start the scraper with a custom command. But i got stuck at this error: AttributeError: 'Settings' object has no attribute 'setmodule' I checked my settingsfile and couldn't find a Setmodule attribute. My custom command file: /webscraper/management/commands/crawl-test.py import os # Django requirements from django.core.management.base import BaseCommand from django.conf import settings # scrapy requirements import scrapy from webscraper.webscraper.spiders.WebSpider import WebSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings class Command(BaseCommand): help = "Web Scraper" def handle(self, *args, **options): process = CrawlerProcess(get_project_settings()) os.environ['SCRAPY_SETTINGS_MODULE'] = 'webscraper.settings' settings_module_path = os.environ['SCRAPY_SETTINGS_MODULE'] settings.setmodule(settings_module_path, priority='project') process = CrawlerProcess(get_project_settings()) process.crawl(WebSpider) process.start() If you need more information just leave a comment! -
Automatically Delete Duplicate objects in template
I am Building a WebApp and I am stuck on an Problem. What i have Build and What i am trying to do :- I build a Private Chat App , If user_1 accept user_2's FriendRequest then a ChatBox will be automatically created in the Chats page. BUT When a user unfriend another user then ChatBox is still there ( Which is no problem ) BUT When the unfriended user again send send friend request then another ChatBox is automatically creating with the same user , AND i want it to delete previous or delete newer chat after second accepted request. What have i tried I also tried .distinct() function BUT it didn't work for Me. I also tried many solutions like This. BUT nothing worked. views.py def accept_friend_request(request,user_id): from_user = get_object_or_404(User,id=user_id) frequest = FriendRequest.objects.filter(from_user=from_user,to_user=request.user).first() user1 = frequest.to_user user2 = from_user chat_box = ChatBox(user_1=user1,user_2=user2) chat_box.save() frequest.delete() return redirect('profile',user_id=user_id) I don't know what to do now. Any help would be Appreciated. Thank You in Advance. -
can you create a social network or a search engine with django python [closed]
can you create a social network or a search engine like google with django python. -
Microservices in Django
I am trying to build a project based on Microservices using Django rest Framework where i have some data coming from a different project running on different port. In illustration , the data in red circle should be coming from a project running on different port based on the id stored in 1st project (one to many relationship). I was able to get the data from 2nd project via api request but wasn't able to display it in the response as in the image below How do i achieve something like this in django rest framework? -
Override method of a django builtin Class
Just for example, I need to modify the implementation of AdminSite.get_app_list like following From #app['models'].sort(key=lambda x: x['name']) To app['models'] = sort_with_name_length(app['models']) //my own method Expected/desired approach: I supposed that it should be achievable by just writing following code in any of my custom module's models.py or sites.py file class MyAdminSite(AdminSite): def get_app_list(self, request): app_list = super().get_app_list(request) for app in app_list: #app['models'].sort(key=lambda x: x['name']) app['models'] = sort_with_name_length(app['models']) #an example change I need return app_list But what above code does is nothing, its never executed, until I use Monkey patching guided by this answer. What I could achieve from django.contrib.admin import AdminSite class MyAdminSite(AdminSite): def get_app_list(self, request): # res = super(MyAdminSite, self).get_app_list(request) //gives following error # super(type, obj): obj must be an instance or subtype of type # So i have to rewrite complete method again in my module like following app_dict = self._build_app_dict(request) app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) for app in app_list: #app['models'].sort(key=lambda x: x['name']) app['models'] = sort_with_name_length(app['models']) return app_list AdminSite.get_app_list = MyAdminSite.get_app_list Problem being faced: Above does what I need in a totally undesired way. This solution has two problems It will not allow me Multilevel Inheritance (I would not be able to have child and grand child) Its … -
Trouble shooting with postgresql to connect with Django | Window 10
I install PostgreSQL version 10 also, install pgAdmin4 During the PostgreSQL installation, as Every developer know default username = Postgres My PostgreSQL username was Postgres. installation window asked me the password, so put the new password Now when I connect PostgreSQL to my Django project I install this module pip install psycopg2 I created a new database using pgAdmin4 named 'mydb' In my Settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USERNAME':'postgres', 'PASSWORD' : '<my_Password_here>' , # I entered the same password that i provided during postgres installation 'HOST' : 'localhost', 'PORT': '5432', } } postgres username = 'postgres' where my Window Username = 'Huzaifa' ERROR is here django.db.utils.OperationalError: FATAL: password authentication failed for user "Huzaifa" Why Postgres using my Window User (username) for authentication NOTE: I already set environment variables as following C:\Program Files\PostgreSQL\10\lib C:\Program Files\PostgreSQL\10\bin -
Unable to deploy django to python 3.8/Linux 2 on Elastic Beanstalk due to "postgresql95-devel is not available to be installed"
This is my requirements.txt: asgiref==3.3.1 boto3==1.17.23 botocore==1.20.23 certifi==2020.12.5 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.6 defusedxml==0.7.1 Django==3.1.7 django-allauth==0.44.0 django-cors-headers==3.7.0 django-rest-auth==0.9.5 djangorestframework==3.12.2 idna==2.10 jmespath==0.10.0 oauthlib==3.1.0 psycopg2==2.8.6 pycparser==2.20 PyJWT==2.0.1 python-dateutil==2.8.1 python3-openid==3.2.0 pytz==2021.1 requests==2.25.1 requests-oauthlib==1.3.0 s3transfer==0.3.4 six==1.15.0 sqlparse==0.4.1 urllib3==1.26.3 The main error message I see in my logs is: postgresql95-devel is not available to be installed. I am able to deploy a similar requirements.txt in an older environment (python 3.6) but for some reason this fails when on python 3.8. I even used the same deployment.zip that succeeded in 3.6 but this suddenly fails in 3.8. Is this a configuration error or a versioning error? Not sure how to debug this. -
How do I implement graphql with social auth in django?
I am facing an error while implementing it. The error is in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I am using python3.9.1 and django-graphql-social-auth0.1.4. -
while signup 'AnonymousUser' object has no attribute '_meta'
class SignupView(View): def get(self, request): userform = UserForm() studentform = StudentForm() facultyform = FacultyForm() deptform = DepartmentForm() roleform = RoleForm() return render(request, 'signup.html', {'userform': userform, 'studentform': studentform, 'departmentform': deptform, 'roleform': roleform, 'facultyform': facultyform}) def post(self, request): user_role = { 'Student': StudentForm(request.POST), 'Faculty': FacultyForm(request.POST), } roleform = RoleForm(request.POST) if roleform.is_valid(): temp_role = roleform.cleaned_data['role'] usertype = user_role.get(temp_role) userform = UserForm(request.POST, request.FILES) deptform = DepartmentForm(request.POST) if userform.is_valid() and usertype.is_valid() and deptform.is_valid() and roleform.is_valid(): role = roleform.save(commit=False) role1 = Role.objects.filter(role=role).first() # saving user with department user = userform.save(commit=False) # department and Role saved dept = deptform.save(commit=False) dept1 = Department.objects.filter(department=dept).first() user.department = dept1 user.role = role1 user.save() new_user = usertype.save(commit=False) new_user.user = user new_user.save() login_userr = authenticate( username=userform.cleaned_data['username'], password=userform.cleaned_data['password']) login(request, login_userr) return redirect('user_profile', pk=user.id) else: return render(request, 'signup.html', {'userform': userform, 'departmentform': deptform, 'roleform': roleform}) else: return render(request, 'signup.html', {'userform': userform, 'departmentform': deptform, 'roleform': roleform}) -
Exported HTML table to excel giving warning while opening the file using office Excel
I am trying to export HTML table to xls format. But when I try to open the file using Excel, I am given a warning message. The waring message: I using this lines of code: var file = new Blob([ html.outerHTML], { type: "application/vnd.ms-excel" }); var url = URL.createObjectURL(file); var filename = dateSelected + "-" + "attendance" + ".xls" //here we are creating HTML <a> Tag which can be trigger to download the excel file. var a = document.createElement('a'); a.id = "export"; document.body.appendChild(a); //here we are checking if the bwoswer is IE or not if IE then we use window.navigator.msSaveBlob function otherwise Go with Simple Blob file. if (window.navigator && window.navigator.msSaveBlob) { window.navigator.msSaveBlob(file, filename); a.click(); document.body.removeChild(a); document.body.removeChild(html); } else { a.download = filename; a.href = url; a.click(); document.body.removeChild(a); document.body.removeChild(html); } I tried to change the blob type but nothing is working. How can i solve this issue? -
Django Blog url error NoReverseMatch at /
I git this error home.html page when I but the url to user posts page the url is work fine in other pages but in home page I get this error Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)/$'] I don't know if their something I need to but in home.html to let me access the post.author.usernname home.html {% extends "blog/base.html" %} {% block content %} <h1>Blog Home!</h1> {% for post in posts %} <article class="media content-section"> <img class = "rounded-circle article-img" src = "{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class = "btn btn-outline-info mb-4" href="?page=1">First</a> <a class = "btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class = "btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-4' and num < page_obj.number|add:'4' %} <a class = "btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> … -
AWS ec2 Nginx + Django server easily gets to 100% CPU utilisation without much traffic
Hi I am using AWS EC2 instance (c5.18xlarge (72vcpu and 144 Gib ram)) with Nginx + Django and postgresql. The problem is it gets to 100% CPU utilisation in 400-500 concurrent users and slows down. Here are my settings: postgresql.conf max_connections = 800 shared_buffers = 50000MB Nginx.conf user www-data; worker_processes 128; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; worker_rlimit_nofile 50000; events { worker_connections 10000; #multi_accept on; } sysctl.conf net.core.somaxconn = 65000 net.core.netdev_max_backlog = 65535 fs.file-max = 90000 net.ipv4.ip_forward = 1 kernel.shmmax=1006632960 gunicorn_start.bash NAME="django_app" # Name of the application DJANGODIR=/home/ubuntu/project # Django project directory SOCKFILE=/home/ubuntu/env/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=128 # how many worker processes should Gunicorn spaw TIMEOUT=120 DJANGO_SETTINGS_MODULE=project.settings # which settings file should Django use DJANGO_WSGI_MODULE=project.wsgi # WSGI module name echo "Starting $NAME as `whoami`" I know the server can't overload on the current usage of the app. Please suggest how can this be solved. Or how can it be debugged to reach the problem. -
Reverse for 'send_form' with no arguments not found. 1 pattern(s) tried: [u'app/send_message/(?P<flag>\\d+)/$']
I am trying to build a form to be used in 2 pages (index and contact). Once the form performs method post, it will bring a page either success or failed (simple html page with few words). I am stuck due to the error shown above and I’m still new in using Django. Appreciate any help. Thank you urls.py from django.conf.urls import url from django.conf.urls import include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^app/', include('app.urls')) ] app/url.py from .views import * app_name = "app" urlpatterns = [ url(r'^home/$', home, name='home'), url(r'^contact/$', contact, name='contact'), url(r'^send_message/(?P<flag>\d+)/$', send_form, name='send_form'), url(r'^send_message/success/$', success, name='success'), url(r'^send_message/failed/$', failed , name='failed'), ] views.py from django.core.mail import send_mail from .forms import MessagesForm from django.conf import settings rom django.shortcuts import render, redirect def home(request): empty_form = send_form(request) cover_title = PageServiceCover.objects.latest('id').title cover_text = PageServiceCover.objects.latest('id').text context = {'cover_title': cover_title, 'cover_text': cover_text,'form':empty_form} return render(request, 'index.html', context) def send_form(request): if request.method == 'POST': form = MessagesForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] category = form.cleaned_data['category'] text = form.cleaned_data['text'] form.save() subject=[name, phone, category] send_mail(subject, text, email, [settings.EMAIL_HOST_USER], fail_silently=False) return redirect('thanks', flag='success' ) else: return redirect('not_working', flag='failed') def success(request): return … -
Download File From s3 using django and render it to browser
I have a Django app in which we have a download button and on click, on that button, the file should be rendered to the browser. I have already tried using the download_file method but the issue is the file is downloaded to the local system. Here is how my current code looks like: def downloadObject(sourceBucket, key): content_type = 'application/x-zip' s3_temp = boto3.client('s3') file = s3_temp.get_object(Bucket=sourceBucket, Key=key) response = FileResponse(file, content_type=content_type, filename="{}".format(key)) response['Content-Disposition'] = 'attachment; filename="{}"'.format(key) return response -
Create Tables in Database from Django
I made an application using django and I want to run the code on a different computer, I have created a database in that computer and I want to create the tables. I am using postgres and I am aware that we can create the tables manually using sql commands but I have a lot of tables. I was wondering if I can make them using commands from django since I have them in my models.py file. I have tried doing py manage.py makemigrations and py manage.py migrate but the tables were not created instead it showed comments like - No changes deteted and No migrations to apply. Thanks in advance! -
Pointfield not picking and storing latitude and longitude in Django
The following Location field which is a Pointfield is not picking up and storing the coordinates. It results in giving the default coordinates given i.e (0,0). class CustomerProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) fullname = models.CharField(max_length=120,unique=True) choice = ( ('AB+ve','AB+ve'), ('A+ve','A+ve'), ('B+ve','B+ve'), ('O+ve','O+ve'), ('AB-ve','AB-ve'), ('A-ve','A-ve'), ('B-ve','B-ve'), ('O-ve','O-ve'), ) bloodgroup = models.CharField(max_length=100,choices=choice) choicea = ( ('Male','Male'), ('Female','Female'), ('Other','Other'), ) gender = models.CharField(max_length=100,choices=choicea) location = models.PointField(default=Point(0, 0),geography=True) profilepicture = models.ImageField(upload_to='images',default=None) def save(self, *args, **kwargs): self.latitude = self.location.y self.longitude = self.location.x super(CustomerProfile, self).save(*args, **kwargs) def __str__(self): return self.fullname -
django - When fields are flexible at creation time
models.py class MatchingPartner(models.Model): matching = models.ForeignKey( Matching, on_delete=models.CASCADE, related_name="matchingpartner" ) non_user_nm = models.CharField(max_length=45, null=True) non_user_gender = models.CharField( max_length=1, choices=NonUserGenderChoice.choices, null=True ) I want to create a "Matching Partner" model with data called "partner." [request "partner" data] "partner": [ { "non_user_nm": "1", "non_user_gender": "F" }, { "non_user_nm": "2", "non_user_gender": "F" } ] There's multiple instances of it going around the code, and if that's the case, "partner": { "non_user_nm": "Mina"} In this way, when data is passed over, fields other than "non_user_nm" would like to be stored as null. if request.data: partners = request.data["partner"] for partner in partners: MatchingPartner.objects.create( matching=matching_instance, non_user_nm=partner["non_user_nm"], non_user_gender=partner["non_user_gender"], ) What should I do? -
Django Search in Models with 3 fields
I have search fields, keyword, cdate_start, cdate_end. They can be null. What I want is if keyword entered, get results the only keyword contained results. If keyword not entered but cdate_start entered get items only greater than this cdate_start. Or keyword and cdate_end entered then get items only contains this keyword and less than cdate_end, and etc. I have to get all combinations like this. I tried something like this. if self.request.GET.get('feedback_s_keyword') is not None: keyword = self.request.GET.get('feedback_s_keyword') else: keyword = '' name_or = Q(author__name__icontains=keyword) surname_or = Q(author__surname__icontains=keyword) feedback_or = Q(feedback__icontains=keyword) if self.request.GET.get('feedback_s_cdate_start') is not None: cdate_start = self.request.GET.get('feedback_s_cdate_start') cdate_start = cdate_start.split('/') try: year_s = cdate_start[0] month_s = cdate_start[1] day_s = cdate_start[2] except: year_s = 2001 month_s = 1 day_s = 1 else: year_s = 2001 month_s = 1 day_s = 1 cdate_gte = Q(cdate__gte=datetime.date(year_s, month_s, day_s)) if self.request.GET.get('feedback_s_cdate_end') is not None: cdate_end = self.request.GET.get('feedback_s_cdate_end') cdate_end = cdate_end.split('/') try: year_e = cdate_end[0] month_e = cdate_end[1] day_e = cdate_end[2] except: year_e = 3000 month_e = 12 day_e = 31 else: year_e = 3000 month_e = 12 day_e = 31 cdate_lte = Q(cdate__lte=datetime.date(year_e, month_e, day_e)) feedbacks = Feedback.objects.filter(name_or | surname_or | feedback_or | cdate_gte | cdate_lte).order_by( "-cdate") But of course, if cdate … -
How to get UserProfile to reference the fields from UserModel?
Just an fyi, I'm pretty new to programming & Django in general. I've been teaching myself. Before I get into the problem, I'll share my Django code: models.py : class User(AbstractUser): # DATABASE FIELDS email = models.EmailField(("email address"), unique=True) REQUIRED_FIELDS = ['username'] USERNAME_FIELD = 'email' # META class Meta: verbose_name = "User" verbose_name_plural = "Users" # TO STRING METHOD def __str__(self): return "User " + str(self.id) + " - " + self.email class UserProfile(models.Model): # RELATIONSHIP user = models.ForeignKey( to = User, on_delete = models.CASCADE, related_name = "user_account" ) # DATABASE FIELDS first_name = models.CharField(max_length=100, verbose_name="First Name") last_name = models.CharField(max_length=100, verbose_name="Last Name") date_created = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Profile Created On") role = models.CharField(max_length=255, verbose_name="User Demographic") # META class Meta: verbose_name = "User Profile" verbose_name_plural = "User Profiles" # TO STRING METHOD def __str__(self): return self.first_name forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import User class AbstractUserCreationForm(UserCreationForm): class Meta: model = User fields = ('username', 'email') class AbstractUserChangeForm(UserChangeForm): class Meta: model = User fields = UserChangeForm.Meta.fields serializers.py from rest_framework import serializers from djoser.serializers import UserCreateSerializer, UserSerializer from . import models from .models import User, UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('id', 'email', 'username', … -
Django - Relationship Model
I need some help for database relationship and assignment. For instance, we have an employee model class EmployeeModel(models.Model): email = models.EmailField(max_length=150, unique=True) employee_no = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) def __str__(self): return str(self.first_name + ' ' + self.last_name) And let say an employee can have a group of task. But before that, we have to create a task in order to group it. This is a task model: class Task(models.Model): id = models.AutoField(primary_key=True) task_code = models.CharField(max_length=150, unique=True, editable=False) name = models.CharField(max_length=150) type = models.CharField(max_length=20, editable=False) description = models.CharField(max_length=250) def __str__(self): return self.name We then now group the tasks. class GroupTask(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150) group_code = models.CharField(max_length=150, unique=True, editable=False) task = models.ManyToManyField(Task, blank=True) def __str__(self): return self.name So after grouping, we now have a list of task in group task model. For example, in Group 1, we have Task 1, and Task 2. This group of task should also be in a project, so we have to connect this group of task in a project model. Because each projects should have a group of task. class Project(models.Model): code = models.CharField(max_length=20, editable=False, default=auto_generated_code) name = models.CharField(max_length=100) description = models.CharField(max_length=250) group_task = models.ManyToManyField(GroupTask, blank=True) def … -
django celery vs multithreading vs asyncio
I have a Django application that allows users to upload a file and my application will convert the file to the user's specifications. Currently, if multiple users try to convert files at the same time, the process will go something like this Process user 1s files converting... done Process user 2s files converting... done It's essentially acting as a queue. Clearly, this is inefficient when multiple users are trying to convert files. I have looked into things like multithreading, celery, asyncio, etc. I can't seem to pick out the differences between the 3. What is the difference and which would be best so users on my site can convert files without waiting for other users' files to finish? Thanks :)