Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got KeyError when attempting to get a value for field `date` on serializer
Im trying to do a queryset to show date__month and total of all sale_prices class RevenueChartListView(ListAPIView): queryset = Transactions.objects.annotate(month=ExtractMonth('date')).values('month').annotate(revenue=Sum('sale_price')).order_by('month') serializer_class = RevenueSerializer class RevenueSerializer(serializers.ModelSerializer): class Meta: model = Transactions fields = ['date', 'sale_price'] However I get an error of "Got KeyError when attempting to get a value for field `date` on serializer `RevenueSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'date'." -
Django - Create excel file from response with openpyxl and convert it to pdf in the same function
In Django app (ubuntu server online) I know how to create an xlsx file from HttpResponse with openpyxl using this piece of code : views.py def export_to_excel(request): movie_queryset = models_bdc.objects.all() response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-movies.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() # Get active worksheet/tab worksheet = workbook.active worksheet.title = 'Movies' # Define the titles for columns columns = [ 'ID', 'Title', 'Description', 'Length', 'Rating', 'Price', ] row_num = 1 # Assign the titles for each cell of the header for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title # Iterate through all movies #try to sort by index here and ignore empty rows # apply a save to DB before export to excel to get the latest changes for movie in movie_queryset: row_num += 1 # Define the data for each cell in the row row = [ movie.bdc_description_1, movie.bdc_description_2, movie.bdc_description_3, movie.bdc_description_4, movie.bdc_description_5, movie.bdc_description_1, ] # Assign the data for each cell of the row for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response But I would also like to convert the generated .xlsx as a .pdf file. I don't know what approach is the … -
Django Custom Dynamic urlpatterns
I'm working on a django project and in this project I have two subprojects. So in this case what I want to do is store domains and assign services (my subprojects) to these domains. For example, let's say I have service1 and service2. And in my domains table I store: service1.domain.com -> service1 domainforservice1.com -> service1 service2.domain.com -> service2 domainforservice2.com -> service2 something like this. So in this case I'm struggling with some issues, because I want to control the domain that request made and according to that domain I can find which service I should load on the main path. So basically we want to make this control: if domain.service = service1: urlpatterns += path('', service1.urls) if domain.service = service2: urlpatterns += path('', service2.urls) But the problem is as we can't take the domain in this area from request we can't make this control. I have tried to write middleware for this and I get the domain address in request.domain but again we have the problem because middleware is executed before this urls.py file. So in this case I'm stuck and can't find a solution to resolve this problem. -
How can I make a web GUI that lets me draw digits freehand?
I've created a neural network that recognises digits trained on the mnist dataset. I have been trying to make a drawing canvas, which I so desperately wanted to integrate into an app built with streamlit(a python framework for web). I made something like that in html and javascript and then tried to integrate, but it doesn't work since there's sudden refreshes by the framework. Anyways I give up. I will recreate the program in something else - maybe Flask or Django. I am wondering how do I recreate the drawing canvas to look like the mnist digits. For reference: You can notice not all pixels are fully white or black. I am trying to recreate this video: https://youtu.be/hfMk-kjRv4c?si=GCUYEDbj3MGWnUq8 in which the guy managed to do that: [] But his source code - https://github.com/SebLague/Neural-Network-Experiments/tree/main/Assets/Scripts/Drawing is in unity and I can't understand it. Someone have any idea how to replicate it using python and with which framework - there will be many UI elements before the drawing so I am wondering do I use Flask or Django or something like that. if I have to use pygame I'll have to choose a service in which it is possible to embed it -
Pycharm start project is not creating venv
When I start a project with Pycharm and try to start a project, my virtual environment directory is not being created. Here is what it looks like on my computer: My start project picture where the location line of the virtual environment does not include the venv directory Now I can manually create a venv by using python -m venv venv then use .\env\scripts\activate but doing so is messing up my template folder location and static location. When I start a project I also used to create an app. I kept my static and templates folder inside the app. But when I go to settings.py in the project I can not find my static and templates folder in suggestion. Even if I manually include them, when running the project I see this warning prompt: Cannot resolve file 'icon.jpg' %} But when I run the project the js files and all the static files are included properly. I thought it could be due to the previous browser cache. So I cleaned the whole browser and ran the project, but it runs absolutely fine. My problem there is that my static files don't show up in suggestions then. I am not new … -
install django in colab
I try to execute django server in colab but don't work I write in colab: !pip install django !django-admin startproject portfolio %cd portfolio/ modify setting.py ALLOWED_HOSTS = ['colab.research.google.com'] from google.colab.output import eval_js print(eval_js("google.colab.kernel.proxyPort(8000)")) !python manage.py runserver 8000 then I open chrome with print(eval_js("google.colab.kernel.proxyPort(8000)")) string the browser show: error 403 That’s an error. That’s all we know. -
No module named 'django' when debugging inside vscode even though django is installed
I am trying to debug my django app inside docker container. I have specified following in my requirements file: Django==3.2.5 psycopg2-binary==2.9.1 djangorestframework==3.12.4 django-rest-swagger==2.2.0 I am installing these dependencies inside my Dockerfile: RUN pip install -r requirements.txt Also when I checked by attacking vscode to docker container and running pip, it shows that the django is indeed installed: # pip list | grep Django Django 3.2.5 However, still I get the error: ModuleNotFoundError: No module named 'django' Here is the screenshot of error showing exception raised in debug mode, launch.json and output of pip list | grep Django: PS: I am using docker compose to start the containers. -
How to make password hashing in django project, i am using custom autentication for login?
I want to make password hashing possible for a django project. views.py for login. def asset_login(request): if request.method == 'POST': username = request.POST.get('user_id') password = request.POST.get('password') try: user = UserTable.objects.get(username=username, password=password) if user: if user.status == 'inactive': messages.error(request, 'Your account is inactive.') return redirect('asset_login') request.session['name'] = user.name request.session['role'] =user.role if user.role == 'admin': return redirect('admin_dashboard') elif user.role == 'ciso': return redirect('ciso_dashboard') elif user.role == 'fnhead': return redirect('fnhead_dashboard') elif user.role == 'systemadmin': return redirect('systemadmin_dashboard') elif user.role == 'assetowner': return redirect('assetowner_dashboard') else: messages.error(request, 'Unknown user position') return redirect('asset_login') # Redirect to clear form and message except UserTable.DoesNotExist: messages.error(request, 'Invalid username or password') return redirect('asset_login') # Redirect to clear form and message return render(request, 'asset.html') models.py for username and password class UserTable(models.Model): sl_num = models.CharField(max_length=100) name = models.CharField(max_length=100) phone_no = models.CharField(max_length=100) email = models.EmailField(blank=False, null=False) location = models.CharField(max_length=100) department = models.CharField(max_length=100) status = models.CharField(max_length=100) role=models.CharField(max_length=100) username=models.CharField(max_length=100) password=models.CharField(max_length=100) def __str__(self): return self.name I want to make paasword hasing possible on django project , i am using custom authentication instead of django build in autentication. -
I have created a django app and I want to run a function and a view both asynchronous
this is the django view file code. i have a function which has no parameters and no return since im using global variables in the code. I am currently using threads and there is an issue. when the startfunc() is running and executing some code, and the data is received at the same time in the view, it just distrupts the startfunc() and the whole process is incomplete which is a big issue for me and the for the app. That's why im trying to use async. if it can be done both of them together( thread + async) i think it would be even more better. let me know if im wrong i tried async but got this error RuntimeWarning: coroutine 'startfunc' was never awaited and also showing some errors because of csrf so i added csrf_exempt but still doesnt work import func # (its a file in the directory of the django app) global func_running # this is the function import func # (its a file in the directory of the django app) global func_running def startFunc(): while func_running: # run a piece of code time.sleep(1) @csrf_exempt @sync_to_async def restview(request): try: raw_data = request.body.decode('utf-8').strip('"') data = json.loads(raw_data) if … -
Django is not sending the response with status code 302
Why is Django not sending the response to status code 302? I see two different codes, 302 and 200. With response ok and redirected: true instead of 302. I am trying to do a hard redirect to the home page with 302 code. @csrf_protect def new_form(request): if not request.user.is_authenticated: response = HttpResponse(status=302) response['Location'] = 'http://192.168.1.200:9000/' return response -
How to use Tiptap to achieve multi person collaborative editing?
I used Vue 3 as the front-end and Django as the back-end to develop the Tiptap editor. Now I want to create a collaborative editing feature for multiple users. I have already registered different users and created multiple files for one user (each file has its own ID, and the file content is stored in the back-end). Now, how can I make a document editable by multiple users at the same time? Is there any faster development solution. -
ImportError: cannot import name 'PlaceholderRelationField' from 'cms.models.fields'
I created new Django CMS project and tried to install also plugin Djangocms-blog after installation server is not running with this error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\djangocms_alias\models.py", line 6, in <module> from cms.models.fields import PlaceholderRelationField ImportError: cannot import name 'PlaceholderRelationField' from 'cms.models.fields' (C:\Users\ASUS\PycharmProjects\newvis\venv\lib\site-packages\cms\models\fields.py) I tried different version of django-cms and djangocms-blog but still getting this error. How I can solve … -
How to deploy django application only offline (client's computer)?
I have created an application of sales management with python django, mysql with restAPI. Now I want to deploy this application to the client computer. My client want to get the application offline [without hosting on internet], only his personal computer. So What the best standard process of deploying the application on Windows 11. -
why i am not receiving the google gemini response in formated paragraphs in html page
I Am using a google gemini api in my django, everything is going fine, response generated my gemini in terminal is perfect with space between two paragraph and all, but when i am passing this response to html page, all the formatting is gone, there is no line of space between two paragraph, and i dont nkow why it is producing unnecessary stars ** in the response, please tell me how i fix it. this is the image of response generated in terminal. this is how it is looking in html page. I Am storing the response generated by gemini in database, and then fetching it on html page. Please help me and tell how i make it look more tidy in html, also tell me how i ignore those unnessary stars. this is what my models.py looks like -
Can't connect to Neo4j Desktop database using latest Neo4j version, new database, and django_neomodel (Authentication Error)
So it throws the exception: neo4j.exceptions.AuthError: {code: Neo.ClientError.Security.Unauthorized} {message: The client is unauthorized due to authentication failure.} But I went up a few levels in the exception and here: auth is set to "None" essentially. My global variables are as such: I'm guessing this is something wrong with my django_neomodel setup, but I have django_neomodel installed and added to my Django project's INSTALLED_APPS. Reason username/password is not neo4j is because neo4j:neo4j does not work (it's not possible to set password neo4j in the latest desktop app), neither does neo4j:ArrowGlue (the password I thought I set when creating the new database). So in the database tab of Neo4j Browser I played ":server user add" and added ArrowGlue:ArrowGlue as an admin level Role. -
Is there any way to know when I'm passed the last item while iterating through a dictionary in django template?
I'm trying to create a text representation of a JSONField that has some data structured as an array of dictionaries like this: [ { "key1":"value1", "key2":"value2" }, { "key3":"value3", "key4":"value4", "key5":"value5" } ] My goal is to represent this data in the Django template like this: ( key1=value1 & key2=value2 ) || ( key3=value3 & key4=value4 & key5=value5 ) Now I'd iterate through the array and see if I'm not hitting the last dictionary so I can add an || between the condition representation text since it's already an array list like: {% for dict in data %} // Do stuff with dict {% if data|last != dict %} || {% endif %} {% endfor %} However, since a dictionary doesn't have a last thing, I'm having a hard time to iterate through the "key,value" when I'm doing stuff with each dictionary object when I've got to append an "&" only if I'm not hitting the end of this dict items. {% for k,v in dict %} k=v // append "&" if this is not the last key being iterated? {% endfor %} Any suggestions/workarounds/ideas would be much appreciated :) -
Deploy multiple sites from a single repository
I have a repository which has three projects, a django rest api, a react dashboard, and a react frontend, this is a store website, that should be used by multiple users, where I want to update all websites (stores) once I make any changes to the repo, I use dockerfile for each project in this repo, and docker-compose file to deploy the project in the server. using environment variables to distinguish between sites, like styles colors, name, etc... my problem now is that the frontend in the built stage is not accessing the environment variables, and this is the problem exactly, that the frontend should be built with the variables, I want to use the container in multiple places. how to handle this I need just an overview solution to this. the must important thing is to make sure that updates goes to all stores websites, I just need to use this command: dokcer compose up --force-recreate -d is that possible ? -
Django Private or Public posts
For my django app I want to enable the user to select whether a post is public or private. This is my best attempt so far: views.py def home(request): recipes = models.Recipe.objects.filter(recipe_private, recipes) context = { 'recipes': recipes } def recipe_private(): for recipe in recipes: if recipe(is_private=True) and recipe.author == self.request.user: True else: False return render(request, "recipes/home.html", context) And here is my models.py: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) ##tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) id = models.CharField(max_length=100, default=uuid.uuid4, unique=True, primary_key=True, editable=False) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.title) The logic works in my head but not in practice, how would I improve this? I want it so only the author can see their own private posts, anyone who isnt the author shouldnt be able to see a post marked as private. -
Custom User admin issue
I am creating a custom User model and I cant get Users table in my admin models.py: class EmailUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('Email required') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class EmailUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = EmailUserManager() USERNAME_FIELD = 'email' groups = models.ManyToManyField(Group, related_name="customuser_set") user_permissions = models.ManyToManyField(Permission, related_name="customuser_set") settings.py: AUTH_USER_MODEL = 'jwt_auth.EmailUser' admin.py: from django.contrib import admin from django.contrib.auth import get_user_model User = get_user_model() admin.register(User) I already run migrations and I actually can create superuser and log in to my admin. I didnot find any solution on the internet. If anybody knows how to fix admin please help. -
Retrieve data from CKEditor using ajax to not cause the page to reload*
Here is my code first: forms code from product.html: ... {% comment %} Review Form Start`` {% endcomment %} <div class="container"> <section class="review-section col-12 mt-4"> {% comment %} Display All Reviews {% endcomment %} <h3 class="hide-review-heading">Reviews</h3> {% for review in reviews %} <div class="review"> <p><strong>{{ review.user.username }}</strong> - {{ review.rating }} stars</p> <p>{{ review.review | safe }}</p> </div> <hr> {% empty %} <p>No reviews yet. Be the first to write a review!</p> {% endfor %} <h3 class="hide-review-heading">Write a Review</h3> <strong class="" id="review-response"></strong> <form action="{% url 'home:ajax_add_review' p.pid %}" method="POST" class="hide-review-form" id="commentForm"> {% csrf_token %} <div class="form-group mt-3"> {{ review_form.review }} </div> <div class="form-group mt-3"> {{ review_form.rating.label_tag }}<br> {{ review_form.rating }} </div> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> </section> </div> {% comment %} Review Form End {% endcomment %} {% endblock body %} review.js: console.log("review.js loaded"); $("#commentForm").submit(function(e) { e.preventDefault(); $.ajax({ data: $(this).serialize(), method: $(this).attr("method"), url: $(this).attr("action"), dataType: "json", success: function(response) { console.log("Comment saved to DB") if (response.bool) { $("#review-response").html("Review saved successfully"); // Assign a class and remove text-danger class if there $("#review-response").addClass("text-success"); $("#review-response").removeClass("text-danger"); $(".hide-review-form").hide(); $(".hide-review-heading").hide(); } else { $("#review-response").html("Error saving review"); $("#review-response").addClass("text-danger"); $("#review-response").removeClass("text-success"); } } }); }); urls.py: from django.urls import path from . import views app_name = "home" urlpatterns = … -
Static files not served in Django production [duplicate]
My Django application working perfectly on my local machine but when I successfully deployed it to AWS EC2, I don't get any styling. I tried search for solution as many others faced this issue but non of the answers fixed my case. I tried a lot of stuff for two days but nothing seem to work with me. What am I missing or doing wrong? Appreciate your help! These are my folders: enter image description here This is my settings.py file: import dj_database_url import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Application definition INSTALLED_APPS = [ # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My Apps 'main_app.apps.MainAppConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # My Middleware 'main_app.middleware.LoginCheckMiddleWare', ] ROOT_URLCONF = 'student_management_system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['main_app/templates'], #My App Templates '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 = 'student_management_system.wsgi.application' ASGI_APPLICATION = 'student_management_system.asgi.application' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # STATIC_ROOT = os.path.join(BASE_DIR, 'static') # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = … -
Unknown field(s) (post) specified for CategoryModel. Check fields/fieldsets/exclude attributes of class CategoryAdmin
I give this error and I don't have any idea about it. `@admin.register(models.CategoryModel) class CategoryAdmin(admin.ModelAdmin): fieldsets = [ ( 'Main', { 'classes' : ('wide',), 'fields' : ['title', 'slug', 'post', 'image', 'description', 'sub_category', 'is_sub_category', 'created_at', 'updated_at'] }, ), ] list_display = ['title', 'is_sub_category', 'sub_category', 'created_at',] list_filter = ['created_at', 'updated_at', 'sub_category',] readonly_fields = ['created_at', 'updated_at',] search_fields = ['title', 'created_at',] prepopulated_fields = { 'slug' : ('title',) } raw_id_fields = ['sub_category',] def get_form(self, request: Any, obj: Any | None = ..., change: bool = ..., **kwargs: Any) -> Any: help_text_fields = 'It initializes automatically' help_texts = { 'created_at' : help_text_fields, 'updated_at' : help_text_fields, } kwargs.update({ 'help_texts':help_texts }) return super().get_form(self, obj=obj, change=change, **kwargs)` -
Integrating Holoviz Panel and Django to build Dashboard Webapps
I am looking for any working example of a Django project that is integrated with Panel Apps. There is a section in the user guide that gives tips on how to integrate. But I am unable to get it to work. Could you please share any available resources online that demonstrates the integration. The code I tried is this (and its variants) The actual business logic is not important here. I want to integrate the Panel Dashboards and Django successfully. # project structure: # myproject/ # manage.py # myproject/ # __init__.py # settings.py # urls.py # wsgi.py # app1/ # __init__.py # apps.py # views.py # app2/ # __init__.py # apps.py # views.py # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2', 'panel', ] # myproject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] # app1/apps.py from django.apps import AppConfig class App1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app1' # app1/views.py import panel as pn from django.http import HttpResponse def app1_panel(request): # Create a simple Panel app slider = pn.widgets.FloatSlider(start=0, end=10, name='Slider') text = pn.widgets.StaticText(name='Slider Value') @pn.depends(slider.param.value) def update_text(value): text.value = f"Slider value: {value:.2f}" app = … -
My Django website is unable to know if visitor is logged in or not
I am trying to deploy a website which does something depending on if the user is login or not. I tested it on local host and it worked but now that I try to deploy on pythonanywhere it seems to to recognize user though I logged in again. I used the "user.is_authenticated method" in my html template -
Downloading Images from S3 bucket in Django
Trying to download images with a download button but when i click it goes to the s3bucket link instead of downloading the image. The link it redirects to is https://bucketname.s3.amazonaws.com/images/filename.jpeg. I want the download button to download the image to the users device when this is clicked instead of redirecting. Heres my main gallery view which uses the search prompt to find the filenames + keywords in my db and then retrieves the matching images from the bucket. def gallery(request): query = request.GET.get('q', 'free wallpapers') s3_image_urls = [] top_search_terms = [] keywords = query.split() conditions = [] query_params = [] for keyword in keywords: conditions.append("description LIKE %s") query_params.append('%' + keyword + '%') sql_query = "SELECT image_key FROM images_table WHERE " + " AND ".join(conditions) with connection.cursor() as cursor: cursor.execute(sql_query, query_params) results = cursor.fetchall() s3_bucket_url = 'https://{}.s3.amazonaws.com/images/'.format(settings.AWS_STORAGE_BUCKET_NAME) # Generate image URLs for result in results: for image_key in result: image_url = s3_bucket_url + image_key s3_image_urls.append(image_url) # Log the search term into the search_logs table with connection.cursor() as cursor: cursor.execute("SELECT search_count FROM search_logs WHERE search_term = %s", [query]) row = cursor.fetchone() if row: new_count = row[0] + 1 cursor.execute("UPDATE search_logs SET search_count = %s WHERE search_term = %s", [new_count, query]) else: # …