Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cookies not being saved in Safari nor Firefox
I recently started to test cookies in my development environment as I need it for token storage and csrf token. I came accross the issue of firefox and safari not setting the cookies in their storage tabs. If safari's 'prevent cross-site tracking' is off the behavior is the same with Firefox. However, not all users if any will have this setting off. With the previous mentioned, both browsers do not save the cookies in the storage tab. But, the cookies are received as when I click in an api testing button I have after loggin in, it works and the resources are accessed since cookies are sent. But, neither Safari nor Firefox show it in the cookies tab. Here is the response after log in. Response HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: https://localhost:3000 Access-Control-Expose-Headers: Content-Type, X-CSRFToken Allow: POST, OPTIONS Connection: close Content-Length: 714 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 18 Apr 2023 17:11:05 GMT Referrer-Policy: same-origin Server: Werkzeug/2.2.3 Python/3.9.6 Set-Cookie: auth1=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9; expires=Tue, 18 Apr 2023 17:21:05 GMT; HttpOnly; Max-Age=600; Path=/; SameSite=None; Secure Set-Cookie: csrftoken=Y1GzI80DfRc3lMkUnboTYeA3AZBY4aih; expires=Tue, 16 Apr 2024 17:11:05 GMT; Max-Age=31449600; Path=/; Secure Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY I am using Django and React both on localhost, … -
my elastic beanstalk application doesn't reflect the latest commit in the live environment
I am deploying my Django app via the eb CLI. I commit my changes to git and deploy (with eb deploy). In the past I would see my changes reflected after a deploy, now I do not. It is as if the application version is being cached on EB's side.Thanks in advance for any help. I checked the source on S3 and it is the latest version, so I have no idea why the live site (also accessed via eb open after deployment to be sure) doesn't reflect. I added some simple console logging to be certain, and it is missing. I've tried restarting the server and rebuilding the environment. Nothing has worked. I also deleted all previous application versions, so the only remaining one has the changes I want, then redeployed and restarted. Still not the version I want running on the environment. -
A form with fields that are associated with different database tables does not pass validation and does not create the necessary record in the db
I need to create an object in a database table using the form. This table is linked to other tables by means of a One-to-Many relationship. that is, through the ForeignKey. The fields are filled in by means of a drop-down list, which displays the objects that are in the tables associated with these fields. When I try to send data from the form, it does not pass validation and does not send anything. forms.py: class receiptForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['is_apartment'].empty_label = "Не выбрано" self.fields['is_owner'].empty_label = "Не выбрано" self.fields['is_receipt_type'].empty_label = "Не выбрано" class Meta: model = receipt fields = ['is_apartment', 'is_owner', 'is_receipt_type', 'date', 'receipt_file'] views.py: def create(request): error = '' if request.method == "POST": form = receiptForm(request.POST) if form.is_valid(): form.save() return redirect('main') else: error = "Форма была неверной" form = receiptForm() data = { 'form': form, 'error': error } if (request.GET.get('error')): return render(request, "main/main.html", context={'error': request.GET.get('error')}) return render(request, "main/main.html", data) models.py: class apartment(models.Model): address = models.TextField("Адрес квартиры", max_length=500, default="") def __str__(self): return self.address class owner(models.Model): surname = models.CharField("Фамилия", max_length=50, default="") name = models.CharField("Имя", max_length=50, default="") middle_name = models.CharField("Отчество", max_length=50, default="") email = models.EmailField("Email", max_length=254) def __str__(self): return f'{self.surname} {self.name} {self.middle_name}' class receipt_type(models.Model): pattern = models.FileField("Шаблон", upload_to='pattern') title … -
Testing a Consumer is failing when use database_sync_to_async Djagno Channels
So, I didn't use channels for a very long time, so let's be that this is a first time that I have tried to do something. I am trying to create 1 Consumer, wrapped with 1 custom Auth middleware and I want to test my Consumer, if it behaves properly in various test cases. Django==4.1.7 channels==4.0.0 middleware.py @database_sync_to_async def get_user(email): user = User.objects.get(email=email) if not user.is_active: raise AuthenticationFailed("User is inactive", code="user_inactive") return user class OktaASGIMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) self.okta_auth = OKTAAuthentication() async def __call__(self, scope, receive, send): try: # token checking and retrieval claims = self.okta_auth.jwt_verifier.parse_token(token)[1] user = await get_user(claims["email"]) scope["user"] = user except Exception as exc: await send({"type": "websocket.close"}) raise return await self.inner(scope, receive, send) tests.py @aioresponses() async def test_connect_with_correct_token_edit_resource_draft( self, mocked_io_request ): mocked_io_request.get( # mocked request/respones ) communicator = WebsocketCommunicator( application, f"/ws/draft/1/?token={sometoken}" ) connected, subprotocol = await communicator.connect() self.assertTrue(connected) So, the issue is, when I use database_sync_to_async as Docs suggests, I am getting: django.db.utils.InterfaceError: connection already closed. When I use from asgiref.sync import sync_to_async, everything works fine and I can test my consumer properly. Also, i an attempt to avoid database_sync_to_async, I switched from JsonWebsocketConsumer to AsyncJsonWebsocketConsumer, but still no help. NOTE: Both of this code works … -
How can i manage leveldb database to cope with Django framework
i am trying to develop a web application that uses leveldb as a database, knowing that leveldb doesn't support an SGBD,how can i deal with it in order to manage data on django framework I suggest to use a relational data base to manage users,sessions and other standard data, and try to use leveldb just for that purpose that i am using for. -
Incrementing an IntegerField in Django
I'm trying to implement the Polls app like the one in the Django documentation. I have an IntegerField to represent the number of votes an option has in my Polls app but if I try to add the voter to the list of voters and increment it by one in my views.py ever time a user votes, it adds to the user to the list of voters but the vote count doesn't increase. This is my Choice model... votes = models.IntegerField(default=0) voters = models.ManyToManyField(UserProfile, blank=True, related_name="my_votes") This is my vote function in views.py option.votes += 1 user = UserProfile.objects.get(user = request.user) option.voters.add(user) How do i fix this please? -
Django: while updating record: ValueError: Cannot force an update in save() with no primary key
There are similar issues on SO, but none alike this. I would like to update a field in a record of a m2m model which has a unique constraint on attendee + training. This model is defined as (model.py): class Occurrence(models.Model): attendee = models.ForeignKey(Attendee, on_delete=models.CASCADE) training = models.ForeignKey(Training, on_delete=models.CASCADE) attended_date = models.DateField(default=date(1900, 12, 31)) class Meta: constraints = [ models.UniqueConstraint(fields=['attendee', 'training'], name='unique_attendee_training') ] Now, consider e.g. that John has taken the Python course and already exists as record in the db. If I try get the date of when the training occurred, I would go like this: from trainings.models import Attendee, Training, Occurrence from datetime import date, datetime attendee = Attendee.objects.get(pk='john@gmail.com') training = Training.objects.get(pk='python310') occurrence = Occurrence.objects.get(attendee=attendee, training=training) print(occurrence.attended_date) # datetime.date(2021, 11, 4) However, if I try to update the date of this record, I get the error. occurrence = Occurrence(attendee=attendee, training=training, attended_date=date(2021, 11, 5)) occurrence.save(update_fields=["attendee", "training", "attended_date"]) The error being: ValueError: Cannot force an update in save() with no primary key. How do I update this record? Note I believe this should be enough to understand the question. But if you want to reproduce the whole issue, I post here the models (model.py) for Attendees and Trainings. class Attendee(models.Model): … -
Python: cannot pickle '_io.BufferedRandom' object [Django] [Cacheops]
I am setting up django cacheops and I am running into an issue regarding pickling my data. My Models have this kind of structure: class A(models.Model): # ... class B(models.Model): link_1 = models.ForeignkeyField(A) link_2 = models.ForeignkeyField(A) link_3 = models.ForeignkeyField(A) def get_link(self): # function does some checks here, decides if link_1, link_2 or link_3 should be loaded link_to_load = "link_1" # fixed for simplicity return getattr(self, link_to_load, None) When I use cacheops, I get this error: cannot pickle '_io.BufferedRandom' object. It also occurs when I use A.object.get(pk=some_pk) instead of getattr. Has someone a tip, how change my code that it does not happen? -
Filter a Query Set by Reverse Foreign Key
If I have the following: class Asset(models.Model): name = models.TextField(max_length=150) project = models.ForeignKey('Project') class Project(models.Model): name = models.TextField(max_length=150) What argument do I pass to Project.objects.filter() to get all Projects that have no associated Assets. -
django runserver in http
I'm a little new to django so bear with me. I have an app that's running just fine in HTTPS. In settings.py I have this bit of line that enables it: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Out of curiosity, instead of disabling this every time to test pages and applications, is there a way to enable http for only 127.0.1:8000 and not *.example.com? Or is this a bad practice to even attempt? -
I am getting same problem while generating test api key
Please help to resolve this error I opened Paytm dashboard and visited to test api details but it shows nothing. I want test api merchant Id and key. Please help -
Ordering a QuerySet by the first object in a prefetch_related query
If I have the following models, describing Books which can have several different Titles: class Book(models.Model): publisher = models.CharField(max_length=255) class BookTitle(models.Model): work = models.ForeignKey(Book, related_name="titles", on_delete=models.CASCADE) title = models.CharField(max_length=255) I'm fetching a QuerySet of Books, pre-fetching their BookTitles, like this: from django.db.models import Prefetch books = Book.objects.prefetch_related( Prefetch( "titles", queryset=BookTitle.objects.all() ) ) I'd like to be able to order the QuerySet by the first of the BookTitles. How would I do that? (This is a very simplified example of my actual code to explain the basic question.) -
Django IntegrityError at admin, null value of id violates the not-null constraint
I am fairly new to Django and I use Django 4.2 and PostgreSQL's latest version. I have this issue with my code, I have created models for a blog post. In the admin, I am trying to test it out to see if everything is working the way I expect it to, but I have reached an error. I am trying to add tags to the blog post. That is like tags that describe what kind of genre the blog post is. This is what my models.py file looks like: class BlogPost(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) id = models.UUIDField(unique=True, primary_key='True', editable=False) post_title = models.CharField(max_length=300, blank=True, null=True, verbose_name='Title of blog post') post_image = models.ImageField(upload_to='posts/%Y/%m/%d', default='static/images/avatar.jpg', blank=True, null=True, verbose_name='Blog post picture') tags = models.ManyToManyField('Tags', blank=True, verbose_name='Tags seperated by #') post_body = models.TextField(blank=True, null=True, verbose_name='body of user') votes_total = models.IntegerField(default=0, blank=True, null=True) created_time = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.post_title class Tags(models.Model): id = models.UUIDField(editable=False, unique=True, primary_key=True) tag = models.CharField(max_length=200) def __str__(self) -> str: return self.tag class Comments(models.Model): blogpost = models.ForeignKey(BlogPost, on_delete=models.CASCADE, blank=True, null=True) comment_body = models.TextField(blank=True, null=True) VOTE_TYPE = ( ('up', 'UP VOTE'), ('down', 'DOWN VOTE'), ) value = models.CharField(max_length=200, choices=VOTE_TYPE) id = models.UUIDField(editable=False, unique=True, primary_key=True) def __str__(self) -> … -
getting model object returned matching query does not exist
I want to display what user is posted from a Book model when others user visited his public_profile page, to do that, i had to use this method: def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) book = Book.objects.get(slug=slug) context = { 'profile': profile, 'book': book } return render(request, 'public_profile.html', context) But using that method returned: Book matching query does not exist. in the public_profile template. my url to public_profile page: <p class="title is-4"><a href="{{ book.get_user_public_url }}"> {{ book.user }} </a></p> my model class Book(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) audio = models.FileField(upload_to='audio') title = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='audio-image') introduction = models.TextField(max_length=500) slug = models.SlugField(unique=True) def get_user_public_url(self): return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug}) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) profile_photo = models.ImageField(upload_to='profile-image', default='static/dafault.jpg') twitter = models.URLField(blank=True, null=True, unique=True) website = models.URLField(blank=True, null=True, unique=True) linkedln = models.URLField(blank=True, null=True, unique=True) country = models.CharField(max_length=70, blank=True, null=True,) about = models.TextField(max_length=700, blank=True, null=True) slug = models.SlugField(max_length=100, unique=True) -
How to handle errors correctly in django?
I have a question, I know that it is possible to do global exception handling in python, but how to do it for all views, namely, I am interested in DetailView, but others will also come in handy.I understand that you need to give your own examples of solutions, but could you give an example of how this can be done, because I have no ideas at all how to do it. I want to do global error handling so that it can be done like this try: current_profile = Profile.objects.get(user_connected_id=current_user_object) except ObjectDoesNotExist SomeERROR....: logger.info('Object user_connected_id not found....') raise ObjectDoesNotExist And if I don't handle the error that appears, then I want it to work in the global handler. And if it's not difficult: what should I do correctly with errors in this handler, other than logging? I need the DetailView handler most of all -
AttributeError: 'NumberObject' object has no attribute 'indirect_reference'
I've been trying to create multiple pdfs and merge them using pypdf (Version 3.7.1). The static data such as images and fonts render out perfectly within the html but don't in pdfs. Following is my code and the error I'm encountering query_set = booklet.objects.filter(booklet_id = id) combine = [] for i in query_set: size = i.size options = { 'page-size': f'{size}', 'orientation': 'Landscape' if i.template_mode == "2" else "Portrait", 'margin-top': '0mm', 'margin-right': '0mm', 'margin-bottom': '0mm', 'margin-left': '0mm', 'encoding': "UTF-8", 'dpi': 900 } url = f"http://ipaddress/test?ids={get_ids}&uuid={i.uuid}&size={i.size}&mode={i.mode}&type_set={i.te_type}&template={i.name}&pre{id.id}" pdfkit.from_url(url, output_path=f"{file_path}/pdfs/{i.te_type}_{i.name}_{i.id}_.pdf", options=options, verbose=False) combine.append(f"{file_path}/pdfs/{i.te_type}_{i.name}_{i.id}_.pdf") merger = PdfWriter() for pdfs in combine: merger.append(pdfs) pdf_name = "base.pdf" merger.write(pdf_name) merger.close() return JsonResponse({"pdf" : pdf_name"}) I have tried cnfiguring the nginx file, thinking it could be the case but it is not I have tried modifying my code and relocating static folder to no success. I have tried rendering static images into a separate template but as i mentioned above they render in just fine but not in the pdf generated by pypdf -
Pycharm professional syntax highlighting for JS contained in a block inside a script tag
While writing JS for a Django application using the Django templating language, I am getting a weird formatting problem as below: Defining a domready block in the base.html file: <script> const csrftoken = Cookies.get('csrftoken'); document.addEventListener('DOMContentLoaded', (event) => { //DOM loaded {% block domready %} {% endblock %} }) </script> Using the block in another template file list.html: {% extends "base.html" %} {% block domready %} var page = 1; var emptyPage = false; var blockRequest = false; window.addEventListener('scroll', function (e) { var margin = document.body.clientHeight - window.innerHeight - 200; if (window.pageYOffset > margin && !emptyPage && !blockRequest) { blockRequest = true; page += 1; fetch('?images_only=1&page=' + page).then(response => response.text()).then(html => { if (html === "") { emptyPage = true; } else { var imageList = document.getElementById('image-list'); imageList.insertAdjacentHTML('beforeend', html); blockRequest = false; } }) } }); // start a synthetic scroll event on page load so that the next page loads in case the browser window is big enough const scrollEvent = new Event('scroll'); window.dispatchEvent(scrollEvent); {% endblock %} Pycharm's formatting for JS code is not working in the list.html file. Is there any way to force Pycharm Professional to highlight the syntax and format the JS code in the domready block … -
Invalid JSON error reported whenever a PointField is saved with the GooglePointFieldWidget in the Django admin
I am using Django 4.1 and GooglePointFieldWidget (from django-map-widgets) on PointFields (from django-geojson). The widget gets displayed as it should and I'm able to change the coordinates, set a marker on the map or even type in an address. All good. The problem is that I'm getting a validation error upon saving the object because GooglePointFieldWidget fills in the hidden textarea of the field with invalid JSON, something like POINT (26.2616671966018 65.06716787213769) when Django expects something like {'type': 'Point', 'coordinates': [26.2616671966018, 65.06716787213769]} How can I solve this validation error? -
Wagtail 500 server error with DEBUG=False
I deployed the Wagtail site on Ubuntu 22.04 following digitalocean's instructions (Nginx + Gunicorn). The site works without errors when DEBUG=True, but when I put False I get Server Error (500) when going to any page. At the same time admin panel works without errors, path to static files is correct. Error.log nginx are clean. What can be the problem? I have already tried everything. gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user1 Group=www-data WorkingDirectory=/home/user1/projectdir ExecStart=/home/user1/projectdir/env/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ --env DJANGO_SETTINGS_MODULE=projectname.settings.production \ projectname.wsgi:application [Install] WantedBy=multi-user.target nginx config: server { listen 80; server_name mysite.com www.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/user1/projectdir/static/; } location /media/ { alias /home/user1/projectdir/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
How do I fix this errors when running my tests
from django.conf import settings from django.utils.functional import cached_property from regulus_oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): def __str__(self): """ Appends the variant-identifier product attribute values to the string representation of child products, for use in multiple places, including on the front end and dashboard, and in emails to customers and the merchant. """ if self.is_child and self.variant_attribute_summaries: # The parent "__str__" method appends a summary of all the product # attribute values, whereas we only want to include a summary of the # variant-identifier ones return f"{ self.title if self.title else self.parent.title } ({ self.variant_attribute_summaries })" else: return super().__str__() def get_title(self): """ Appends the variant-identifier product attribute values to the title of child products, for use in multiple places, including on the front end and dashboard, and in emails to customers and the merchant. """ title = super().get_title() if self.is_child and self.variant_attribute_summaries: title = f"{ title } ({ self.variant_attribute_summaries })" return title get_title.short_description = "Title" @cached_property def variant_attribute_summaries(self): """ Returns a string of a product's variant-identifier ("Colour" and "Size") product attribute values. """ return ", ".join( [ product_attribute_value.summary() for product_attribute_value in self.get_attribute_values().filter( attribute__name__in=settings.NSH_VARIANT_PRODUCT_ATTRIBUTE_NAMES ) ] ) from regulus_oscar.apps.catalogue.models import * # noqa isort:skip Above is my models.py file and everything works as … -
Django- Object of type Product is not JSON serializable
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/orders/create/ Traceback (most recent call last): File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\middleware.py", line 59, in process_response request.session.save() File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\backends\db.py", line 82, in save obj = self.create_model_instance(data) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\backends\db.py", line 69, in create_model_instance session_data=self.encode(data), File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\backends\base.py", line 94, in encode return signing.dumps( File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\signing.py", line 150, in dumps return TimestampSigner(key, salt=salt).sign_object( File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\signing.py", line 228, in sign_object data = serializer().dumps(obj) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\signing.py", line 125, in dumps return json.dumps(obj, separators=(",", ":")).encode("latin-1") File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' Exception Type: TypeError at /orders/create/ Exception Value: Object of type Product is not JSON serializable I am trying to serialize it using product=json.dumps(item['product'],cls=DjangoJSONEncoder) but i still get the same error. There are many questions like these but i am not able to connect the dot.Thanks def create_order(request): cart=Cart(request) if request.method=='POST': form=OrderCreateForm(request.POST) if form.is_valid(): order=form.save() for item in cart: #product=json.dumps(item['product'],cls=DjangoJSONEncoder) … -
How to get (Parent) objects by filtering its child model?
I have researched some (answer, answer)s but didn't get what I want. So I have two models: models.py class TvProgram(TimeStampedModel): name = models.CharField(max_length=512) class TvProgramSchedule(TimeStampedModel): tvprogram = models.ForeignKey( to=TvProgram, on_delete=models.CASCADE ) schedule = models.DateTimeField() I want to get Tvprograms (Parent) which its children's schedules are only for the 7 days, In my case I am getting tvprograms with its all children. Is there a way to retrieve all the Parent objects that are in the filtered querysets? -
How to pass class name with model to the Django Admin site register?
I have a couple of models and I created some classes in admin.py for the column list view as below: class AppleAdmin(admin.ModelAdmin): pass class OrangeAdmin(admin.ModelAdmin): pass class BananaAdmin(admin.ModelAdmin): pass class GrapesAdmin(admin.ModelAdmin): pass I'm trying to concatenate the model name with Admin (AppleAdmin) and pass the class name to the register parameter. for model in app_modules: ma = str(model.__name__+'Admin') if ma : try: admin.site.register(model, ma) except: pass Any help would be much appreciated. -
Django does not have access to environment variable
I want to deploy my Django site to DigitalOcean App Platform so I copy the settings from their official sample app (https://github.com/digitalocean/sample-django/blob/main/mysite/settings.py). And here's the problematic part: ... import os ... # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases if os.getenv('DJANGO_DEVELOPMENT_MODE', 'False') == 'True': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv('DATABASE_URL', None) is None: raise Exception('DATABASE_URL environment variable is not set') DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL')), } When I fire up the development server, I get this error: ... raise Exception('DATABASE_URL environment variable is not set') Exception: DATABASE_URL environment variable is not set This tells me the if statement is evaluated to False even though I have this environment variable: I create a same System variable: But I get the same error. Now I go to Python shell and test this: Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print(os.getenv('DJANGO_DEVELOPMENT_MODE', 'False') == 'True') True >>> print(os.getenv('DJANGO_DEVELOPMENT_MODE')) True >>> The environment variable looks fine. At this point I go back to settings.py and edit the if statement like this: ... … -
How can i fix the 'Web application could not be started' error in passenger_wsgi.py
So, i try to install django and python on my server and get this error. Error 'ModuleNotFoundError: No module named 'django'' File passenger_wsgi.py looks so: passenger_wsgi.py. I also check path to django and looks like here it is. django module is here Help, pls! I tried to reinstall all modules, but it also doesn't work.