Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot open downloaded zip file
I want to download a note with all attached files to a zip file in Django by clicking a button. That's the view: def download_note(request, pk): note = get_object_or_404(Note, pk=pk) file_path = f'notes/media/downloaded_notes/note{note.id}.txt' notefiles = NoteFile.objects.filter(note=note) urls = [f.file.url for f in notefiles] if get_language() == 'en': content = f'Title: {note.title}, Author: {note.user}, Date: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \ f'Category: {note.category}\n' \ f'Note:\n{note.note_text}' else: content = f'Tytuł: {note.title}, Autor: {note.user}, Data: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \ f'Kategoria: {note.category}\n' \ f'Notatka:\n{note.note_text}' with open(file_path, 'w', encoding='utf-8') as f: f.write(content) zip_file_path = f'notes/media/downloaded_notes/note{note.id}.zip' with zipfile.ZipFile(zip_file_path, 'w') as zipf: zipf.write(file_path, os.path.basename(file_path)) media_root = settings.MEDIA_ROOT.replace('\\', '/') print(media_root) for url in urls: print(f'{media_root}{url[6:]}') #file_url = os.path.join(media_root, url[6:]) #zipf.write(file_url, os.path.basename(url[6:])) file_name = os.path.basename(url) zipf.write(f'{media_root}{url[6:]}', file_name) with open(zip_file_path, 'rb') as f: response = FileResponse(f.read(), content_type='application/zip') response['Content-Disposition'] = f'attachment; filename="note{note.id}.zip"' return response When I click download button Chrome hangs for few seconds and then file is downloaded. But zip file in Downloads directory is not working. When I am trying to open it there is a message saying that the file's format is invalid or file is broken. But when I go to django project and to media/downloaded_notes/note70.zip everything works fine. So I think an issue is in this fragment: with open(zip_file_path, 'rb') … -
How can I add or do some multiplcations and let my user change their CharField values in Django Application
I need an Explanation and Advice to make my small project like I would given my users "money, not real money just some numbers" and let them spend on my items and I need a way to know how can I make the money usable on the money they have like addition the money amount and subtraction on the amount of their money, I need an Advice and Explanation please. I've tried to do these things and they are not working, my mind is blowing and I need help -
How to filter an item in one queryset from appearing in another queryset in django
I have a Django view where I am getting the first queryset of 'top_posts' by just fetching all the Posts from database and cutting it in the first four. Within the same view, I want to get "politics_posts" by filtering Posts whose category is "politics". But I want a post appearing in 'top_posts', not to appear in 'politics_posts'. I have tried using exclude but it seems like it`s not working. Below is my view which is currently not working: def homepage(request): top_posts = Post.objects.all()[:4] politics_posts = Post.objects.filter(category='news').exclude(pk__in=top_posts) context={"top_posts":top_posts, "politics_posts":politics_posts} return render(request, 'posts/homepage.html', context) Any help will be highly apprecuiated. Thanks. -
how to do dependent drop down in Django
how to do dependent drop down in Django, showing errors anyone [enter image description here] (https://i.stack.imgur.com/vMzmb.png) how to get output like branches corresponding to states [enter image description here] (https://i.stack.imgur.com/fR5lj.png) is it possible without Django forms, only with views -
How can I store the response from a third party API as instance in a Django model
I am building a web API in DRF. And there's this third party API whose response returns fields like ip_address, latitude, longitude, etc. I have a user model(which is basically inherited from an AbstractBaseUser) that contains fields like email, username, first_name and last_name. Creating an instance of this user model works. But what I want to do is save response from this third party API as an instance of a model called Artist that has a OneToOneField with the user model whenever an instance of this user model is saved. How can I do this? Note: I am letting Djoser, a third party library for handling authentication, take care of the authentication endpoints on my user model. So no views involved in this project so far yet it works. -
grouping is giving wrong data if order_by is added
I have a model Lead. It has column deal_value. I want to get the count of leads for the given buckets for deal_value. Buckets are from 0 to 1000 --> '<=1000' from 10001 to 100000 --> '<=100000' So I annotate the queryset with 'bucket' and group by bucket and perform aggregation on it. below is the code: import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'design_studio_app.settings') django.setup() from dashboard.utils import get_accessible_objects_for_a_user from accounts.models import User from dashboard.qfilters import get_q_created_at from django.db.models import Case, When, CharField, Value from django.db.models import Count user = User.objects.get(pk=1529) # get the queryset queryset = get_accessible_objects_for_a_user( 'Leads', user) # get the leads which are created this month queryset = queryset.filter(get_q_created_at('this_month')) queryset = queryset.order_by('deal_value') measure_group_metric = 'deal_value' min_value = 0 max_value = 100000 queryset = queryset.filter( **{measure_group_metric+"__gte": min_value, measure_group_metric+"__lte": max_value}) case_conditions = [ When(**{measure_group_metric+"__gte": 0, measure_group_metric+"__lte": 1000}, then=Value('<=1000')), When(**{measure_group_metric+"__gte": 10001, measure_group_metric+"__lte": 100000}, then=Value('<=100000')) ] queryset = queryset.annotate( bucket=Case( *case_conditions, default=None, output_field=CharField(), ) ) annotated_data = queryset.values('bucket').annotate(count=Count('id',allow_distinct=True)) print(annotated_data) The annotated_data is <SoftDeleteQuerySet [{'bucket': '<=1000', 'count': 26}, {'bucket': None, 'count': 1}, {'bucket': '<=100000', 'count': 8}, {'bucket': '<=100000', 'count': 1}, {'bucket': '<=100000', 'count': 1}]> So the count is wrong. we can see that bucket bucket': '<=100000' is repeated. However if I remove order_by('deal_value'). … -
Problem in Django Testing with Selenium ( TypeError : expected str, bytes or os.PathLike object, not NoneType )
I am currently running a testing to check whether if there is any problem with client-side rendering in Django. Therefore, I am running a loop to visit every route available in the Django project and record the browser console. The code is as follows : class SeleniumTest2(LiveServerTestCase): def setUp(self) -> None: super(MySeleniumTests, self).setUp() User = get_user_model() self.superuser = User.objects.create_superuser('superuser', 'superuser@example.com', 'password') self.client.login(username='superuser', password='password') models = apps.get_models() factories = generate_dynamic_factories_2(models) for model_name, factory_class in factories.items(): instances = factory_class.create_batch(10) for instance in instances : instance.save() def tearDown(self): self.selenium.quit() super(MySeleniumTests, self).tearDown() if(check_library_selenium()): def test_client_side(self): urls = get_urls() driver = webdriver.Edge() live_server = self.live_server_url for url in urls: driver.get( str(live_server) + url) # Print or use the console output as needed logs = driver.get_log('browser') print(url, logs) driver.quit() else : print(RED+'Client-side checker skipped'+RESET) And the error are as follows : Traceback (most recent call last): File "/Users/zulfathihanafi/.pyenv/versions/3.9.16/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1723, in __call__ return super().__call__(environ, start_response) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ response = self.get_response(request) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1706, in get_response return self.serve(request) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1718, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/views/static.py", line 34, in serve fullpath = Path(safe_join(document_root, path)) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/utils/_os.py", line 17, … -
Django Installation on Windows 10
I'm a newbie when it comes to Django framework, just want to ask if what drive is it recommended to install Django, should I follow YT vids that installs on desktop or should I put it in more specific path. Thanks As for now I haven't tried to install it, I'm still gathering opinions from experts to reduce flaws and errors in the future. :) -
django.db.utils.OperationalError: (2002, "Can't connect to server on 'mysql' (115)")
I did find some related questions, but the answers don't work. I think the problem might be the configuration problem. When I run sudo docker-compose up, it create 4 images. But the error occurs like that: rest | Performing system checks... rest | rest | System check identified no issues (0 silenced). rest | Exception in thread django-main-thread: rest | Traceback (most recent call last): rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection rest | self.connect() rest | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner rest | return func(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect rest | self.connection = self.get_new_connection(conn_params) rest | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner rest | return func(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection rest | connection = Database.connect(**conn_params) rest | File "/usr/local/lib/python3.10/site-packages/MySQLdb/__init__.py", line 121, in Connect rest | return Connection(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/MySQLdb/connections.py", line 193, in __init__ rest | super().__init__(*args, **kwargs2) rest | MySQLdb.OperationalError: (2002, "Can't connect to server on 'mysql' (115)") rest | rest | The above exception was the direct cause of the following exception: rest | rest | Traceback (most recent call last): rest | File "/usr/local/lib/python3.10/threading.py", line 1016, in _bootstrap_inner rest | self.run() rest … -
Is there a way to use chain and group with celery?
Im building a solution using python, django rest framework, celery and rabbitmq to run some tasks in my api project. However some tasks may be done in parallel and others not. I tried this solution using chord and group, but in these two ways the last task(task_9) never is executed, all the others previous tasks are executed with success. When i tried chord i put task_9 as a callback function, but even this doesn't work. Here is an example of my code. chain(task_1.si(registry_id, name) | task_2.si(registry_id, name) | task_3.si(registry_id, name) | group(task_4.s(task_3_result), task_5.s(task_3_result), task_6.s(task_3_result), task_7.s(task_3_result), task_8.s(task_3_result), ) | task_9.si(registry_id, name) ).apply_async() -
Django settings.py can't import my local module
My Django tree looks like this git/src ├── myproject │ ├── settings.py │ ├── mysharedlib.py │ └── urls.py └── www ├── urls.py └── views.py It works except that in settings.py I have import mysharedlib But this raises an exception ModuleNotFoundError: No module named 'mysharedlib' Why isn't this working? -
Forbidden: /api/v1/token/logout/ "POST /api/v1/token/logout/ HTTP/1.1" 403 58
I am experiencing this problem following a tutorial and I can't identify the error in my "MyAccountView.vue" page. I tried changing to re_path and it did not work. Forbidden: /api/v1/token/logout/ [16/Oct/2023 19:01:35] "POST /api/v1/token/logout/ HTTP/1.1" 403 58 CODE: URLS.PY from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')) ] SETTING.PY REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSESS':( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSESS':( 'rest_framework.permissions.IsAuthenticated', ) } ERROR IMAGES Getting this error in browser's console MyAccountView.vue If it works i'm supposed to forward on "/" or home page of my site. methods: { logout() { axios .post("/api/v1/token/logout/") .then(response => { axios.defaults.headers.common["Authorization"] = "" localStorage.removeItem("token") this.$store.commit('removeToken') this.$router.push('/') }) .catch(error => { if (error.response) { console.log(JSON.stringify(error.response.data)) } else if (error.message) { console.log(JSON.stringify(error.message)) } else { console.log(JSON.stringify(error)) } }) } } -
How can I serialize the Transaction model in django rest framework
There are two reasons why the Transaction model should have a sender and receiver and assign them to the CustomUser model with different related names. It could help answer questions like: Who initiated the Transaction? Who received the funds? We want to serialize this model because our company intends to use React.js as the frontend of the application. I would like to know how to validate the serialization to ensure that the sender can send funds from their account to another. As you can see this view, I created it based on django template: def transfer(request): if request.method == 'POST': account_number = request.POST['account_number'] amount = Decimal(request.POST['amount']) superuser_account = Account.objects.get(user='superuser username') # set this username to the admin username or your preferred account. sender_account = Account.objects.get(user=request.user) receiver_account = Account.objects.get(account_number=account_number) interest_rate = 0.02 deduction = amount * interest_rate if sender_account.account_balance >= amount: sender_account.account_balance -= amount sender_account.save() receiver_account.account_balance += amount receiver_account.save() superuser_account.account_balance += deduction superuser_account.save() Transaction.objects.create( sender=request.user, receiver=receiver_account.user, amount=amount, account_number=account_number ) return redirect ('Transfer') else: messages.error(request, 'Insufficient Funds') return redirect ('Transfer') return render(request, 'transfer.html') This view checks if the sender account balance is greater than or equal to the specified transfer amount. If the sender doesn't have enough funds, it sets an error … -
Regex for username allows for more than one special character
The regex I have is not working as I intend it to. It should not allow for more than one special character and the special character should not be the starting character of the username. The below regex allows for more than one special character and it also for the special character to be the starting character. regex=r'^(?=.{6,15})(?=.*[a-z])(?=.*[@-_]).*$', Valid Input : user@site Invalid Inputs, user@@site, @usersite I tried to alter the Regex it mulitple ways, but not able to achieve the desired output -
How to assign user and user.profile to the request object using a single database query in django?
Django assign user to request in the django.contrib.auth.middleware.py by calling request.user = SimpleLazyObject(lambda: get_user(request)) The get_user function is in the init.py file which in turns calls another get_user function in the backends.py def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None Here it is making a database call to get user by id. How can I get the user profile(related to user by a one to one field) in the same query and propagate it back so I can assign it to request.profile? -
Follow up to https://stackoverflow.com/questions/77300502/django-turn-off-on-pagination-for-one-filter-request/77300948#77300948
As mentioned in the question from title, I have 2 models, 1 Product and 1 for ProductImages. class Product(models.Model): title = models.CharField(max_length=200) details = models.TextField(null = True) slug = models.CharField(max_length=300, unique=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs') image = models.ImageField(upload_to='product_imgs/', null=True) def __str__(self): return self.image.url My view for fetching list of products is, def get_queryset(self): qs = super().get_queryset() if self.request.method == 'GET': if 'category' in self.request.GET: category = self.request.GET['category'] category = models.ProductCategory.objects.get(id=category) qs = qs.filter(category=category) if 'owner' in self.request.GET: print('get_queryset Owner') owner = self.request.GET['owner'] qs = qs.filter(owner=owner) if 'available' in self.request.GET: available = self.request.GET['available'] == 'true' qs = qs.filter(available=available) results = [] for product in qs: images = models.ProductImages.objects.filter(product=product.id) results.append({'product': product, 'images': images}) return JsonResponse({ 'status': 'success', 'result': results, }) I am getting an error saying TypeError: Object of type Product is not JSON serializable on line return JsonResponse({ I couldn't find a solution for returning response which is combination of 2 different models. Can anybody please help me solving this issue? PS: I don't want to get the list of products in frontend and then make network call/calls to get images associated with them. -
DRF spectacular creates tags, can't figure out where to remove(
class EquipmentViewSet(ReadOnlyModelViewSet): queryset = Equipment.objects.all() serializer_class = EquipmentSerializer @extend_schema( summary='Получение списка всех объектов класса "Оборудование"', tags=['Equipment'], description=""" Получение списка всех оборудования. В ответе будет получен полный список объектов класса "Оборудование". """, request=EquipmentSerializer, responses=equipment_status_codes ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) In the swager, in addition to tags=['Equipment'], tag = v1 is created where /api/v1/equipment/{id}/ is located. I tried everything, I want to cry, extend_schema_view doesn't help in any way -
How to get rid of this extra gap in my Django website?
I deployed this website, which can be seen by pasting the URL in the browser. RFP Website If you see the homepage, you can see that on the right, it seems to scroll infinitely and I am getting a huge gap, which is not in other pages. How to get rid of this? -
How can I properly Query data from a django model without
im trying to create a simple django app for buying and selling shares but im having trouble querying my data properly specifically the amount of available shares. These are my models: from django.db import models from accounts.models import CustomUser class Share(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) quantity_available = models.PositiveIntegerField() def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) share = models.ForeignKey(Share, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_price = models.DecimalField(max_digits=10, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) is_purchase = models.BooleanField() then these are my views: from django.shortcuts import render, redirect from .models import Share, Transaction from .forms import BuyShareForm, SellShareForm def buy_share(request): share = Share.objects.filter(quantity_available__gt=100) form = BuyShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] if quantity <= share.quantity_available: transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=True) transaction.save() share.quantity_available -= quantity share.save() return redirect('shares:buy-success') else: form.add_error('quantity', 'Insufficient shares available') context = { 'share': share, 'form': form, } return render(request, 'shares/buy_share.html', context) def sell_share(request): share = Share.objects.all() form = SellShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=False) transaction.save() share.quantity_available += quantity share.save() return redirect('shares:sell_success') return render(request, 'shares:sell_share.html', {'form': form}) when i try to get the … -
Cannot redirect with forwardauth Traefik middleware
How to actually switch(redirect) to another page (login page) with Traefik ForwardAuth ? I'm using the following docker labels: 'traefik.http.routers.my-route.rule=Host("main.int")' 'traefik.http.routers.my-route.entrypoints=https443' 'traefik.http.routers.my-route.tls=true' 'traefik.http.routers.my-route.middlewares=my-test-auth@docker 'traefik.http.middlewares.my-test-auth.forwardauth.address=https://auth.page.int/login/' 'traefik.http.middlewares.my-test-auth.forwardauth.tls.insecureSkipVerify=true' Traefik logs shows that is accessing the auth.page.int/login page: GET /accounts/login/ HTTP/2.0" 200 3459 but browser stays on the main page. BTW redirect works with RedirectRegex middleware for the same example. Documentation: https://doc.traefik.io/traefik/middlewares/overview/ -
React axios get parameter is undefined
I want to get some data from an api with a parameter current user's username. useEffect(()=>{ console.log(currentUser[0]?.id.toString()) if (currentUser) { console.log(currentUser[0]?.id.toString()) axios.get(`http://127.0.0.1:8000/get_chat2/?user1=${currentUser[0]?.id.toString()}&user2=`).then(res=>{ setUsers(res.data) console.log(res.data) }) },[currentUser]) When I print currentUser[0]?.id.toString() I get user's id but when I send the request it is undefined. I tried doing it a string but it still is undefined. Also when instead of id I use the username it isn't undefined. -
How to debug a 502 error for a Docker compose app?
An application that I'm maintaining (I'm not the one who created it, so my knowledge of it is limited) is deployed via Docker compose and consists of the following containers: name what is status servey_prod_bot a Telegram bot works ... helper services for bot, of no interest in this context servey_prod_stat reports new data works servey_prod_app admin web app not accessible (see below) servey_prod_nginx well, Nginx works servey_prod_db db works Recently, I was asked to modify the _stat component, and, long story short, that forced me to rebuild the whole thing and restart the containers, and some code changes might get applied. The _bot and the _stat seem to work nicely, the _app is also up, but now an attempt to get it via browser fails with 502. What I have done to debug this already: the _app (it's a Django app): I've checked docker logs and shows that it successfully started gunicorn, listens to http://0.0.0.0:9090 and has 3 workers (on restart workers exited and the app is shut down, then restarted successfully; no migrations involved); I've also checked nc -zv localhost 9090 and nc -zv 0.0.0.0 9090 inside the container, both report that the port is open; finally, I've … -
Django Turn off/on pagination for one filter request
I have 2 models, 1 for Product and 1 for ProductImages with pagination set to 10. For any product, we can have associated multiple images. class Product(models.Model): title = models.CharField(max_length=200) details = models.TextField(null = True) slug = models.CharField(max_length=300, unique=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs') image = models.ImageField(upload_to='product_imgs/', null=True) def __str__(self): return self.image.url My ProductList view looks like, class ProductList(generics.ListCreateAPIView): queryset = models.Product.objects.all() serializer_class = serializers.ProductListSerializer pagination_class = pagination.PageNumberPagination def get_queryset(self): qs = super().get_queryset() if self.request.method == 'GET': if 'category' in self.request.GET: category = self.request.GET['category'] category = models.ProductCategory.objects.get(id=category) qs = qs.filter(category=category) if 'owner' in self.request.GET: print('get_queryset Owner') owner = self.request.GET['owner'] qs = qs.filter(owner=owner) if 'available' in self.request.GET: available = self.request.GET['available'] == 'true' qs = qs.filter(available=available) ids = [] for product in qs: # images = models.ProductImages.objects.filter(id=product.id) print('Images: %d', product.id) ids.append(product.id) for id in ids: print('Id %d', id) images = models.ProductImages.objects.filter(product__in=ids) I am trying to fetch products and images associated with those products. When I fetch products I get 10 products (as per set pagination) and I get 10 images. But problem is I want to get all (say) 25 images associated with those 10 products, i.e. I want to turn off the pagination only for filter on ProductImages … -
How To Upload and Display Images in Django 4.2.5 on Whogohost
I have developed my Django application using Django 4.2.5. And locally it is uploading and displaying images fine but on production server it is uploading but not displaying the uploaded images. I have check the url of the images on my HTML Templates while on the server using DevTools but it seems to be pointing rightly. I don't know whether this has to do with some dependencies of sort. So someone should help. See my Model Code: from imagekit.models import ProcessedImageField from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from imagekit.processors import ResizeToFill, Transpose #File Extension Validator @deconstructible class FileExtensionValidator: """ImageKit Validation Decorator""" def __init__(self, extensions): self.extensions = extensions def __call__(self, value): extension = value.name.split('.')[-1].lower() if extension not in self.extensions: valid_extensions = ', '.join(self.extensions) raise ValidationError(f"Invalid file extension. Only {valid_extensions} files are allowed.") image_extensions = ['jpeg', 'jpg', 'gif', 'png'] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=20, blank=True) # 'admin', 'cashier', 'customer' full_name = models.CharField(max_length=60, blank=True) phone = models.CharField(max_length=14, blank=True) address = models.CharField(max_length=160, blank=True) is_active = models.BooleanField(default=True) image = ProcessedImageField( upload_to='profile_images', processors=[Transpose(), ResizeToFill(150, 200)], format='JPEG', options={'quality': 97}, validators=[FileExtensionValidator(image_extensions)], default='avatar.jpg' ) last_updated = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user.username}-Profile' See the url to displaying the images: <img class="img-thumbnail" src=" {{ user.profile.image.url … -
Django session cookie is not being set in production
I have a Django application I just moved to production. I am unable to make the site display I am logged in. It works fine on my local machine and I do not see any errors in production and the username and password is correct. The problem the session cookie is not being set and my settings are correct I believe. Here are my settings related to sessions: DEBUG = False ALLOWED_HOSTS = ["localhost","102.219.85.91","founderslooking.com","app.founderslooking.com"] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1", "http://localhost:file", "http://app.founderslooking.com", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN = "founderslooking.com" #SESSION_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://*.127.0.0.1", "http://app.founderslooking.com",] INTERNAL_IPS = [ "127.0.0.1", ] I am not using https because I am only testing the site until I am sure everything works, then I will switch over to https. Why is the session cookie not being set? The application is on a VPS using Ubuntu, Gunicorn, Nginx and Supervisord