Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the >= operator in python working like a > in a if statement?
I have an if statement that checks whether whatever is submitted in a Django form is greater than or equal to the listing_price (initial price of the item) and greater than all other bids before saving. The second part of the conditional is working, but the form will only save if the submitted value is greater than the listing_price, not equal. The greater than or equal to operator is working like a greater than operator instead. What could be causing the problem and how do you fix it? views.py def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) listing_price = listing.bid bid_form = BidsForm() #code for the bid form bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() max_bid =0 for bid in other_bids: if bid.bid > max_bid: max_bid = bid.bid if request.method == "POST": bid_form = BidsForm(request.POST) #checks if bid form is valid if bid_form.is_valid(): new_bid = float(bid_form.cleaned_data.get("bid")) if (new_bid >= listing_price) and (new_bid > max_bid): bid = bid_form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids." }) else: return … -
Is that safe too use same venv for different projects?
I'm trying to learn Django framework, and I made a Virtual Environment include Django 4 and python 3.10. Is it safe to use this VENV for all my future projects or should I make new for each one? Consider that those projects will be make for real persons and they expect high security. -
Is the any import problem in this code?I tried many solutions like changing app name but none worked for me
from rest_framework import serializers from rest_framework import hospital class hospitalsSerializer(Serilizers.Modelserializer): class Meta: model=hospital field='all' //this is my serializers.py -
Adding button to a field in a form to add data from another form Django
So, I have this html file with a model form and I would like to add a button '+' to just one field of the form to to open a modal with another smaller form to fill out and just take information from one column. I already have the way to open the modal and the second form, in the database I am guessing I will need a foreign key, but I am still trying to figure out how to implement the button right next to the field. So far, I have this in my forms.py file: class contractsform(forms.ModelForm): class Meta: model = Contratos fields = '__all__' widgets = { 'name': forms.TextInput(attrs ={'class': 'form-control'}), 'contractee': forms.TextInput(attrs={'class': 'form-control'}), 'contractor': forms.TextInput(attrs={'class': 'form-control'}), 'start': forms.NumberInput(attrs={'class': 'form-control', 'type': 'date'}), 'end': forms.NumberInput(attrs={'class': 'form-control', 'type': 'date'}), 'cost': forms.NumberInput(attrs={'class': 'form-control'}), 'type': forms.Select(attrs={'class': 'form-select'}), 'department': forms.Select(attrs={'class': 'form-select'}), 'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}), 'product': forms.TextInput(attrs={'class': 'form-control'}), 'attached_file': forms.FileInput(attrs={'class': 'form-control'}), 'notification': forms.CheckboxInput(attrs={'class': 'form-check-input'}), } I added attrs just to make the fields pretty. I would like to add it to the contractor field, with bootstrap 5, but I am new to Django and the manual confused me a little bit. -
Django CSRF verification failed even with @csrf_exempt
I've got a web service written in Django that has a py file with a bunch of view functions that are decorated with @csrf_exempt. It's all working as it has been for years. I recently added another function and entry in urls.py. I used the same pattern as all the other view functions -- decorated with @csrf_exempt, but for this one function the server responds with a CSRF verification failed. a snippet of my urls.py url(r'changepassword$', websvc2_account.changepassword), url(r'resetpassword$', websvc2_account.resetpassword), url(r'getcodetodeleteaccount$', websvc2_account.getcodetodeleteaccount), url(r'deleteaccountwithcode$', websvc2_account.deleteaccountwithcode), url(r'setuserdetails$', websvc2_account.setuserdetails), The function I added: @csrf_exempt def getcodetodeleteaccount(request): ... These views are called from mobile apps, so I do not want CSRF and all of them are decorated with @csrf_exempt. This new function is the only one that doesn't work. Any help or clues would be appreciated. Thanks -
How to display few fields from another model instead of one <select> field in Django Admin
everyone. I have two models linked one-to-many relationships ModelA: field_1 .. field_n ModelB: some_field = ... field = ForeignKey(ModelA) What i need to do so that when opening an entry of ModelB in Admin site, other then all ModelB fields, all fields of ModelA are displayed instead of field? Sorry for my english 😬 -
Cloud Foundry Django app `cf push` logs the error `port 5432 failed: Connection refused`
I am deploying a basic Django app with Cloud Foundry. The app appears to be unable to connect to or authenticate with the database. I encounter the error after I run the cf push -f manifest.yml command. It returns Start unsuccessful and suggests I look at the logs with the cf logs app-name-1 --recent command. The logs contain this error: ERR django.db.utils.OperationalError: connection to server at "server-name.region-name.rds.amazonaws.com" (ip.redacted), port 5432 failed: Connection refused ERR Is the server running on that host and accepting TCP/IP connections? The app's repo contains a manifest.yml that specifies an application name app-name-1 and a service service-name-psql-db. This app exists, as you can see from the output of the cf apps command: Getting apps in org org-name / space space-name as user-name.. name requested state processes routes app-name-1 started web:0/1 app-name-1.app.domain.com Further, the app is hooked up to a database service as you can see from the output of the cf services command: Getting services in org org-name / space space-name as user-name... name service plan bound apps last operation broker upgrade available service-name-psql-db aws-rds micro-psql app-name-1 update succeeded aws-broker The credentials I am trying to use to connect to the database seem correct to me. … -
wsgi:error pid 131476:tid 140411361216256 remote 200.110.48.158:35204 ModuleNotFoundError: No module named 'django.core'
[Thu Jun 16 20:32:08.505090 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] Traceback (most recent call last): [Thu Jun 16 20:32:08.505133 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] File "/root/novo-ai-api-main/backend/server/server/wsgi.py", line 18, in <module> [Thu Jun 16 20:32:08.505139 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] from django.core.wsgi import get_wsgi_application [Thu Jun 16 20:32:08.505159 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] ModuleNotFoundError: No module named 'django.core' [Thu Jun 16 20:48:58.603180 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] mod_wsgi (pid=131476): Failed to exec Python script file '/root/novo-ai-api-main/backend/server/server/wsgi.py'. [Thu Jun 16 20:48:58.603316 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] mod_wsgi (pid=131476): Exception occurred processing WSGI script '/root/novo-ai-api-main/backend/server/server/wsgi.py'. [Thu Jun 16 20:48:58.603447 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] Traceback (most recent call last): [Thu Jun 16 20:48:58.603477 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] File "/root/novo-ai-api-main/backend/server/server/wsgi.py", line 18, in <module> [Thu Jun 16 20:48:58.603483 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] from django.core.wsgi import get_wsgi_application [Thu Jun 16 20:48:58.603506 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] ModuleNotFoundError: No module named 'django.core' These are my all working files **#000-default.conf** <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating … -
Update To Django 4.0.5 in an existing web app in Pythonanywhere
I have got a web app working on the web and I want to update the Django version from 3.1 to 4.0.5 because of it’s posible with the new version to solve a problem when an annotate query doesn’t find results and to get 0 instead of None. How can I change the version of Django easily without delete and deploy again the web app? Is possible to go into the virtual environment and simply update Django or is necessary something more (like change requirements before or something more)? -
How to return extra dictionary information in queryset via Django ListViewApi?
Currently my query is returning following response using ListViewApi [ { task: x year: y total_value: 10 },{ task: p year: e total_value: 10 } ] I want to display following extra information in dictionary format using django queryset [ { task: x year: y total_value: 10, category_data:[ { type: b, value: 3 },{ type: b, value: 7 } ] },{ task: p year: e total_value: 10 } ] -
Django: Switch a form in template depending on choice field
I am looking for a way to switch and display a form in template, depending on choice in CharField in another form. My app has the following models: class Damage(models.Model): damage_place = models.CharField() damage_date = models.DateField() class DamageType1(models.Model): damage = models.ForeignKey(Damage) ... class DamageType2(models.Model): damage = models.ForeignKey(Damage) ... class DamageType3(models.Model): damage = models.ForeignKey(Damage) ... Damage model has a DamageForm(forms.ModelForm) that is filled in by another user. Each DamageType model has different fields (marked as ... for simplicity) and own DamageTypeForm1(forms.ModelForm), DamageTypeForm2(forms.ModelForm) and DamageTypeForm3(forms.ModelForm). There is also a form in a template specifying which DamageType to choose: class DamageSpecify(forms.Form): DAMAGE_CHOICES = [ ('DamageType1', 'DamageType1'), ('DamageType2', 'DamageType2'), ('DamageType3', 'DamageType3'), ] damage_type = models.CharField(choices=RODO_CHOICES) And now, after choose specific damage_type in DamageSpecify I would like to display the filled DamageForm and empty DamageType(1, 2 or 3) in template to fill and save both forms. How could this be done? -
Django Allauth redirect to localhost instead of 127.0.0.1
I have a custom User class, which is shown on the main page: After a successful log in, django redirects me to the localhost page shown above. I also have an API that connects the backend to the frontend. However, it communicates with http://127.0.0.1/, which has a different user. In my views I only have: urlpatterns = [ path('', views.index, name='index'), path('api/tableEntries', views.ReactView.as_view(), name="api"), path('api/getUser', views.getUser.as_view(), name="getUser"), path('accounts/', include('allauth.urls')), ] And in my settings, I have the redirect variable set like this: LOGIN_REDIRECT_URL = 'index' I have 2 questions: I read in other threads that localhost and 127.0.0.1 sometimes resolve to different domains, and share different cookies. But why do they resolve to different domains? How do i fix it so that the redirect goes to 127.0.0.1 and I can access it with an API call? -
raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I use Django and every time when I try to send email I get this response Internal Server Error: /order/ Traceback (most recent call last): File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Daniil\Desktop\Admin\py\qazpoligrah1\main\views.py", line 53, in post email.send() File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\mail\message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages new_conn_created = self.open() File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 91, in open self.connection.login(self.username, self.password) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 739, in login (code, resp) = self.auth( File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 642, in auth (code, resp) = self.docmd("AUTH", mechanism + " " + response) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 432, in docmd return self.getreply() File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 405, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed my settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.mail.yahoo.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@yahoo.com' EMAIL_HOST_PASSWORD = 'password' my views def post(self,request): print(request.POST.get('mail'), request.POST.get('type')) prod_type = models.ProductTypes.objects.filter(pk = request.POST.get('type')) order_msg = prod_type[0].name email = EmailMessage('Qazpoligraph', order_msg, settings.EMAIL_HOST_USER, to= (request.POST.get('mail'),)) email.send() return redirect('/') I tryed to change the EMAIL_PORT and the EMAIL_HOST but nothing … -
How does djagno update urls when you add a model to an app?
If I have an app (blog) and I create a posts model and then add a schedule model how are the urls for schedule created? Are they imported with the blog.urls like the posts in 3 line below? urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('accounts/', include('django.contrib.auth.urls')) ] Then how would django reference the schedule model views? Is it path('schedule/,views.scheduleDetail.as_view(),name='sidebar.html') in the myblog.urls? Thanks -
How do I fix the codsad dsdsd sd?
Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng Bang Bang Chief Keef Glo GAng import pyvisa import time import pandas as pd from colorama import Fore, Style import sys rm = pyvisa.ResourceManager() rm.list_resources() ps1 = rm.open_resource('GPIB0::8::INSTR') ps2 = rm.open_resource('GPIB0::7::INSTR') def PowerOFF(): ps1.write("OUTP:STAT OFF") ps2.write("OUTP:STAT OFF") def PowerON(): ps1.write("VOLT 15.0") ps1.write("OUTP:STAT ON") ps2.write("INST P25V") ps2.write("VOLT 15.0") ps2.write("OUTP:STAT ON") temp = input("on or off:\n") if temp =="on": b1 = [] b2 = … -
column "value" is of type smallint but expression is of type timestamp with time zone LINE 1: ... '2022-06-16T23:17:27.223553+00:00'
_Hi! I want to add time like "00:00". class Time(models.Model): day = models.DateTimeField(null=True) value = models.DateTimeField(auto_now_add=True, null=True) def add_time(request, str): if request.method == 'POST': form = TimeForm(request.POST) time = request.POST.get('time') time = Time(id_goal=goal, day=datetime.now(), value=time, description=description) time.save() When i had value = models.TimeField(null=True) it was good and worked before I had deployed to Heroku. After it wrote me: django.db.utils.ProgrammingError: column "value" is of type smallint but expression is of type timestamp with time zone which I didn't understand and now I have a big headache for over two-three days. Haha :P -
Is there a way to create a django model with 20 columns
I am currently building a django application and i want to have a model with 20 columns. Is there a simplest way to do this? Please help. -
Validation Check not working to checkPostive value Django Validation in Form.py
I am working this validation check in django , i have to check postiva values. I have values a,b,c,d if (a,b) also (c,d) positive value will not allowed, i wrote the code this way but do not know why is not checking the validation. I am working on django forms.py for i in range(count): a = int(self.data.get(f'runtime_set-{i}-a') or 0) b = int(self.data.get(f'runtime_set-{i}-b') or 0) c = int(self.data.get(f'runtime_set-{i}-c') or 0) d = int(self.data.get(f'runtime_set-{i}-end_bbch') or 0) if a ==b==c==d: continue if (a + b) > 0 + (c + d) > 0: raise ValidationError( "When A '{a}' , B '{b}' is postive then C '{c}' and d'{d}' positive value is not allowed ") -
How i can get the value string from a drop down list
please how i can get correctly the value from the drop down list, i have used django-widget-tweaks library . this is the code of the field dropdown list that i want to get the value string from it: <p >{{ form.category_column.label_tag }}</p> <p id="category_column_id">{% render_field form.category_column autocomplete="off" hx-get="/sizescolumn/" hx-target="#id_sizes_column" %}</p> I have tried to got the value using javascript by this line of code : var select = document.getElementById('category_column_id').value; ---->but it doesn't work. thanks in advance. -
Django UserCreationForm's fields doesn't show up
class UserRegForm(forms.ModelForm): ...... class Meta: model = get_user_model() # model has: username, email, full_name, is_admin/is_staff/etc. fields = ('username', 'email', 'full_name',) And yet, when going into Django admin and pressing "new user", it asks for username and password only... And, when I create a user like that and try to edit/change it, the 'email' field is completely empty (which is the username_field)... Why? -
How to override model form to create a user in Django
I am trying to create a new user from the modelform by calling the CustomerUserManager in managers.py class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CustomUserCreationForm,self).__init__(*args, **kwargs) try: if args[0]["email"]: self.email= args[0]["email"] self.password= args[0]["password1"] except: pass class Meta: model = CustomUser fields = "__all__" def save(self, **kwargs): return CustomUserManager.create_user(self,email=self.email,password=self.password,name="hic") The managers.py is class CustomUserManager(BaseUserManager): def create_user(self, email, password, name,**extra_fields): ... user = self.model(email=email,name=name, stripe_customer_id=customer.id ,**extra_fields) user.set_password(password) user.save() return user Obviously the self.model does not exist, so how can I correctly create that user from the modelform? If I import the model, I get circular error import. here is my model.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(verbose_name=_("first name"), max_length=50) stripe_customer_id = models.CharField(max_length=120) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = CustomUserManager() -
'CustomUserForm' object has no attribute 'save_m2m' when creating custom user
I am trying to create a user using the following code: class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CustomUserCreationForm,self).__init__(*args, **kwargs) try: if args[0]["email"]: self.email= args[0]["email"] self.password= args[0]["password1"] except: pass class Meta: model = CustomUser fields = "__all__" def save(self, commit=False,**kwargs): customer = stripe.Customer.create( email=self.email, name="test", ) user = CustomUser.objects.create(email=self.email,password=self.password) user.set_password(self.password) user.save_m2m() return user I get the error 'CustomUser' object has no attribute 'save_m2m' Can someone please assist on how to solve this? -
Django Import Export data witjout ID
I tried to export data from Django to Excel, but every thing walk behind me, when I export a Excel File, Django Export only Ids : enter image description here I tried to walk behind some tutorials like : https://django-import-export.readthedocs.io/en/latest/api_widgets.html and Django call 'id' expected a number but got string. In Django App, I have: models.py from pyexpat import model from statistics import mode from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from django.forms import IntegerField class Post(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Person(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return f"({self.name} is {self.post} " class Room(models.Model): name = models.CharField(max_length= 150 ) def __str__(self): return str(self.name) class Classification(models.Model): name = models.ForeignKey(Person, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) date = models.DateField(auto_created=False) def __str__(self): return f"({self.name} Take {self.room} at {self.date})" admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import * from import_export import fields, resources from import_export.widgets import ForeignKeyWidget @admin.register(Post, Room, Classification, Person) class TestappImportExport(ImportExportModelAdmin): pass class Classificationresource(resources.ModelResource): name = fields.Field( column_name='name', attribute='name', widget=ForeignKeyWidget(Person, 'name')) room = fields.Field( column_name = 'room', attribute = 'room', widget= ForeignKeyWidget(Room, 'name')) class Meta: fields = ('name', 'room') even I tried to reverse class Classificationresource(resources.ModelResource) … -
How to loop through particular element in the payload or JSON
I trying to insert all the fields from the payload where values of QId and Answer changes. All I did is I tried looping the QId and Answer but the only one last data is getting inserted. I wanted to insert all value of the QId and Answer views.py cursor = connection.cursor() for ran in request.data: print('request.data--', ran) auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = '0' print('sid--', sid) for i in request.data: qid = i['QId'] print('qid--', qid) answer = i['Answer'] print('answer--', answer) cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) print(qid) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) for row in result_st: print('sp_SaveAuditResponse', row) return Response(row[0]) payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
Is there a way to configure Apache to auto-recognize URLs for Django vs React without hard-coding each endpoint?
We're using Apache 2.4 with React 17 and a Django 3.2 (Python 3.9) application. Curious about a better way to set up our Apache configs to route requests to the React and Django apps. Right now, our Apache virtual hosts file hard-codes which routes need to be handled by the React app vs which need to be handled by Django ... AliasMatch ^/(?!people)(?!states/)(?!countries/)(?!predefined_types/)(?!coop_types/)(?!coops/)(?!data)(?!save_to_sheet_from_form).* /var/www/html/client/build/$0 <Directory "/var/www/html/client/build/"> Options Indexes FollowSymLinks AllowOverride all </Directory> WSGIDaemonProcess ssl_directory home=/var/www/html/web python-home=/var/www/html/web/venv WSGIProcessGroup ssl_directory WSGIScriptAlias /coops /var/www/html/web/directory/wsgi.py/coops process-group=ssl_directory WSGIScriptAlias /data /var/www/html/web/directory/wsgi.py/data process-group=ssl_directory WSGIScriptAlias /countries /var/www/html/web/directory/wsgi.py/countries process-group=ssl_directory WSGIScriptAlias /states /var/www/html/web/directory/wsgi.py/states process-group=ssl_directory WSGIScriptAlias /predefined_types /var/www/html/web/directory/wsgi.py/predefined_types process-group=ssl_directory WSGIScriptAlias /coop_types /var/www/html/web/directory/wsgi.py/coop_types process-group=ssl_directory WSGIScriptAlias /people /var/www/html/web/directory/wsgi.py/people process-group=ssl_directory WSGIScriptAlias /save_to_sheet_from_form /var/www/html/web/directory/wsgi.py/save_to_sheet_from_form process-group=ssl_directory The Django app, for its part, defines urls in the standard way (in our urls.py file) ... ... urlpatterns = [ path('data', views.data, name='data'), path('coops/no_coords', views.coops_wo_coordinates, name='coops_wo_coordinates'), path('coops/unapproved', views.unapproved_coops, name='unapproved_coops'), path('coops/', views.CoopList.as_view()), path('coops/<int:pk>/', views.CoopDetail.as_view()), path('people/', views.PersonList.as_view()), path('people/<int:pk>/', views.PersonDetail.as_view()), path('users/', views.CreateUserView.as_view()), path('predefined_types/', views.CoopTypeList.as_view()), path('coop_types/', views.CoopTypeList.as_view()), path('countries/', views.CountryList.as_view()), path('states/<country_code>', views.StateList.as_view()), path('login', views.signin), path(settings.LOGOUT_PATH, views.signout), path('user_info', views.user_info), ] urlpatterns = format_suffix_patterns(urlpatterns) Is there a more automated way we can get Apache to know what routes shoudl go to Django vs React? Whenever we add a new Django endpoint, we have to add a …