Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect to normal django view after logging in using DRF api
I get this in my console whenever i log in, it logs in successfully, api returns 200 but then when it tries redirecting to the dashboard view, it returns 302 and redirects to the login page [09/Aug/2024 18:17:04] "GET /static/js/login.js HTTP/1.1" 200 2297 [09/Aug/2024 18:17:24] "POST /api/v1/token/login HTTP/1.1" 200 70 [09/Aug/2024 18:17:25] "GET /dashboard/ HTTP/1.1" 302 0 [09/Aug/2024 18:17:25] "GET /accounts/login/?next=/dashboard/ HTTP/1.1" 200 1451 [09/Aug/2024 18:17:25] "GET /static/js/login.js HTTP/1.1" 304 0 [09/Aug/2024 18:18:46] "GET /accounts/login/?next=/dashboard/ HTTP/1.1" 200 1451 below is my login api which authenticates the user trying to log in import json from rest_framework.decorators import api_view,permission_classes from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework import status from core.models import Order, Laundry from .serializers import OrderSerializer, SignUpSerializer from django.views.decorators.csrf import ensure_csrf_cookie,csrf_exempt, csrf_protect from rest_framework.authtoken.models import Token from django.contrib.auth import authenticate,logout, login,get_user_model @api_view(['POST']) @permission_classes([AllowAny]) @ensure_csrf_cookie def user_login_token(request): """user login api""" if request.method == 'POST': email = request.data.get('Email') password = request.data.get('Password') current_user = authenticate(request, username=email, password=password) if current_user: login(request, current_user) token, created = Token.objects.get_or_create(user=current_user) response = Response({'token': token.key, 'SuperRole': current_user.is_superuser}, status=status.HTTP_200_OK) return response return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) this is my code listening for when the user submits the form (clicks the login button) const loginForm = document.querySelector('form'); loginForm.addEventListener('submit', … -
How i learn django framework and which topic is important in django?
I'm completely beginner. I have little bit knowledge of django. Like how to create form and how to save into n database.and login and sigin I'm completely beginner. I have little bit knowledge of django. Like how to create form and how to save into n database. -
Which backend framework should we use for faster performance on very large database (e.g. Hospital Data)?
I am confused on which backend framework should we use for faster performance and response of APIs when we have a very large database. I have been using Django with MongoDB, but I could just say the API responses are very late. When I try to filter something it may take around 6-7 seconds for the response to come. -
in cmd when i create virtual env it gives no error but where i created there is no directory or folder of virtualenv
in conamd promp i see this but no folder of virtual env and from my all older projects virtualenv directory is vanished mkvirtualenv nameenv these are version outputs virtualenv --version gives this virtualenv 20.26.3 from C:\Users\aneesRiazChaudhary\AppData\Local\Programs\Python\Python312\Lib\site-packages\virtualenv_init_.py Python version 3.12.5 django-admin --version 5.0.7 -
Saving self generated image in django models.ImageField
I have a method generate_certificate(), that uses a base image from default storage in django and edits it through pillow library and saves that image to the default djnago storage and returns file path. def generate_certificate(name, certification): base_image_path = os.path.join(settings.MEDIA_ROOT, 'certificates', 'Certificate.png') font_path = os.path.join(settings.MEDIA_ROOT, 'fonts', 'font.ttf') if not os.path.exists(base_image_path): raise FileNotFoundError(f"Base certificate image not found at {base_image_path}") img = Image.open(base_image_path) d = ImageDraw.Draw(img) location = (143, 155) text_color = (100, 100, 100) font = ImageFont.truetype(font_path, 40) d.text(location, name, fill=text_color, font=font) location = (360, 215) font = ImageFont.truetype(font_path, 18) d.text(location, certification, fill=text_color, font=font) location = (200, 310) font = ImageFont.truetype(font_path, 15) d.text(location, '2024-08-07', fill=text_color, font=font) file_name = f"{name.split(' ')[0]}_{random.randint(0, 255)}.png" file_stream = BytesIO() img.save(file_stream, format='PNG') file_stream.seek(0) # Save the file to the media directory and return the relative path file_path = default_storage.save(f'certificates/{file_name}', ContentFile(file_stream.read())) return file_path # Return the relative path I am using this method in a post method view that creates a record for UserCertification model. The request payload has the all the data except the image which is generated in the view. as below: def post(self, request): try: user = request.data.get('user') certification = request.data.get('certification') score = request.data.get('score') certificate_url = generate_certificate(user, certification) print(f"Generated certificate file path: {certificate_url}") # Debugging … -
When hosting my page, websockets not workign
I'm working on a game that consists of a musical bingo. The frontend is built in ReactJS and is hosted on Vercel using the Free tier. The backend is a Django app hosted on a Render web service. I've successfully made them communicate with each other using the correct URLs provided by these hosting services. However, I need help with WEBSOCKETS, as the wss URLs don't seem to be working. The game works like this: on the home page, the musicals are drawn using a simple "Play" button and it calls the api and returns one of the 14 musical options, and the users generate a bingo card by entering their name and getting a unique combination of 4 musicals. As musicals are drawn on the main screen, I used websockets to update the bingo cards so that the squares are marked accordingly. However, now that I've hosted everything, it's not working. Thanks for reading! I´ve tried using render redis database service but i dont know how to configure it to work with this one. Idk what else can i do as this is my first time working with these -
Django how to sort by fields that don't exist
Currently, I have two models posts.models from django.db import models from django_prometheus.models import ExportModelOperationsMixin from users.models import User from category.models import Category # Create your models here. class Post(ExportModelOperationsMixin('post'), models.Model): header_image = models.ImageField(default='ancean-no-header-image.png') title = models.CharField(max_length=100) introduce = models.TextField(default='') content = models.JSONField('json', null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_column="author", related_name='author') category = models.ForeignKey(Category, on_delete=models.SET_NULL, db_column="category", related_name='category', null=True, blank=True) wave = models.IntegerField(default=0) # wave field like 'like post' on general SNS created_at = models.DateTimeField(null=True) updated_at = models.DateTimeField(auto_now=True) is_finish = models.BooleanField(default=False) is_public = models.BooleanField(default=False) def __str__(self): return f'{self.title} - {self.author}' category.models from django.db import models class Category(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return f'{self.name}' I want to create a logic that gets the number of posts per category and sorts them in descending order. "http://localhost:8000/api/category?ordering=-post_count" Through the url as above I want to make it like the result of this query. SELECT c.name, count(*) AS post_count FROM category_category c JOIN posts_post p ON (c.id = p.category) GROUP BY p.category ORDER BY count(*) DESC I want to use Django ordering, but post_count is a non-existent field(Category model), so I can't use it. I'd appreciate it if you could tell me a good way. category.views class CategoryView(GenericAPIView, ListModelMixin): queryset = Category.objects.all() serializer_class = … -
Unable to install django in virtualenv
Unable to load django in virtualenv. "pip install django" is running indefinitely In VScode (just in case it matters) I create a virtual environment and try to install django, here is the sequence of actions: virtualenv myenv myenv\Scripts\activate pip install django Last operation not completed however long I wait (screenshot) enter image description here Without a virtual environment everything is installed perfectly. -
As I am trying to use REST API to PUT method and I get 500 Internal server error? [closed]
As I am trying to build a get, post, delete, and put methods in REST API Developed with Django. The Django is connected with Angular with help of Djongo(For the need of MongoDB). Everything work fine except the put method when I use put method I get "Internal Server error 500" And here's my code Angular component: @Component({ selector: 'app-edit', standalone: true, imports: [SharedModule, CommonModule, HttpClientModule], templateUrl: './edit.component.html', styleUrl: './edit.component.scss' }) export class EditComponent { name : string = '' mobilenumber : string = '' emailid : string = '' id : string = '' constructor(private http : HttpClient){} edit() { const temp = { id: this.id, name: this.name, mobilenumber: this.mobilenumber, email: this.emailid }; const url = `http://127.0.0.1:8000/call/${this.id}`; this.http.put(url, temp).subscribe( response => console.log("Edited", response), error => console.error("Error", error) ); } } When I go to the url : http://127.0.0.1:8000/call I get "Allow: GET, POST, HEAD, OPTIONS" is the put method even allowed. If allowed how do I resolve it? Please help me with my code -
Adding new row to the Django template table
I have a simple table generated from Django template variable: {% for object in object_list %} <tr> <td class="c9">{{object.first_name}}</td> <td class="c9">{{object.last_name}}</td> <td class="c9">{{object.tel}}</td> </tr> {% endfor %} I'm making insert to this model and the server side is done, but how to add a new row in top of this table? With this method: var row = table.insertRow(0)? or can I change this variable 'object_list' and row will be added automatically? This simple solution 'var row = table.insertRow(0);' is not adding columns with CSS classes. -
Django project use "python manage.py migrate" show stderr
environment Python 3.11.7 package:asgiref==3.8.1Django==5.1psycopg2==2.9.9sqlparse==0.5.1tzdata==2024.1 this is my models.py code from django.db import models class User(models.Model): user = models.CharField(blank=False) password = models.CharField(max_length=64) group_id = models.SmallIntegerField() email = models.EmailField(unique=True, null=True) create_time = models. DateTimeField(auto_now_add=True) class working_hours(models.Model): working_choices = { 'morning': "Options1", 'noon': 'Options2', 'eveing': 'Options3', 'befor dawn':'Options4', } ordinary = models.BooleanField(default=True) time_start = models.TimeField() time_end = models.TimeField() working = models.CharField(blank=False, choices= working_choices) the command execute python .\manage.py makemigrations polls no problem but then use python manage.py migrate File "D:\public_cloud_site\mysite\manage.py", line 22, in <module> main() File "D:\public_cloud_site\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_line utility.execute() File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\base.py", line 459, in executeoutput = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\base.py", line 107, in wrapperres = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 118, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\executor.py", line 18, in initself.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\loader.py", line 58, in initself.build_graph() File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\recorder.py", line 90, in applied_migrations return { ^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\models\query.py", line 400, in iterself._fetch_all() File "D:\public_cloud_site\venv\Lib\site-packages\django\db\models\query.py", line 1928, in _fetch_allself._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\models\query.py", line 91, in iter results = compiler.execute_sql( … -
How to perform left join and select a flag if fields exist on right table in django
I have article and bookmark tables and i want to fetch articles while getting is_bookmarked flag if the user has bookmarked the article. Article table has all the meta data related to the article and the bookmark table has user and article columns to maintain which user has bookmarked which article i.e Consider Bookmark table with columns article_id and user_id and a combined unique constraint of these. SELECT a.id AS article_id, a.title, (b.article_id IS NOT NULL) AS is_bookmarked FROM article_article a LEFT OUTER JOIN article_bookmark b ON a.id = b.article_id AND b.user_id = 1 Now i want to replicate this sql query to an django orm query, i don't want to use CASE or exists, and i'm unable to replicate this query just because of the is_bookmarked flag. I've tried FilteredRelations but couldn't get the query replicated. -
convert PMG file to PNG in python django
how to convert pmg files to png file format in python django -
Remove this box from the Django Signup form
In the tutorials I've followed, I didn't see this, so I assume it's because I recently updated django to 5.1. Now, there's this new box on the django signup view. It reads: Password-based authentication: Whether the user will be able to authenticate using a password or not. If disabled, they may still be able to authenticate using other backends, such as Single Sign-On or LDAP. Enabled Disabled I'd like to get rid of it as it makes the user creation process confusing for them. I'm not sure how to though. I'm currently just using css to hide it by selecting it - but I'm sure there's a better way. I'm already using a custom signup form which does NOT have this in it: class CustomSignupForm(UserCreationForm): email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('email', 'password1', 'password2') -
Pattern for periodically fetching data from an external system
Assume I have a Django application with the following features: there's a Project model which has a created_at field the application supports a plugin system where a developer can create custom API endpoint and install them onto the application, exposing them publicly. The endpoints can run arbitrary code, but cannot schedule long running tasks (e.g. Celery tasks) My goal is to create a third party analytics service for this application. In order to do that, the analytics service needs to poll the application for new data periodically. Specifically, the analytics application needs to fetch any new projects. The first step is to create a plugin that will act as an "adapter", which exposes an API endpoint that presents the projects in a format that is useful to the analytics service. We have full control over this endpoint, which parameters it accepts, etc. Assume it answers using pagination. Now the question is: assuming the analytics service will perform one request per hour to get the new projects, what should be the pattern to only ask for new projects? There are two techniques which I've thought of, both with their advantages and disadvantages. Use a query parameter since specifying the timestamp of … -
How to use Async Redis Client + Django in python?
I'm trying to create a distributed semaphore using Redis to use in my Django application. This is to limit concurrent requests to an API. I'm using asyncio in redis-py. However, I want to create a connection pool to share across requests since I was getting a "Max clients reached" error. Thus, I created a shared connection pool in settings.py which I use in my semaphore class. However, I then get an error got Future <Future pending> attached to a different loop when I make concurrent requests. This is my code: import os import uuid import asyncio import time from typing import Any import random from django.conf import settings from redis import asyncio as aioredis STARTING_BACKOFF_S = 4 MAX_BACKOFF_S = 16 class SemaphoreTimeoutError(Exception): """Exception raised when a semaphore acquisition times out.""" def __init__(self, message: str) -> None: super().__init__(message) class RedisSemaphore: def __init__( self, key: str, max_locks: int, timeout: int = 30, wait_timeout: int = 30, ) -> None: """ Initialize the RedisSemaphore. :param redis_url: URL of the Redis server. :param key: Redis key for the semaphore. :param max_locks: Maximum number of concurrent locks. :param timeout: How long until the lock should automatically be timed out in seconds. :param wait_timeout: How long … -
How do I properly authenticate with OAuth using google-auth-oauthlib and Django?
I am building a Django project that works with video and needs to upload to Youtube. For this, I need oauth credentials. I am unable to authenticate with Oauth even though my redirect URI is correct and I am parsing the request for the code and passing it to the flow. I am using google-auth-oauthlib and oauth to authenticate. Here is what the error looks like: Traceback (most recent call last): File "/home/team/lotteh/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py", line 89, in sentry_wrapped_callback return callback(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/users/views.py", line 47, in google_auth_callback email, token, refresh = parse_callback_url(request, code) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/users/oauth.py", line 66, in parse_callback_url flow.fetch_token(code=token_url) File "/home/team/lotteh/venv/lib/python3.12/site-packages/google_auth_oauthlib/flow.py", line 285, in fetch_token return self.oauth2session.fetch_token(self.client_config["token_uri"], **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/requests_oauthlib/oauth2_session.py", line 406, in fetch_token self._client.parse_request_body_response(r.text, scope=self.scope) File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 415, in parse_request_body_response self.token = parse_token_response(body, scope=scope) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 425, in parse_token_response validate_token_parameters(params) File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 432, in validate_token_parameters raise_from_error(params.get('error'), params) File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 405, in raise_from_error raise cls(**kwargs)oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Bad Request And the views: def google_auth(request): from django.shortcuts import redirect from … -
Cannot cast type bigint to UUID in Django migration when migrating from SQLite to PostgreSQL
I'm encountering an issue while migrating my Django project from SQLite to PostgreSQL. I had previously set the id field to UUID in SQLite, but now when applying the migration in PostgreSQL, I receive the following error: `django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...ompany_company" ALTER COLUMN "id" TYPE uuid USING "id"::uuid ^ my models class Company(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) class Job(models.Model): BEGINNER = 'Beginner' MID = 'Mid' EXPERT = 'Expert' LEVEL_CHOICES = [ (BEGINNER, 'Beginner'), (MID, 'Mid'), (EXPERT, 'Expert'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) ` I initially developed my Django project using SQLite and set the id field of the Company model to UUID. Now that I am migrating the database to PostgreSQL, I need to update the id field to UUID in the PostgreSQL schema. Details: 1.Current Migration Code: # Generated by Django 4.2.7 on 2024-04-26 22:25 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('company', '0002_initial'), ] operations = [ migrations.AlterField( model_name='company', name='id', field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False), ), ] 2.Migration Error Message: psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid LINE 1: ...ompany_company" ALTER COLUMN "id" TYPE uuid USING "id"::uuid ^ I … -
what is Password-based authentication in django
I made a form that inherits from the UserCreationForm and use class based view that inherits CreateView and when I use runserver and display the form, there is a section at the bottom Password-based authentication that I don't notice forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class RegisterForm(UserCreationForm): """Form to Create new User""" class Meta: model = get_user_model() fields = ["username", "password1", "password2"] views.py class SignUp(CreateView): form_class = RegisterForm template_name = "register.html" success_url = reverse_lazy("core:Login") def form_valid(self, form): user = form.save() if user: login(self.request, user) return super().form_valid(form) register.html <h1>signup</h1> {{form}} And when I ran the code I saw this output output image so i didn't expect password-based authentication. My question about What exactly this is ? Should it be displayed here ? How do I hide it ? -
How can custom django error views be tested?
In the Django documentation they provide the following example for testing custom error views. Given the following example how would you go about testing custom server_error and csrf_failure views? I've tried to trigger my error view using a few different django.core.exceptions however the custom error view is never run. Returning an HTTPResponse gives the error AssertionError: No templates used to render the response which makes sense. However when I try to raise an error that should trigger a server error like raise ImproperlyConfigured, the error is just raised in the test. Testing for CSRF failure is another story as I feel I'm not even close. # views.py from django.views import defaults from django.views.csrf import csrf_failure as csrf_failure_default def server_error(request): template_name = 'wholesale/500.html' return defaults.server_error( request, template_name=template_name, ) def csrf_failure(request, reason=''): template_name = 'wholesale/403_csrf.html' return csrf_failure_default( request, reason=reason, template_name=template_name, ) # tests.py from django.test import TestCase, override_settings from . import views def page_not_found_view(request): raise Http404 def server_error_view(request): # raise ImproperlyConfigured return HttpResponseServerError() def bad_request_view(request): raise BadRequest def permission_denied_view(request): raise PermissionDenied def csrf_failure_view(request): return HttpResponse(status=HTTPStatus.FORBIDDEN) urlpatterns = [ path('404/', page_not_found_view), path('500/', server_error_view), path('400/', bad_request_view), path('403/', permission_denied_view), path('403_csrf/', csrf_failure_view), ] handler404 = views.page_not_found handler500 = views.server_error handler400 = views.bad_request handler403 = views.permission_denied @override_settings(ROOT_URLCONF=__name__) … -
django-filters filter by Booleans or None with IN lookup expr
I'm trying to create a filter for DRF viewset that will filter my model field: is_claim_submitted = models.BooleanField( IS_CLAIM_SUBMITTED_NAME, blank=True, null=True ) I've written a filter according to django-filter docs class BoolInFilter(BaseInFilter, BooleanFilter): pass class DefectFilter(django_filters.FilterSet): is_claim_submitted__in = BoolInFilter( field_name="is_claim_submitted", lookup_expr="in", ) class Meta: model = Defect fields = { "id", "is_claim_submitted", } So I'm trying to filter a queryset by sending request http://localhost:8000/api/v1/defects/is_claim_submitted__in=true,false. Basicly, the values of URI param must be in a list of [True, False, None]. How ever it doesn't filter and it doesn't parse the values to python bools (true -> True). For some reason it doesn't get field_class = forms.NullBooleanField from BooleanFilter, but uses default Field parsing. I've already checked the MRO, though I still can't manage to figure out why my code doesn't work. The problem is precisely with BooleanFilter, as all the same but with NumberFilter and ids works fine. Is there a mistake in my code or is there a better way to implement such a filter? -
My django application is not rendering instead it is just showing the csrf middleware token id in the address bar
This is the views.py file section, class filterTask(View): def get(self, request): return render(request, 'filter-task.html'); def output(request): form = Taskform if request.method == 'GET': form = Taskform(request.GET.get('priorityChoice')) ans = Task.objects.filter(priority = form).values() return redirect(request, 'output.html',context={'ans':ans}) This is the filter-task.html file {% include 'base.html' %} `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <a href="{% url 'index' %}">Go To Homepage</a> <body> <h3>Filter Task by Priority</h3> <form method="get" autocomplete="off"> {% csrf_token %} <label id="priorityChoice">Enter the priority </label>: <select id="priorityChoice" name="priorityChoice" required> <option value="low">low</option> <option value="mid">mid</option> <option value="high">high</option><br> </select><br><br> <input type="submit" value="Submit"/> </form> </body> </html>` I am trying to filter a specific attribute of an object from the html file by getting the answer from a dropdown option, Kindly help me. I am trying to filter a specific attribute of an object from the html file by getting the answer from a dropdown option, Kindly help me. -
How to retrieve the URL of the uploaded image instead of the ID?
I have a Django RESTful application and a user can upload images from the Admin panel of Django. But the problem I am facing is that, in the corresponding API call, the IDs of the images are displayed instead of the URLs of the images. See the API call below (imag is the property): { "id": 30, "name": "Dier", "sort": "hghkjhkh", "uis": false, "cites": "B", "pet_list": "nvt", "description": "Wat een lekker dier", "feeding": "", "housing": "", "care": "", "literature": "", "images": "https://dier.blob.core.windows.net/media/media/photos/animals/amphibiance_X04Eh6N_1z0N4Gs_9EPmeMA_6j3axdY_da4cpTO_2VAY67x_hcUVB7f_bv9qvuY.jpg", "category": 11, "category_name": "mammal", "klasse_name": "mammal", "hdd_list_remark": "Wat een mooi dier", "bird_directive_list": "Bijlage|", "Habitat_directive_list": "Bijlage |V", "imag": [ 5, 6 ], }, So the corresponding code: model.py: import sys from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.contrib.auth.models import Permission from PIL import Image from django.db import models from django.conf import settings class AnimalImage(models.Model): animal = models.ForeignKey( 'Animal', related_name='imag', on_delete=models.CASCADE) image = models.ImageField(upload_to='media/photos/animals') def __str__(self): return f"Image for {self.animal.name}" class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") animal_images = models.ManyToManyField( AnimalImage, related_name='related_animals', blank=True) def img_preview(self): # new return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') img_preview.short_description = "Huidige Foto" def img_previews(self): images = self.images.all() return mark_safe(''.join([f'<img src="{img.image.url}" width="100"/>' for img in images])) img_previews.short_description = "Thumbnails" class … -
Problems with building dockerfile on GitHub Actions
I'm currently really freaking out about GitHub Actions. I have restructured my Django project on GitHub. Before my dockerfile worked like that: # Base image ARG arch=amd64 FROM --platform=linux/${arch} python:3 # Set work directory WORKDIR /appname # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Set default environment variables ENV DJANGO_SETTINGS_MODULE=appname.settings ENV DEBUG=False # Copy entrypoint script COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh # Command to run on container start ENTRYPOINT ["/entrypoint.sh"] where "appname" was the main repository of my django app where also the dockerfile layed in. I've restructured the app to make it way cleaner. Now my project looks like this (from root directory/github repo): .git/ .github/ apps/ appname/ config/ templates/ .gitignore manage.py requirements.txt README.md The dockerfile and entrypoint.sh are now in config/docker/.. So I've changed my dockerfile: # Base image ARG arch=amd64 FROM --platform=linux/${arch} python:3 WORKDIR /config # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE=appname.settings ENV DEBUG=False # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt --no-cache-dir # Copy things COPY . . # Entrypoint script RUN chmod +x entrypoint.sh # Command to … -
AWS Application Load Balancer sticky session fails after targets change
I have a CloudFront distribution pointing to an Application Load Balancer, which is load balancing to ECS containers running a Django app. The ALB target group has stick sessions enabled using Application-based cookie, set to Django's sessionid cookie which is Django's main "logged-in" user indicator. All works well after the user logs in; Django sets the sessionid cookie and the ALB sets AWSALBAPP-0 cookie to a different value for each response, and the session stays sticky to a single ECS container. The problem is when I redeploy the app, and the containers stop. When the ALB directs traffic to new targets, I see the AWSALBAPP-0 cookie get set to _remove_. Always after this, the cookie value stays as _remove_ and the session is no longer sticky - it round-robin load balances. I have to log out and log back in to reestablish stickiness. Why is this happening? AWS documentation says: If a target fails or becomes unhealthy, the load balancer stops routing requests to that target, and chooses a new healthy target based on the chosen load balancing algorithm. The load balancer treats the session as now being "stuck" to the new healthy target, and continues routing requests to the …