Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple database foreign keys
I am trying to implement multiple database support for my django (version 1.11) app. For that purpose I have included in my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'labrin_dbase', 'USER': 'labrin_admin', 'PASSWORD': 'ndzwwZHv63STuvAF?C_$L@j@*@epZXaX', 'HOST': 'localhost', 'PORT': '5432', }, 'comment': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'labrin_dbase_comments', 'USER': 'labrin_admin_comments', 'PASSWORD': 'adzwaTHv63STuvAF!C_$L@j@*@epZXaY', 'HOST': 'localhost', 'PORT': '5433', } } DATABASE_ROUTERS = [ 'labrin_task.comment_router.CommentRouter', ] And my database router is configured as below: class CommentRouter(object): def db_for_read(self, model, **hints): if model._meta.db_table == 'todo_comment': return 'comment' return None def db_for_write(self, model, **hints): if model._meta.db_table == 'todo_comment': return 'comment' return None def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): if model_name == 'comment': return db == 'comment' return None Models in my "todo" app(which is only app in project): from django.db import models from django.contrib.auth import get_user_model UserModel = get_user_model() class Todo(models.Model): name = models.CharField(max_length=64) description = models.TextField() author = models.ForeignKey(UserModel, on_delete=models.CASCADE) deadline = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): todo = models.ForeignKey(Todo, on_delete=models.CASCADE) author = models.ForeignKey(UserModel, on_delete=models.CASCADE) text = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) class ShareTodo(models.Model): todo = models.ForeignKey(Todo, on_delete=models.CASCADE) with_user = models.ForeignKey(UserModel, on_delete=models.CASCADE) comment_allowed = models.BooleanField(default=False) When I remove comment database and DATABASE_ROUTERS from settings.py, my app is working … -
Django format DecimalField in annotation
Is it possible to format a DecimalField in an annotation similar to intcomma template tag? class MyModel(models.Model): number = models.DecimalField(max_digits=9, decimal_places=2, default=D('0')) For example if instance.number = Decimal('1000') the formatted number would be a string: 1,000.00 -
IntegrityError: UNIQUE constraint failed: usermanager_userprofile.email_address
I'm developing a registration app that use User model with OneToOneField. models.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.db import models from django.dispatch import receiver class UserProfile(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) USER_TYPE_CHOICES = ( ('Citizen', 'Citizen'), ('Private Company', 'Private Company'), ('Public Company', 'Public Company'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField('First name', max_length=30) surname = models.CharField('Last name', max_length=150) gender = models.CharField('Gender', max_length=1, choices=GENDER_CHOICES) date_of_birth = models.DateField('Date of birth', null=True) user_type = models.CharField('Typology', max_length=20, choices=USER_TYPE_CHOICES) profile_image = models.ImageField('Profile image', upload_to='users_upload/profiles/%Y/%m/%d') company_name = models.CharField('Company Name', max_length=75, blank=True, null=True) fiscal_data = models.CharField('Fiscal data', max_length=200, unique=True) city = models.CharField('City', max_length=150) address = models.CharField('Address', max_length=200) postcode = models.CharField('Zip Code', max_length=50) country = models.CharField('Country', max_length=75) telephone_number = models.CharField('Telephone', max_length=20) email_address = models.EmailField('Email', unique=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() forms.py from django import forms from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'password1', 'password2') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = [ 'name', 'surname', 'gender', 'date_of_birth', 'user_type', 'profile_image', 'company_name', 'address', 'postcode', 'city', 'country', 'telephone_number', 'email_address', 'fiscal_data', … -
How to save the link of the file uploaded in the database and the actual file in a specific folder in django
I have a form with an upload option (filefeild). The file uploaded is saved directly in the databse. I need to store the file in a specific folder and the link to the file on the database For now the uploaded file is directly stored in the database table def uploaddata(request): if request.method == 'POST': form = dataform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = dataform() return render(request, 'uploaddata.html', { 'form': form }) This is my model ```python class Metadataform(models.Model): Type = models.CharField(max_length=100, blank=True) Vars = models.CharField(max_length=2000, blank=True) Error = models.CharField(max_length=2000, blank=True) Document = models.FileField(upload_to="store/Data/") And also i want the files to be stored outside the media folder somewhere on the server in a given path. could you help me define the Media path ```python MEDIA_ROOT = '../store/Data/' MEDIA_URL = 'store/Data/' -
How to set formatter programatically?
I am trying to format my logger, for which I defined a formatter in the settings life. However I cannot manage to figure out how to set it as the logger's handler's formatter: def mylogger(name): logger = logging.getLogger(name) handler = RotatingFileHandler(logger_path, 'w') handler.setFormatter(?????) logger.addHandler(handler) return logger Note I need to do this programatically. I can't declare the handler in the setting file because RotatingFileHandler may need to be passed some additional arguments. So the question is: in handler.setFormatter(?????) how do I get the formatter (by name, for example, just how loggers are retrieved) I defined in the settings file? -
How to get another field value from model if I know first field value?
I am trying to learn django and faced problem accessing models. I have model in models.py that look like this: class Countries(models.Model): Country = models.CharField(max_length=200) PPP = models.DecimalField(max_digits=15, decimal_places=10) def __str__(self): return self.Country Now in views.py I want to make some calculations based on user input. User will choose value from first field (Country) and I need to find second field value (PPP) based on that. It means that I have data structured something like that: Country | PPP ---------------- Lithuania | 0.45 Germany | 0.86 Estonia | 0.55 Spain | 0.77 So I will know country and I will need to access its PPP. How should I do it? Because various solutions I tried gives me an error. Lats solutions I tired: pVal = str(form.cleaned_data['Country']) country = Countries.objects.first() pValKof = getattr(country, pVal) Based on my research I feel I should be somewhere near the solution, but I just can't understand getattr completely. Or maybe there is some other way to achieve this? -
Django GROUP BY multiple fields with postgres
I'm having this model: class Tag(models.Model): name = models.CharField(max_length=100) random_number = models.IntegerField() def __str__(self): return self.name and I want to aggregate it by both id and name and count random_number. Typically, I would use: from tryin.models import Tag from django.db.models import Count print(Tag.objects.all().values('pk','name').annotate(Count('random_number')).query) SELECT "tryin_tag"."id", "tryin_tag"."name", COUNT("tryin_tag"."random_number") AS "random_number__count" FROM "tryin_tag" GROUP BY "tryin_tag"."id", "tryin_tag"."name" which is fine, but instead I got different SQL query: SELECT "tryin_tag"."id", "tryin_tag"."name", COUNT("tryin_tag"."random_number") AS "random_number__count" FROM "tryin_tag" GROUP BY "tryin_tag"."id" which lacks grouping by name. This query doesn't work, because name has to be either grouped or aggregated. This happening solely because I have my database in settings.py set to django.db.backends.postgresql. I have tested this on fresh django 2.2.5. I don't have much experience with postgres, so I guess this might be normal. What is correct way to group by 2 fields? Is it possible to run it via Django ORM and not RawSql? -
New model using signals
models.py class Customer(models.Model): name = models.CharField(max_length=16) description = models.CharField(max_length=32) Is it possible to have new model using signals . For example if i save above model it must give me below model. def create_customer(sender, instance, created, **kwargs): class Newname(models.Model): customername = models.CharField(max_length=100) signals.post_save.connect(receiver=create_customer, sender=Customer) -
Django: How much overhead does an installed app add to each request?
I want to use factory_boy for test data in my unit tests, but I'm worried about overhead of having it installed in the production site. While trying to implement a different (unrelated) feature a while back, I discovered that code files seem to be loading once early in the request process, then executing again at the proper place in the request process. For example: some code that checks permissions was executing twice during each request - the first time, request was "None"; the second time, request was a valid object. I finally added a check for "if request is not None:" and that solved my problem. But it seems that perhaps some (most?, all?) code in the site is being processed - call it "compiled", if you will - on each request. Is that true? Perhaps it is only the apps specified in INSTALLED_APPS that get loaded in such a way. I have installed "faker" in my packages folder (in Docker), but did not include it in INSTALLED_APPS, yet I am able to "import" classes from faker and use them in a management command I wrote. I'm thinking that maybe that will make it not add overhead to each request … -
django no reverse match with filtered ListView
I'm trying to work out how to pass a url from the template now that I have set up a filter on a ListView. Here is the view where I am overriding get_queryset to filter for the 'area' attribute of my Project model. This works well, however, before setting up the filtering, everything worked nicely, but of course now that I have a dynamic variable added to the url, the reverse lookup no longer works. In an ideal world it would pass something that would get the unfiltered list view, as I also need this for the dropdown links. Here is my view: class ProjectListView(ListView): model = Project def get_queryset(self): self.area = get_object_or_404(Area, name=self.kwargs['area']) return Project.objects.filter(area=self.area) and here is my urls for this app: urlpatterns = [ path('<area>/', ProjectListView.as_view(), name='project-list'), path('project-create/', ProjectCreateView.as_view(), name='project-create'), path('<slug:slug>/update/', project_update_view, name='project-update'), path('search/', search, name='search'), ] here is the url in the template: <a href="{% url 'project-list' %}"> <h2>Service Integration Development Project Portal</h2> </a> Which no longer works as it is expecting 'area' in some way. here is the error I am getting: NoReverseMatch at /si/Operational Improvement/ Reverse for 'project-list' with no arguments not found. 1 pattern(s) tried: ['si/(?P<area>[^/]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/si/Operational%20Improvement/ Django … -
Catch exception at a lower level but get the trace up to request level
A new method that is used in multiple points is giving me some trouble so I want to catch any exception it throws and silently handle it. def mymethod(self, *args, **kwargs): try: # ... except: log_mymethod_error() return False def log_mymethod_error(): logger = logging.getLogger('mymethod_logger') logger.addHandler(RotatingFileHandler(log_path, 'w')) logger.exception('mymethod error') However this will track the trace only at the scope of mymethod. I would like to see the whole traceback up until the request level, so I can see exactly how it was produced, and access information such as path, request method, user... I can't just catch the exception in the view. It needs to be caught within the method instead and return a dummy value so that the pieces using mymethod can go on with the execution and ignore whatever mymethod was supposed to run. -
Call function from another function NameError: name 'MethodName' is not defined
I am new in python. How can call function from another function. Here is an example : def RunNew2N3(fromempid,toempid,fromdate,todate,fromcscid='',tocscid=''): cursor = connection.cursor() try: cursor.callproc('[dbo].[SPRUN]',[fromempid,toempid,fromdate,todate,fromcscid,tocscid]) finally: cursor.close() def create(self,request): tsmt = request.data.get('tsmt') fromempid = tsmt['empid'] toempid = tsmt['empid'] fromdate = tsmt['tdate'] todate = tsmt['tdate'] serializer = TsmtSerializer(data=tsmt) if serializer.is_valid(): tsmt_saved = serializer.save() RunNew2N3(fromempid,toempid,fromdate,todate) ==>Call from here return Response({"result":"TSMT '{}' created successfully".format(tsmt_saved.tdate),"status":"success"}) else: return Response({"result":"'{}'".format(serializer.errors),"status":"fail"}) I put the call function on top and why I can't call that.I got the error message NameError: name 'RunNew2N3' is not defined -
How to make the python scripts which i run using command prompt and host/execute online?
Please give me right direction to host a django application/host a python script which are using BeautifulSoup python library and works well on executing with window command prompt. I want to run the python code online in some platform and get the output but doesnot figure how to do it. If i use django to host python web application then how i can use django to host web application. If anybody has worked on django plz guide me. -
'Cannot add foreign key constraint' in django migration
I try to add a 1:n reltationship but the foreign key constraint could not be added. class PlatformEnv(models.Model): id = models.AutoField(db_column='ID', primary_key=True) tag_type = models.ForeignKey(Tagtypes, models.DO_NOTHING, db_column='Tag_Type', blank=True, null=True) class Tagtypes(models.Model): name = models.CharField(max_length=50, blank=True, null=True) This is the generated migration: migrations.AddField( model_name='platformenv', name='tag_type', field=models.ForeignKey(blank=True, db_column='Tag_Type', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='polls.Tagtypes'), ), The DB shows the following error: Error in foreign key constraint of table adtech_mandators/#sql-5de0_4cf61_130: FOREIGN KEY (`Tag_Type`) REFERENCES `TagTypes` (`id`): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. The tables: CREATE TABLE `TagTypes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; CREATE TABLE `PlatformEnv` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Tag_Type` int(11) DEFAULT NULL, PRIMARY KEY (`ID`), ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; -
how to generate python template file ? eg used django-admin command
i want to use my custom python command to generate some default python template file, eg in django project uesd the command django-admin startproject xxx then some default py files generated in the Folder how should i do -
How to install django in miniconda?
i want to develop django rest API in windows. Due to some reason i have to use miniconda in my system. My project location is c:/users/noman/dev/cardionic/ . i create virtualenv 'env' using miniconda which is created in c:/user/noman/miniconda3/envs/env instead of base folder. I activate my env using 'activate env' and install django. I create new django project using 'django-admin startproject cardio' . when i run 'python manage.py runserver' it generates "ModuleNotFoundError: No module named 'sqlparse' " i have done my best but could not resolve this issue. Thanks in advance -
Django cannot login (login view does not return set-cookie header for sessionid at login)
I am getting the following response from the Django (2.2) default login view: Request URL: https://api.n.exchange/en/accounts/login/?next=/en/referrals/ Request Method: GET Status Code: 200 OK Remote Address: 104.25.23.99:443 Referrer Policy: no-referrer-when-downgrade Cache-Control: max-age=0, no-cache, no-store, must-revalidate CF-RAY: 51105b439e71b50e-VNO Connection: keep-alive Content-Encoding: br Content-Language: en Content-Type: text/html; charset=utf-8 Date: Wed, 04 Sep 2019 13:37:09 GMT Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Expires: Wed, 04 Sep 2019 13:37:09 GMT Server: cloudflare Set-Cookie: csrftoken=BHfEypgp6ux4FvQr14G06DQnqHjRL0tXZYP4Cg2b67naaFkxFw29g0C5UVettETb; expires=Wed, 02 Sep 2020 13:37:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax Transfer-Encoding: chunked Vary: Cookie, Origin X-Frame-Options: SAMEORIGIN X-NewRelic-App-Data: PxQGUlFVCwoGR1JTDwQFX1IAFB9AMQYAZBBZDEtZV0ZaCldOdxRdARBfWA9JB1JSXgMOTFReWRIWWFQdAxMXCh4UUQdPSw5+XAJQD2cIVhVKUVIVRE8IHwBKUVAPBw5QVggOBltfUVYDUw5WFBUFHhFVAFAABABbAQEGWFYGWQVSRk0EVl1EAzk= Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,he;q=0.7,lt;q=0.6,de;q=0.5 Connection: keep-alive Cookie: __cfduid=d76f7b7d2a1caa6948456ad6829dc25991553698344; _ga=GA1.2.2123122031.1553698346; _ym_uid=1553698347983819119; _ym_d=1553698347; crisp-client%2Fsession%2F6eb9ed9e-2c8b-48e8-a0ce-62c3ce81fb61=session_76921095-b26c-4790-a968-82cf111e3940; _hjid=e834477e-35c2-4ef9-aacd-5fb2d644ae2c; crisp-client%2Fsocket%2F6eb9ed9e-2c8b-48e8-a0ce-62c3ce81fb61=1; _gid=GA1.2.1927749960.1567447617; USER_TZ=Europe/Vilnius; django_language=en; _ym_isad=1; _ym_visorc_42222484=w; _ym_visorc_45642111=w; csrftoken=BHfEypgp6ux4FvQr14G06DQnqHjRL0tXZYP4Cg2b67naaFkxFw29g0C5UVettETb; _gat=1 Host: api.n.exchange Referer: https://api.n.exchange/en/accounts/login/?next=/en/referrals/ Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 X-NewRelic-ID: VQUAV1VaDhADVVlXBQgBVw== next: /en/referrals/ As you can clearly see, the set-cookie header for the sessionid which represents the authenticated Django session is missing. What could be the cause? (at first, I was thinking the reason is that we have a self signed HTTP certificate behind Cloudflare but we have migrated to a valid letsencrypt certificate and removed cloudflare to test it, but the problem persists). Thanks! -
django Subtract two time to retrieve restive time
Hello when i try to substract two datetime.time i get error the error is : unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' my views.py is : if(allreservertion.heuredebut== form.cleaned_data['heuredebut']): x= dt.datetime.strftime(form.cleaned_data['heuredebut'] - form.cleaned_data['heurefin']) y= dt.datetime.time(allreservertion.heuredebut + allreservertion.heurefin) print(x) print(y) print("meme heure début") return render(request,'registration/plan.html') -
Login via Phone field in Extended User Model
I have used django user model and extended it to add a phone field. I then wrote an authentication back end to log the user in via phone number. I was able to use either username or email to login but cannot access phone number field from extended user model. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phonenumber = models.CharField(max_length=10) backends.py class AuthenticationBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): usermodel = get_user_model() print(usermodel) try: user = usermodel.objects.get(Q(username__iexact=username) | Q( email__iexact=username)) if user.check_password(password): return user except user.DoesNotExist: pass backend.py is what I used to implement login via username or email but I couldn't do it for phonenumber in extended user model. -
Importing Errors
I am getting errors in almost all imports please help. i'm using django 2.2.5, python 3.7, but getting errors in unresolved import'django.contrib' ,unresolved import'django.urls',unresolved import'django.shortcuts' etc from django.contrib import admin from django.urls import path,include urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls), ] from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") Message=No module named 'django' File "C:\Users\Sharf\Desktop\python projects\p1\calc\urls.py", line 1, in <module> from django.urls import path -
Unable to Post multiple curl requests to django endpoint with uWSGI and nginx
I am unable to send multiple curl requests to django endpoint. Single requests are processed but multiple curl requests are met with a 500 error. Need help!!! nginx/sites-enabled/uvlearn.conf: upstream django { server unix://home/clyde/Downloads/automatic_annotator_tool/django_app/socket_101.sock; keepalive 32; } server { listen 8000; server_name #; # substitute your machine's IP address or FQDN charset utf-8; client_max_body_size 75M; # adjust to taste location /static { alias /home/clyde/Downloads/automatic_annotator_tool/django_app/static; # your Django project's static files - amend as required } location / { uwsgi_pass django; include /etc/uwsgi/sites/uwsgi_params; # the uwsgi_params file you installedi proxy_read_timeout 300; proxy_connect_timeout 300; proxy_http_version 1.1; proxy_set_header Connection ""; keepalive_requests 100; } location /queried_data { alias /home/clyde/Downloads/automatic_annotator_tool/data/queried_data; } location /upload_data { alias /home/clyde/Downloads/automatic_annotator_tool/data/upload_data; } location /nginx_status { stub_status on; } }` I am able to send a single curl command using: ```curl -X POST -H "Content-Type: application/json" -d '@8_19_35am_1566893975637_1.json' http://13.232.246.51:8000/search/upload_rtsp/``` But when I send multiple curl commands using: ```curl -X POST -H "Content-Type: application/json" -d '@8_19_35am_1566893975637_1.json' -d '@8_19_35am_1566893975638_1.json' http://13.232.246.51:8000/search/upload_rtsp/ I get server 500 errors. I checked the nginx access logs and error logs. All I can see is a 500 error registered when I make multiple requests and a 200 pass when I make a single request. What controls should I add to … -
How to handle multiple forms in django
Here i have two forms within my single page.I have a list of categories info in some table and i have two different action with POST request.One is to delete the single category object and another is to delete the checked objects. But deleting the single object is not working after placing two forms together.Before there was no form for deleting selected categories so the deleting the single object was working fine with the modal but when i used two form then even if i click the delete single category link then it is performing the delete selected category view and says no category selected. How can i handle two forms here.I have given two different names in a submit button and two different actions also. def delete_category(request, pk): category = get_object_or_404(Category, pk=pk) if request.method == 'POST' and 'single-delete' in request.POST: category.delete() messages.success(request, '{} category deleted.'.format(category.title)) return redirect('view_categories') else: messages.error(request,'Invalid request') def delete_selected_categories(request): selected_categories = Category.objects.filter(id__in=request.POST.getlist('categories')) if selected_categories: if 'delete_selected' in request.POST: count = selected_categories.count() selected_categories.delete() messages.success(request, '{} categories deleted.'.format(count)) return redirect('view_categories') else: messages.info(request, 'No categories selected.') return redirect('view_categories') template <div class="table-responsive"> <form action ="{% url 'delete_selected_categories' %}" method="post"> {% csrf_token %} <table> {% for category in categories %} <tr> … -
Django: bulk update from a list of dicts without constructing the whole query set
I have a list which contains dicts. Something like: [{'id': 0, 'price': 20}, {'id': 1, 'price': 10}] # a few thousands of elements how can I update corresponding models without constructing the whole QuerySet? -
django app deployment in apache not working from an anaconda3 environment in windows
Hello guys I was trying to deploy my django app in apache and configured an ssl license. I cannot get any rest framework apis from django only the wampserver main page. I think my issue is that I am using a conda environment and not a virtualenvironment and I couldn't find any links to configure it for windows. Can someone guide me through this? httpd.conf # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/access_log" # with ServerRoot set … -
How to run wsgi along the side of the daphne for django channels
i am using django channels in my project using using official django channels v2, my simple channels app is completed and working fine if run python manage.pr runserver but i want to run django channels in different port so i am now using daphne using daphne my_project.asgi:application --port 8001 it working fine in 8001 port and i also run python manage.py runserver in another terminal parallely working fine. now my both channels in 8001 and django in 8000 port working correctly but my runserver command running ASGI/Channels instead of wsgi development server, Starting ASGI/Channels version 2.2.0 development server at http://127.0.0.1:8000/ settings.py ASGI_APPLICATION = 'my_project.routing.application' WSGI_APPLICATION = 'my_project.wsgi.application' if i debug any function in views.py request, it is ASGI request instead of django wsgi request my question is: how to get django request instead of ASGI or if we install django channels every request become ASGI request? what is the use of the python mange.py runworker command