Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - if statement in template not working
I have a Django site using the following models: class User_Posts(models.Model): message = models.TextField(max_length=CONFIG['MODEL_SETTINGS']['User_Posts']['message_length']) post_date = models.DateTimeField(auto_now_add=True) character = models.ForeignKey(Characters, related_name='user_posts', on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='user_posts', on_delete=models.CASCADE) non_bot = models.CharField(max_length = 10, default = 'user') class Bot_Replies(models.Model): message = models.TextField(max_length=CONFIG['MODEL_SETTINGS']['Bot_Replies']['message_length']) character = models.ForeignKey(Characters, related_name='bot_posts', on_delete=models.CASCADE) post_date = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='user_origin', on_delete=models.CASCADE) non_bot = models.CharField(max_length = 10, default = 'bot') in my view, i am passing: user_posts = User_Posts.objects.filter(created_by = request.user, character__pk = pk) bot_posts = Bot_Replies.objects.filter(created_by = request.user, character__pk = pk) posts_list = sorted( chain(user_posts, bot_posts), key = lambda x: x.post_date, reverse = False )[-10:] and passing 'posts_list' to the template as 'posts'. My template is looping: {% for post in posts %} <div class="card mb-2"> <div class="card-body p-3"> <div class="row"> {% if posts.non_bot == 'user' %} <div class="col-2"> {{ post.created_by }} </div> {% else %} <div class="col-2"> {{ post.created_by }} </div> {% endif %} <div class="col-2"> {{ post.message }} </div> </div> </div> </div> {% endfor %} but the if statement never works, it always passes to the "else" clause. If I print out the variable non_bot value on my screen, it shows the correct bot/non-bot values but for some reason I cannot access them in the template. … -
Random Line of Carets in HTML Page
I'm making a web app with Django, bootstrap, HTML, CSS, and JS. I'm generating some API results to a table using template building in Django. In between an H1 for the table and the table, there is this random line of carets. When I inspect them, it can't find an element in the DOM. Here's the code for the h1 and table start: {% if body %} <a href="#results"></a><h1 style="display: flex;flex-direction: column;justify-content: center;text-align: center;">RESULTS</h1> {% endif %} <table id="searchResults" class="table .table-hover" width="100%"> And here's a screenshot of the issue: -
Where to start for a course selection program guide?
I have a project for school where I need to make course selection tool that tells the user what classes they should take all four years of high school based on interests and selected rigor. I also wanna incorporate machine learning somehow but don't really know much about it. Any suggestions for how I could go about developing this website what logic I need to implement really just anything. I've got about a month to do this. Any guidance is helpful. Im not looking to create anything too complex but tutorials for how I could go about this would be nice too. Thanks :) I tried searching the internet but most tutorials seem to overwhelming or complex -
Django Template comparing value issues
Good day! I would like to ask why this code is not returning True even if the condition is equal in Django template. I have tried displaying the output of each and confirmed that the if-else condition is being satisfied. Please see attached picture for the sample output {% if core.username == username %} Same. ---- {{ core.username }} == {{ username }} {% else %} Different. --- {{ core.username }} == {{ username }} {% endif %} -
How to get socialaccount (discord information) django allauth
So i don't know how to get the discord information from allauth So can any one help me This is my settings SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } }, 'discord': { 'SCOPE': [ 'identify', 'email', 'guilds' ], 'AUTH_PARAMS': { 'access_type': 'online', } } } -
Django login form on main page
How can i fix my login section, o cannot see input fields on my home page site. I want to have main home site with posts and small window for login on the right site: enter image description here def home(request): loginform= auth_views.LoginView.as_view(template_name='site/home.html') context = { 'posts': Post.objects.all(), 'form': loginform } return render(request, 'site/home.html', context) home.html {% extends "site/base.html" %} {% load crispy_forms_tags %} {% block content %} ... {% endblock content %} {% block userpanel %} <div class="content-section"> {% if user.is_authenticated %} ... {% else %} {% load crispy_forms_tags %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Zaloguj</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Zaloguj</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Potrzebujesz konta? <a class="ml-2" href="{% url 'register' %}">Zarejestruj</a> </small> </div> </div> {% endif %} {% endblock userpanel %} I want to have interactive home page with content and login section -
Upload data from excel to mysql
I am working with django, I receive an excel file through an endpoint to save its data in the database very quickly, as quickly as possible, the excel file has numerical data, it has around 250 columns and 10 thousand rows. I plan to save each measurement in the database with a reference to know which measurements are from which excel. So how can I solve this problem, I have tried with pandas but it is taking a long time, or what architecture can I implement for this problem? -
Django Redis cache get expire time
Is it possible to get key's expire time in Django using Redis cache? Something like: from django.core.cache import cache cache.get_expire('mykey') # 300 (seconds) I tried: cache.ttl('my_key') getting an error AttributeError: 'RedisCache' object has no attribute 'ttl' -
django SSO with PingFederate oauthlib.oauth2.rfc6749.errors.InvalidGrantError
so I have this .... from requests_oauthlib import OAuth2Session auth_url = settings.DCM_SSO_URL + '/as/authorization.oauth2' client_id = settings.DCM_SSO_CLIENT_ID client_secret = settings.DCM_SSO_API_KEY redirect_uri = 'http://<FQDN>/ssoauth' scope = "email groups openid profile" token_url = settings.DCM_SSO_URL + '/as/token.oauth2' userinfo_url = settings.DCM_SSO_URL + '/idp/userinfo.openid' def oauthlogin(request): user = request.session.get('user') if not user: intuauth = OAuth2Session( client_id=client_id, redirect_uri=redirect_uri, scope=scope) authorization_url, state = intuauth.authorization_url(auth_url) request.session['oauth_state'] = state request.session.save() return HttpResponseRedirect(authorization_url) def oauthcallback(request): intuauth = OAuth2Session(client_id, state=request.GET.get("state")) print(dir(intuauth)) token = intuauth.fetch_token( token_url=token_url, client_secret=client_secret, code=request.GET.get("code")) request.session['oauth_token'] = token request.session.save() u = intuauth.get(userinfo_url) return JsonResponse(u) but now I'm stuck with a ... oauthlib.oauth2.rfc6749.errors.InvalidGrantError after logging in ... what am I missing? -
500 Internal error when adding a new third-party app in INSTALLED_APPS Django Apache2
I'm stuck with a weird problem when I add a new app name in my INSTALLED_APPS in the settings.py file I get a 500 internal error. This error happens only in production, in my local machine everything is working fine. If I remove the name of the app everything works fine again. What I've already tried but didn't change anything: Setting DEBUG to Ture. Experiment with different types of apps (ex tinyMCE, adminsortable, grappelli, debug_toolbar etc.) Removing and re-installing these apps. Checking apps compatibility (with Django and Python versions or within their own dependencies) Checking the error.log file If I check the error.log file I always get different outputs depending on the app I was adding to the settings.py file. I will leave here the error.log output that I get when trying to use Django adminsortable which is the app that I'm actually trying to use. The error is long that I've put it here And this is my INSTALLED_APPS in settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', "users.apps.UsersConfig", "crispy_forms", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "taggit", "search", "photogallery", "django_filters", 'adminsortable', 'django_cleanup.apps.CleanupConfig', ] And here are the packages that I've already installed and their dependencies. attrs==19.3.0 Automat==20.2.0 blinker==1.4 certifi==2020.4.5.1 chardet==3.0.4 click==7.1.2 cloud-init==20.4 … -
Can't get background image to work properly in Django using %static%
This is the code for a website which changes background image when refreshed but am not able to modify it to work on Django I have written the code for a website which changes it's background image when refreshed. It worked before but after trying it in Django, I tried to use %static% to display images now it's not changing the background image. function changeBackground() { var imagess = ["{% static \"images/ESOTSM.jpg\" %}","{% static \"images/arrival.jpg\" %}","{% static \"images/arrival1.jpg\" %}","{% static \"images/asclearasday.jpg\" %}","{% static \"images/batmanblue.jpg\" %}"] var randomNumber = Math.floor(Math.random() * 5); document.body.style.backgroundImage = x = 'url(' + imagess[randomNumber] + ')'; console.log(imagess[randomNumber]); console.log(x) } window.onload = changeBackground; body{ background-image:url(".jpg"); background-size:cover; background-position:center; background-repeat:no-repeat; background-color:black; overflow-x: hidden; } -
Cannot import rq use_connect on docker container
I have Django application running on dokku and keep getting an rq import error message once I link the postgresql database to the dokku app. I do not understand why I am getting this error now, as I have documented the steps I took to deploy this app in the past, and I followed them exactly to deploy it again. I deploy my dokku app, then I get blue screened because it relies on redis and postgres. From there I link redis, which does not show an error on redeploy. Then I link my new postgres database and it throws the following error: 20:12:02 system | web.1 started (pid=31) 20:12:02 system | default_worker.1 started (pid=35) 20:12:02 system | archive_expired_jobs.1 started (pid=37) 20:12:02 system | badgr_sync.1 started (pid=41) 20:12:08 default_worker.1 | Traceback (most recent call last): 20:12:08 default_worker.1 | File "manage.py", line 22, in <module> 20:12:08 default_worker.1 | main() 20:12:08 default_worker.1 | File "manage.py", line 18, in main 20:12:08 default_worker.1 | execute_from_command_line(sys.argv) 20:12:08 default_worker.1 | File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line 20:12:08 default_worker.1 | utility.execute() 20:12:08 default_worker.1 | File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 395, in execute 20:12:08 default_worker.1 | self.fetch_command(subcommand).run_from_argv(self.argv) 20:12:08 default_worker.1 | File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 244, in fetch_command 20:12:08 default_worker.1 | klass … -
while running django command from docker compose it says "sh: django: not found"
I created docker image and when i run docker-compose run --rm app sh -c "django --version" the output is sh: django: not found requirements.txt:- Django>=3.2.4,<3.3 djangorestframework>=3.12.4,<3.13 Dockerfile:- FROM python:3.9-alpine3.13 LABEL maintainer="ayush270702" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV="true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user docker-compose.yml:- version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" After running docker build . and docker-compose build django is getting installed and image is getting created successfully, but when I run docker-compose run --rm app sh -c "django --version" output: (https://i.stack.imgur.com/RUx40.png) I tried removing virtual env from Dockerfile but output was same FROM python:3.9-alpine3.13 LABEL maintainer="ayush270702" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN pip install --upgrade pip && \ pip install -r /tmp/requirements.txt … -
name 'ObjectNotExist' is not defined
error ObjectNotExist The following error occurs when converting HTML to PDF name 'ObjectNotExist' is not defined veiws.py def cart(request, total=0, quantity=0, cart_item=None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, is_active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity except ObjectNotExist: # 'ObjectDoesNotExist' pass context = { 'total': total, 'quantity': quantity, 'cart_items': cart_items, } return render(request, 'store/cart.html', context) -
Occlude foreign PK from HTML value attribute Django Crispy Forms
When rendering a choice form field of ModelB with django crispy forms, the foreign key id of modelA is available in the HTML attributes of the choice objects. My understanding is that the primary key id of modelA is sensitive and should not be shown to the users. <select name="modelB" class="select form-select is-invalid" id="id_modelA"> <option value="FK1" selected="">Choice 1</option> <option value="FK2">Choice 2</option> ... <option value="FK5">Choice 5</option> </select> Ideally, I could use modelA.uuid as a proxy for the true modelA.id in the html attributes but crispy forms doesn't want to allow this. <select name="modelB" class="select form-select is-invalid" uuid="uuid_modelA"> <option value="uuid1" selected="">Choice 1</option> <option value="uuid2">Choice 2</option> ... <option value="uuid5">Choice 5</option> </select> Model A: class modelA(models.Model): user_instance = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=30) uuid = models.UUIDField(default=uuid_lib.uuid4, unique=True, editable=False, primary_key=False) Model B: class modelB(models.Model): user_instance = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) modelA_instance = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='modelB') uuid = models.UUIDField(default=uuid_lib.uuid4, unique=True, editable=False, primary_key=False) I've tried overriding the choices widget using a construction like below but crispy rejects any user input because the modelA.uuid that is pass into the HTML choice value is not a foreign key that matched the queryset: modelA_queryset = modelA.objects.filter(user_instance=self.user) self.fields['modelA'].queryset = modelA_queryset self.fields['modelA'].widget.choices = [(modelA.uuid, modelA.__str__) for modelA in modelA_queryset] Using this construction allows me … -
Как сделать чтобы по ID находить api данные в urls [closed]
У меня есть джанго проект мне нужно через ссылку находить нужные api данные enter image description here Я пробовал почти все, , я использовал в папке Views get, get_queryset,response и тд, но не работала возможно я что-то не понимаю -
Django Model.objects.get - object is not iterable
I am building a Django app with a user model. the model: models.py class User(AbstractUser): phone = models.CharField(max_length=20, blank=False) is_verified = models.BooleanField(default=False) address = models.CharField(max_length=200) city = models.CharField(max_length=50) country = models.CharField(max_length=50) is_verified = models.BooleanField(default=False) serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name') views.py class UserProfile(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get_queryset(self): return User.objects.get(id=self.request.user.id) when going to the url /profile i get an error: 'User' object is not iterable I validated that i have a User in the database with id = 1 and also that self.request.user.id is int(1) appreciate any insight I tried to get the user profile data from the object user. i was expecting to get a result with the user serialized i.e {id: 1, first_name="X", last_name="Y"} i actually got a response with 'User' object is not iterable -
If I Restart the docker, celery worker stops consuming tasks
I am having weird issue with Celery and Docker. As a broker I am using SQS, it works fine if I clear the docker cache and start the docker engine fresh. but if I rebuild the docker and start it again, celery worker stops consuming tasks. Worker works fine outside of the container (i.e in my local environment) Here are the versions I am using. celery[sqs]==5.2.* django==4.1.* pycurl==7.44.* my docker-compose celery_worker: restart: always build: context: ./backend dockerfile: Dockerfile.dev volumes: - ./backend:/usr/src/app/ env_file: - ./.env.dev command: sh -c "celery -A app.celery:celery_app worker --loglevel=INFO" depends_on: - api -
AttributeError 'str' object has no attribute 'get' json from file
Iam traying to get boolean value by key if the value is true there is no issue but if the value == false i got error AttributeError 'str' object has no attribute 'get' this problem i faced alot even when i get data from db main code if model.check_login(request): ad = User.objects.get(UID=login_user_uid(request)) per = {"perto": False} status = per['perto'] print(f'sdf {type(status)}') print(f'sdf {status}') if per['perto'] is True: return render(request, "users/add_user.html", {}) else: return reverse('home') else: return redirect(reverse('login')) output sdf <class 'bool'> sdf False Internal Server Error: /add_user Traceback (most recent call last): File "C:\workstation\amon_env\envo\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\workstation\amon_env\envo\Lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\workstation\amon_env\envo\Lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: ^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'get' -
Why I'm getting this error:You're accessing the development server over HTTPS, but it only supports HTTP.?
I'm using Django==3.1, I know it is backdated but I need solution. Whenever I go to run my website I'm get this error: Django version 3.1, using settings 'alef.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [06/May/2023 00:17:02] code 400, message Bad request version ('å\x13q\x90O¢5\x98£\x02}\x8dNÅ[Di\x00\x05\x00\x03\x02h2\x00\x1b\x00\x03\x02\x00\x02\x00-\x00\x02\x01\x01\x00+\x00\x07\x06zz\x03\x04\x03\x03\x00') [06/May/2023 00:17:02] You're accessing the development server over HTTPS, but it only supports HTTP. [06/May/2023 00:17:02] code 400, message Bad request version ('Û\x07\x0fæ\x07¹QÔûôÛ') [06/May/2023 00:17:02] You're accessing the development server over HTTPS, but it only supports HTTP. why it coming? It is very important to fix. Can you please tell me where is the issues here? what fault I did? this is list of requirements.txt: asgiref==3.2.10 boto3==1.17.36 botocore==1.20.36 certifi==2020.12.5 chardet==4.0.0 crispy-tailwind==0.5.0 dj-database-url==0.5.0 Django==3.1 django-admin-honeypot==1.1.0 django-admin-thumbnails==0.2.5 django-crispy-forms==1.13.0 django-session-timeout==0.1.0 django-storages==1.11.1 gunicorn==20.1.0 idna==2.10 jmespath==0.10.0 Pillow==8.4.0 psycopg2-binary==2.9.5 python-dateutil==2.8.1 python-decouple==3.4 pytz==2020.1 requests==2.25.1 s3transfer==0.3.6 six==1.15.0 sqlparse==0.3.1 urllib3==1.26.3 whitenoise==5.3.0 -
Authenticate enduser without disturbing the django admin site
first, i login to django admin site, then i go to the login page in my html template and i logout, but when i go again to django admin site, the django admin site is also logged out. How do I separate these two things, so that when the enduser login and logout it doesn't affect the django admin? my project uses custom user model, that's all nothing else. class MyAccountManager(BaseUserManager): def create_user(self, username, first_name, middle_name, last_name, club_favorite, email, password=None): if not username: raise ValueError("Users must have a username") user = self.model( username = username, first_name = first_name, middle_name = middle_name, last_name = last_name, club_favorite = club_favorite, email = email, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, first_name, middle_name, last_name, club_favorite, email, password=None): user = self.create_user( username, password = password, first_name = first_name, middle_name = middle_name, last_name = last_name, club_favorite = club_favorite, email = email, ) user.is_admin = True user.save(using=self._db) return user class MyAccount(AbstractBaseUser): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=254, blank=True) club_favorite = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) object = MyAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'middle_name', 'last_name', 'club_favorite', 'email'] def __str__(self): return self.username … -
Attempting to confirm if a user is okay with deleting their account utilizing a random string, but the string they enter is never correct
I am utilizing Django to create a website. I am currently making a settings page that should easily allow users to delete their account if they enter a string equivalent to a random string that is set in the context sent to the HTML page. However, the string the user enters is never equal to the random string, despite them being the same. My code is below: views.py @login_required def settings(request): confirmation = ''.join(random.choices(string.ascii_uppercase, k=7)) if request.method == 'POST': form = NewDeleteForm(request.POST) if form.is_valid(): if form.cleaned_data["confirmation"] == confirmation: User.objects.filter(username = request.user.get_username()).update(is_active = False) return redirect("home") else: return redirect("settings") else: form = NewDeleteForm() context = { 'home_act': 'active', 'contact_act': '', 'released_act': '', 'about_act': '', 'current_act': '', 'form': form, 'confirmation': confirmation, } return render(request, 'turtles/settings.html', context) forms.py class NewDeleteForm(forms.Form): confirmation = forms.CharField(label = 'Type the letters above to confirm account deletion.') settings.html {% extends 'turtles/base.html' %} {% load static %} {% block head %} <title>Settings</title> {% endblock %} {% block content %} <div class="container"> <h3 style="text-align: center; font-size: 30px; font-weight: bold;">Settings</h3> {{ data }} {% if user.is_superuser %} <h4>Administrator Settings</h4> <a href="{% url 'admin:index' %}">Click here to go to the administrator settings page.</a> {% endif %} <h4>Delete Account</h4> {{ confirmation }} <form … -
Why does the Django SelectDateWidget not retain widget choices if the field errors?
I've created a modified SelectDateWidget to include years spanning 100 years ago to 18 years ago. I wanted to reverse the order of the years so the most recent appears at the top. class DateMultiWidget(forms.SelectDateWidget): template_name = 'myapp/date_multi_widget.html' def __init__(self, attrs=None, months=None, empty_label=None): curr_date = timezone.now() years = range(curr_date.year - 100, curr_date.year - 17) years = reversed(years) super().__init__(attrs, years, months, empty_label) This works as expected when I initially load the form. I've been testing out how the form handles validation errors, however, and if I enter an invalid date, when the form reloads after django raises a ValidationError, all of the years are missing from the select. If I remove the reversed() function, it all works fine when a validation error occurs, but the years aren't in the order I'd like. I got around this by reversing the years within the widget template, but it's a bit cumbersome and I'm interested to know why the original method doesn't work. <div id="id_{{ widget.name }}" class="date-selector input-group"> <span class="input-group-text"><label>{{ group_label }}:</label></span> {% spaceless %} {% for widget in widget.subwidgets %} <select class="form-select" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> <option value="" disabled selected>{% if forloop.counter == 1 %}DD{% elif forloop.counter == 2 %}MM{% … -
Can you monitor multiple urlpatterns with Django's runserver autoreload
In the project I'm working on, I'd like to have it run 2 apps on one runserver for development purposes (standalone in production), to utilize amongs others autoreload options. What I'd like to do is have wsgi application, and asgi application by implementing Django channels next to it. For that, I feel like I need to have 2 ROOT_URLCONFs basically, as one would apply to wsgi, and other to asgi application. I am interested is there a way to make runserver pay attention to multiple ROOT_URLCONFs or urlpatterns whatever you want to name them? And does this approach make sense in the first place, as from what I've seen on the web, it's not such an uncommon setup, but I haven't seen anyone placing it under one runserver. For the ease of development setup it would be one server, as there's already an overhead on startup of the project development. -
How to setup urlpatterns for ASGI Django Channels http type protocol?
I am pretty sure I am missing something from the documentation, but I am unable to find a definitive answer anywhere. I have a Django application, and what I'd like to do is use Django Channels for websocket purposes, however I am also interested in async http that Django Channels can provide for me. Looking all over the internet and also in the source code of Django Channels, the only kinds of examples I was able to find match the ones from the documentation where "http" property in ProtocolTypeRouter is set to get_asgi_application, and only websockets have their own urlpatterns. application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": django_asgi_app, # WebSocket chat handler "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path("chat/admin/", AdminChatConsumer.as_asgi()), path("chat/", PublicChatConsumer.as_asgi()), ]) ) ), }) I can't understand how to set up urlpatterns that http property will route to.