Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Second Order SQL Injection
def find_or_create_bp(bp_metadata): """ Returns a BusinessProcess, creating a new one if not found. """ bp_id = bp_metadata['id'] bp_name = bp_metadata['name'] bp_matches = BusinessProcess.objects.filter( bp_id=bp_id, bp_name=bp_name ).order_by('-id') if bp_matches: bp = bp_matches[0] else: bp = BusinessProcess( bp_id=bp_id, bp_name=bp_name ) bp.save() print("BusinessProcess created: " + bp_name) return bp Method find_or_create_bp at line 42 of project/api/src/monitoring_backend/monitoring_app/management/commands/migrate_watchitemconfigs.py gets database data from the filter element. This element’s value then flows through the code without being properly sanitized or validated, and is eventually used in a database query in method find_or_create_step at line 64 of project/api/src/monitoring_backend/monitoring_app/management/commands/migrate_watchitemconfigs.py. This may enable an Second-Order SQL Injection attack. -
Django reload - ajax GET after POST does not get latest database model instances
This question has been posted in different ways already but I can't get it to work.. I don't use AJAX yet in my script but I should use it as my database update is not visible in my application. Only when I restart the application, I can see the change. Can someone help me? I currently have this: .html {% block content %} <form id="post-setting-form" class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <h3 class="card-title">Update Mail Settings</h3> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="form-label">Send Emails:</label> <p></p> <input type="radio" name="update_type" value="manual" {% if view.manualSetting %}checked {%endif%}> Manual {% if view.manualSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <input type="radio" name="update_type" value="auto" {% if view.autoSetting %}checked {%endif%}> Automated {% if view.autoSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <button type="submit" class="btn btn-primary">Update</button> </div> </div> </div> </div> </form> {% endblock %} .views class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(pk=1) model.save() model.reload model.refresh_from_db() autoSetting = int(model.auto == True) manualSetting = int(model.manual == True) def post(self, request, *args, **kwargs): id_ = self.kwargs.get("pk") logger.info("testestest") update_type = self.request.POST.get('update_type') logger.info(update_type) if update_type == 'manual': … -
The Django test client redirects to the login page with a logged-in superuser
I am trying to connect a superuser to the Django test client, and then access a page in the Django administration interface with a GET method. However, I get a redirect to the login page, even though the superuser is properly logged in. Here is my code: def test(self) -> None: client = Client() user = User.objects.create(username='user', is_superuser=True) client.force_login(user) response = client.get(f'/admin/management/establishment/', follow=True) print("Redirect chain\t", response.redirect_chain) print("Request user\t", response.wsgi_request.user) print("Is superuser\t", response.wsgi_request.user.is_superuser) Here is the output: Redirect chain [('/admin/login/?next=/admin/management/establishment/', 302)] Request user user Is superuser True Do you know why I have this redirection and how I can avoid it? -
Updating postgres database by psql instead of django migrate-command and pg_catalog
I have a django server running in such production environment that cannot be copied to any test server as such (somebody must have changed the virtual environment manually since pip refuses to install the used versions as incompatible). However I should change the postgres database structure. I'm not sure if the django migration commands (python manage.py makemigrations & python manage.py migrate) will pass, thus I'm planning to prepare for running psql-commands instead, if needed. So I compared to sql-dumps (taken by pg_dump on test server) before and after migration command to obtain the needed psql-commands and detected that also an ineternal table pg_catalog had changed as below: < SELECT pg_catalog.setval('public.django_migrations_id_seq', 29, true); --- > SELECT pg_catalog.setval('public.django_migrations_id_seq', 32, true); What can be the meaning of this pg_catalog and does it make sense in trying to updata it by psql-command ? On the other hand, if the migrate-commands do not work and I need to run them with --fake qualifier, can I trust the result will still be what I wanted ? -
i want to update paypal subscription (classic mathod i guess)
i have implement subscription using this link : https://overiq.com/django-paypal-integration-with-django-paypal/ this mathod is using ipn now i want to update the exising subscription, i show the paypal documentation but this is the another mathod to integrate paypal, and i had integrate paypal only using email, i think this is the classic subscription using paypal, and i can not found any official docs for subscription for paypal with this mathod, so how to update subscription with this mathod? also if anyone find any official docs please share thanks in advance !! -
how do i configure os path directory
I keep getting the following response when I querry to get static files: (.venv) PS C:\Users\USER\Documents\estar app> python anchor/manage.py collectstatic --no-input STATIC_ROOT = os.path.join(BASE_DIR, "<where all static files will be collected>") NameError: name 'os' is not defined Who can help out, please? I tried: python manage.py collectstatic --no-input -
Django multiple user login on multiple tab session issue
I have an issue with my Django app. If I use to login to the app with different users from different browser tab , then it is loging out the first user. I am using django file bases session, which create session file. But if I login with a second user the first session file is over writing . So my question is , is there a way to set the session file name to a unique name for each login using any middleware or other options in django. May be and extended class using SessionMidleware I am sort of lost, I tried different solutions , but none of this works. If any one know how to implement it , please guide me, Thanks for any help. -
Django Foreign Key error ......What should I do now?
```In [1]: import json In [2]: from Bugijugi. models import Post In [3]: with open('posts.json') as f: ...: posts_json = json.load(f) ...: In [4]: for post in posts_json: ...: post = Post(title=post['title'], content=post['content'], author_id=post['us ...: er_id']) ...: post.save() ...: ``` --------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py:97, in DatabaseErrorWrapper.call..inner(*args, **kwargs) 96 with self: ---> 97 return func(*args, **kwargs) IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: IntegrityError Traceback (most recent call last) Input In [4], in <cell line: 1>() 1 for post in posts_json: 2 post = Post(title=post['title'], content=post['content'], author_id=post['user_id']) ----> 3 post.save() File F:\IMPORTANT\GAME\vrsty life\CSE 347\Project\Sample\Bugijugi\models.py:27, in Post.save(self) 26 def save(self): ---> 27 return super().save() File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:743, in Model.save(self, force_insert, force_update, using, update_fields) 740 if loaded_fields: 741 update_fields = frozenset(loaded_fields) --> 743 self.save_base(using=using, force_insert=force_insert, 744 force_update=force_update, update_fields=update_fields) File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:780, in Model.save_base(self, raw, force_insert, force_update, using, update_fields) 778 if not raw: 779 parent_inserted = self._save_parents(cls, using, update_fields) --> 780 updated = self._save_table( 781 raw, cls, force_insert or parent_inserted, 782 force_update, using, update_fields, 783 ) 784 # Store the database on which the object was saved 785 self._state.db = using File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:885, in Model._save_table(self, raw, cls, force_insert, force_update, using, update_fields) 882 … -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile when uploading a picture
My project is a django website to predict if a person has brain Tumour or not. def tumor_pred(imageTumor): model = load_model("bestmodel2.h5") path = imageTumor img = load_img(path, target_size=(224, 224)) input_arr = img_to_array(img)/225 input_arr.shape input_arr = np.expand_dims(input_arr, axis=0) pred = model.predict_classes(input_arr)[0][0] if pred == 0: return 'no' elif pred == 1: return 'yes' else: return 'error' mriReport function def mriReport(request, aid): appoitment_details = Appoitment.objects.all().filter(id=aid) if request.method == "POST": Appoitment_ID = request.POST['SessionID'] Patient_ID = request.POST['PatientID'] PatientName = request.POST['PatientName'] PatientEmail = request.POST['PatientEmail'] Date = request.POST['Date'] imageTumor = request.FILES['imageTumor'] result = tumor_pred(imageTumor) try: MRIReport.objects.create(Appoitment_ID_id=Appoitment_ID, Patient_ID_id=Patient_ID, PatientName=PatientName, Date=Date, PatientEmail=PatientEmail, image=imageTumor, result=result) return redirect('labWorkshop') except Exception as e: raise e return render(request, 'MRIReport.html', {'appoitment_details': appoitment_details}) I get the error expected str, bytes or os.PathLike object, not InMemoryUploadedFile when i try to run my machine learning model I have seen other stackoverflow solutions where it is reported that it is trying to open an already opened file. Therefore i tried by to removing: img = load_img(path, target_size=(224, 224)) New function def tumor_pred(imageTumor): model = load_model("bestmodel2.h5") img = imageTumor # img = load_img(path, target_size=(224, 224)) input_arr = img_to_array(img)/225 input_arr.shape input_arr = np.expand_dims(input_arr, axis=0) pred = model.predict_classes(input_arr)[0][0] if pred == 0: return 'no' elif pred == 1: return 'yes' … -
Django 4.0.1 cannot import name 'SortedDict' from 'django.utils.datastructures'
My project isn't working! I need help! I'm just fill in the forms. And run the project. Error: Traceback (most recent call last): File "/home/pc/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/pc/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pc/Documents/Projects/Django/Travel/Web/views.py", line 92, in sign_in user = auth.authenticate(username=username, password=password) File "/home/pc/.local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 42, in sensitive_variables_wrapper return func(*func_args, **func_kwargs) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 77, in authenticate user = backend.authenticate(request, **credentials) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/backends.py", line 48, in authenticate if user.check_password(password) and self.user_can_authenticate(user): File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 115, in check_password return check_password(raw_password, self.password, setter) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/hashers.py", line 47, in check_password preferred = get_hasher(preferred) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/hashers.py", line 129, in get_hasher return get_hashers()[0] File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/hashers.py", line 96, in get_hashers hasher_cls = import_string(hasher_path) File "/home/pc/.local/lib/python3.10/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "/home/pc/.local/lib/python3.10/site-packages/django/utils/module_loading.py", line 15, in cached_import import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/pc/.local/lib/python3.10/site-packages/django_scrypt/hashers.py", line 2, in <module> from django.utils.datastructures import SortedDict ImportError: cannot import name … -
Django create get api from different table return
I am trying to use the def list function Django from these two which I have tables Batch and BatchYield the table of Batch look like batch_id | batch_status | `````````|```````````````| 11 | completed | and the table of BatchYield look like id | grade_a_produce | grade_b_produce | grade_c_rejection | harvest_date | batch_id | ```|`````````````````|`````````````````|```````````````````|``````````````|``````````| 23 | 100 | 120 | 212 | 22-02-12 | 11 | 25 | 110 | 122 | 242 | 21-01-14 | 11 | So I wrote a def list function in Django in which I have joined these two table with this code def list(self, request, *args, **kwargs): try: for data in request.data: batch_id = data.get('batch_id') all_batchyield = BatchYield.objects.filter(batch_id=batch_id).values('grade_a_produce', 'id', 'grade_b_produce', 'grade_c_rejection', 'harvest_date', 'batch_id') if all_batchyield.count == 0: return Response({"response": "Data not Found"}, status=status.HTTP_200_OK) all_batchyield_df = pd.DataFrame(all_batchyield) all_batchyield_df = all_batchyield_df.replace({np.nan: None}) all_completed_batchs = Batch.objects.filter(id=batch_id).values('batch_status', 'id') completed_batch_df = pd.DataFrame(all_completed_batchs) completed_batch_df = completed_batch_df.replace({np.nan: None}) completed_batch_df.rename(columns={'id': 'batch_id'}, inplace=True) final = pd.merge(completed_batch_df, all_batchyield_df, on='batch_id') final = final.drop('batch_id', axis=1) except Exception as e: return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(final.to_dict('record'), status=status.HTTP_200_OK) From this code I got the and output which look like this [ { "batch_status": "completed", "grade_a_produce": 100.0, "id": 23, "grade_b_produce": 120.0, "grade_c_rejection": 212.0, "harvest_date": "2022-02-12T00:00:00Z" }, { "batch_status": … -
Pre populating a django form using Initial not working
I am trying to save a modelform by prepopulating 'template_name' field . As per django documentation and other threads it is clear that initial parameter should work but i just can't make it work for my code. I am getting the error that template_name field is empty. Any help on what am I missing and any other approach towards this will be great. Here is the code models.py class TemplateNameModel(models.Model): "Model to add the template name" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tna_template_name = models.CharField(verbose_name="Template name",max_length = 128, unique = True, null = False, blank = False, help_text="please enter name of the new tna template") description = models.CharField(verbose_name="template description", max_length = 256, null = True, blank = True, help_text ="Please enter the description(optional)") created_by = models.TextField(verbose_name="Template created by", max_length= 128, null = False, blank = False,help_text ="Please enter the name of creator") date_created = models.DateTimeField(auto_created= True, null = True, blank = True) is_active = models.BooleanField(verbose_name="Template status",null = False , blank= False) def __str__(self): return self.tna_template_name class TnaTemplateModel(models.Model): id = models.AutoField(primary_key=True, editable=False) template_name = models.ForeignKey(TemplateNameModel, verbose_name="template name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the template") process_name = models.ForeignKey(ProcessModel, verbose_name="process name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the process") sequence = models.IntegerField(verbose_name="Process Sequence",null = False,blank = False) … -
add filter_horizontal into a model form in django
I am trying to add filter_horizontal like in admin for the "genre" of a book model form and I am using widgets.FilteredSelectMultiple but the result was this not this. How can I fix this? This is my code for bookform class BookForm(forms.ModelForm): publisher = forms.ModelChoiceField(queryset=Publisher.objects.all()) genre = forms.ModelMultipleChoiceField( widget=widgets.FilteredSelectMultiple('Genre', False), queryset=Genre.objects.all(), ) class Meta: model = Book fields = ['language', 'number_of_pages', 'summary', 'isbn', 'publisher', 'genre'] -
Redis not working. __init__() got an unexpected keyword argument 'username'
i am trying to run the celery -A project worker -l info. But each time it returns an error like init got unexpected error. Kindly Help. Thanks in advance. -
JavaScript not functioning after htmx get/post request swapped
I'm building a Django project and trying to get and post data using htmx and everything works, which means I can get and post data there is no problem with that, but the problem is after data is swapped the bootstrap dropdown or tooltips or other elements that need some javascript to function is not working, I think the error is because after htmx swapped there is always new data added or replaced to the DOM, so the new data is no longer supported to any script. so how can I handle this? -
How to permanently store the data from my django website into a sqlite3 database?
I am trying to build a Resume Parser website using Django which is connected with a SQLite3 database. The parsed data from the resumes I upload gets stored in the database but whenever I refresh my website it disappears. What I want is to permanently save that parsed data into my database and whenever new data is being added, it should have the previous data and the new data should be added to it. I am new to Django, so this is something I don't know. Any help would be appreciated. I am including my models.py file below. from django.db import models from django import forms from django.forms import ClearableFileInput # for deleting media files after record is deleted from django.db.models.signals import post_delete from django.dispatch import receiver class Resume(models.Model): resume = models.FileField('Upload Resumes', upload_to='resumes/') name = models.CharField('Name', max_length=255, null=True, blank=True) email = models.CharField('Email', max_length=255, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=1000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=1000, null=True, blank=True) college_name = models.CharField('College Name', max_length=1000, null=True, blank=True) designation = models.CharField('Designation', max_length=1000, null=True, blank=True) experience = models.CharField('Experience', max_length=1000, null=True, blank=True) uploaded_on = models.DateTimeField('Uploaded On', auto_now_add=True) total_experience = models.CharField('Total Experience … -
What's wrong here? It says, services.app Additional property enviornment is not allowed
version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" enviornment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword -
what is difference between room.host.id and room.id in my code
{% for room in rooms %} {% if request.user == room.host %} Edit Delete {% endif %} @{{room.host.username}} <a href = {% url 'room' room.id %}>{{room.id}} >>>{{room.name}} {{room.topic.name}} #views def userProfile(request, pk): user = User.objects.get(id=pk) context={'user':user} return render(request, 'profile.html', context) -
How to Register a user either by Email ID or by Mobile Number in Django?
I can register a user getting both email address and mobile number in my application. But what I really want is to register a user using either email or mobile number. So that if a user provides email address, it must be saved in email field in database and if user provides mobile number, it must be saved in mobile field in database. Also I need to send an activation link if the user provides an email address. Otherwise I need to send an OTP or activation link to the mobile number. Please suggest me a better way to accomplish this task. -
How To Implement Custom Password Hashing in Django?
So my manager has asked me to implement Base64 Password Encryption for our django website. I can't find any base64 hashing algo in django.contrib.auth.hashers. So, I figured that I'd have to write my own Hasher module. Problem is, I don't know how. I have tried reading the django documentation but its still unclear to me. I just need my User's Passwords to be stored using Base64 Encryption in the database. Also, I need my Custom User Authentication to work accordingly. Here's my User Model: from django.contrib.auth.models import AbstractUser from .managers import UserManager class User( AbstractUser ) : email = models.EmailField( verbose_name = 'Email Address', unique = True, null = False ) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__( self ) : return self.get_username() Here's my User Manager: from django.contrib.auth.models import BaseUserManager class UserManager( BaseUserManager ) : def create_user( self, email = None, password = None, first_name = None, last_name = None ) : try : user = self.model( email = self.normalize_email( email ) ) user.set_password( password ) user.is_active = True user.first_name = first_name user.last_name = last_name user.save( using = self._db ) return user except Exception as e : raise Exception( e ) def … -
How to compose Django Model Filter for relation existence?
How can I run the following query using Django Models? SELECT * FROM TABLE_A WHERE (SELECT COUNT(id) FROM TABLE_B WHERE TABLE_A.field1 = TABLE_B.field1) > 0 I want to select records from Table_A that have matching records in Table_B. -
Download byte range requests support for firebase storage
Am trying to narrow down a problem and knowing if firebase storage supports byte range requests for video downloads will help. I can't seem to find that information anywhere. My web app includes video streaming functionality (You-tube style) and I wonder if this is the best choice. If not what better alternative to host the videos? I have already implemented this as follows but my videos plays in all devices and browsers except iphones and ios devices: <video width='100%' height='315' poster='{{ value.image }}' controls loop muted playsinline> <source type='video/mp4' src='{{ value.video }}'> </video> Based on extensive research here and other resources online, Solutions seems to be adding controls playsinline muted to the video tag seemed to work, mine didn't with these. The other problem was video-container type. Have confirmed that mine is mpeg4 container and displayed with video/mp4 in the source type. Last issue I see is that server might not support byte range requests, am trying to determine if this is it with firebase before deciding to move on to another video storing solution. (And any suggestions for these?) Thanks. -
Need to get the Total hours calculated from the multiple entries of hour field in django rest framework
serializers class Consolidated_serializers(serializers.ModelSerializer): project_name = serializers.CharField(source='project.project_name') username = serializers.CharField(source='user.username') user_id = serializers.CharField(source='user.id') class Meta: model = Timelog fields = ('id','username','user_id','project_name','date','hours',) viewset class Total_hours_viewset(viewsets.ModelViewSet): queryset = models.Timelog.objects.all().annotate(sum_delta=Sum('hours')) serializer_class=serializers.Consolidated_serializers the result Iam getting is [ { "id": 13, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" }, { "id": 14, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" } ] But the result i Need is [ Total hours: 16:00:00 { "id": 13, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" }, { "id": 14, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" } ] I tried using the above code but i couldn't able to get the total hours in the json view for multiple entries. Can you please help me to get the total hours by adding the multiple entries of hour field in the model. -
Hindi Conversion is not working with django translation
I am new to django and i am trying to use internationalization feature to translate the content of page. I am able to convert it in languages like French , German but when i am trying to use Hindi it does not work at all. Settings.Py """ Django settings for prj project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_PATH=os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-m$v&xn!i6jcv4pp^!$p)^%h#xolpod8&969@9x!%*wpyxtm2o7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'prj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_PATH], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'prj.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases … -
Why does 127.0.0.1:80 not work in apache virtualhost?
I can work around this, but I'd like to understand better what's going on. Using Apache 2.2 on Ubuntu, in a local development environment, a virtual host with *:80 as the address works, but 127.0.0.1:80 doesn't. Neither does localhost:80. I only have one .conf file with virtual hosts in it besides the main appache2.conf file. Here's what's in that separate vhosts file: <VirtualHost CCNM-378B:80 # Does not work. (CCNM-378B is what 'hostname' from the command line says) <VirtualHost 127.0.0.1:80 # Does not work. <VirtualHost localhost:80 # Does not work. <VirtualHost *:80 # WORKS ServerName localhost In etc/hosts I have: 127.0.0.1 localhost access.log says: 127.0.0.1:80 ::1 - - [24/Mar/2022:16:31:12 -0600] "GET /favicon.ico HTTP/1.1" 404 487 "http://localhost/ideatree/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36" In apache2.conf I have: ServerName 127.0.0.1 #ServerName localhost But neither of these seem to make a difference. The app that Apache is serving is a Django app. The Apache docs say the following about vhost name resolution, but it doesn't explain why this is happening since the base apache2.conf defines '127.0.0.1' as ServerName but that isn't recognized in the VirtualHost. If a VirtualHost doesn't specify a ServerName, a server name will be inherited …