Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django combine 2 querysets without changing the original order
def get_queryset(self): normal_posts = Post.objects.filter(field1=‘value1’).order_by('another_field_1’) featured_posts = Post.objects.filter(field2=‘value2’).order_by(‘another_field_2') all_posts = (normal_posts | featured_posts) #does not preserve the order return all_posts I'm using DjangoFilterBackend and along with filterset_class for paginated query results. Hence not able to use below. normal_ads.union(featured_ads) #django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() is not supported. I tried using from itertools import chain also, however its not much helpful as its returning a list and not query set. Please suggest. -
AWS Route 53 Routing for Django Application - ALLOWED HOSTS
I am deploying a django application to AWS elastic beanstalk. I’m having troubles getting a Route 53 hosted domain record to route traffic appropriately, and I think it’s a problem on the application side and not AWS. I have a ticket open with AWS, and in their first response their thinking was that it was probably application problem, but they are still investigating. Was hoping someone here could help me on the Django side. I have a hosted zone, “example.com” in Route 53. Within the hosted zone I have 4 records, 2 are the NS and SOA records that come with each hosted zone by default. And I created 2 additional “A” records, that are alias’ to my elastic beanstalk environment. These two records are named “example.com” and “www.example.com”. In my django application I have added my elastic beanstalk CNAME, “example.com”, and “www.example.com” to the ALLOWED_HOSTS, as follows: '''ALLOWED_HOSTS = [‘env-example.eba-emvtkupp.us-west-1.elasticbeanstalk.com’, ‘example.com’, ‘www.example.com’, ‘https://example.com’, ‘https://www.example.com’,]''' Note - i added the https versions of the urls as well…im not sure if this is actually necessary. When i deploy the application to elastic beanstalk everything is normal. I try to access example.com in a browser and it works. I try to access … -
Django - How to filter out row that are same in some fields and differ in others?
i have a model in django like this class Article(models.Model): column_one = ForeignKey() column_two = ForeignKey() column_three = ForeignKey(null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["column_one", "column_two"], condition=Q(column_three=None), name='article_unique_if_no_column_three'), models.UniqueConstraint( fields=["column_one", "column_two", "column_three"], condition=~Q(column_three=None), name='article_unique_if_column_three'), ] How can i filter so that i get all the articles but if there are two that have the same data except the column_three it chose the one with column_three not null and exclude the one with column_three=None thanks in advance -
Running crond as root user when server is going to be running as non-root django container
I'm currently dockerizing my app and am trying to get cron jobs working. For context I am creating my job using the python-crontab module. I would like to run the container as a non-root user (as I believe is best practice) however I am struggling to get the cron task to run. This is the relevant part of my current dockerfile: ######### # FINAL # ######### #Pull base image FROM python:3.9.15-alpine3.16 #Create directory for app user RUN mkdir -p /home/user #create app user RUN addgroup -S app && adduser -S useradmin -G app #create directories ENV HOME=/home/user ENV APP_HOME=/home/user/userapp RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/media WORKDIR $APP_HOME #install dependencies RUN apk update && apk add libpq COPY --from=builder /user/wheels /wheels RUN pip install --no-cache /wheels/* # copy entrypoint.sh COPY entrypoint.sh $APP_HOME # copy project COPY . $APP_HOME RUN python /$APP_HOME/user/cron.py RUN crontab -l > /home/user/crontab.txt RUN crond -f -L /dev/stdout # chown all the files to the app user RUN chown -R user:app $APP_HOME # change to app user USER useradmin # run entrypoint.sh ENTRYPOINT ["/home/user/userapp/entrypoint.sh"] The line RUN crond -f -L /dev/stdout is the only way so far I have found to get the cron jobs … -
How do migration operations (eg. AddField) detect if you're applying or reverting a migration?
A good example is django.db.migrations.AddField. Let's say I've created a simple migration such as: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.AddField( model_name="foo", name="bar", field=models.TextField(blank=True, null=True), ), ] Running the migration would result in the bar field being added, and reverting to a previous migration would result in the bar field being removed. However when I look under the hood of the AddField class, I don't see the logic for detecting the direction of the applied migration. class AddField(FieldOperation): field: Field[Any, Any] = ... preserve_default: bool = ... def __init__( self, model_name: str, name: str, field: Field[Any, Any], preserve_default: bool = ..., ) -> None: ... I need to create a similar function for collected data that can apply/revert changes based on changes made to the model the data is based on. This function would be used inside migrations in a similar way to AddField, and needs to detect whether the user is applying or reverting a migration. -
Why do I get a different schema when I run generateschema on the command line compared to obtaining it via the api using Django SchemaGenerator?
I am using the Django Rest Framework SchemaGenerator to create a schema for my API. However, I get different results depending on whether I generate a static schema using python manage.py generateschema compared to when I request a dynamic schema through the API endpoint configured as urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), re_path(r'^auth/', include('api.djoser.urls')), re_path(r'^auth/', include('djoser.urls.authtoken')), path('schema/', get_schema_view( title="Morty", description="API to access Morty", version="1.0.0" ), name='morty-schema'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Using the static method I get a complete schema with all the API endpoints. The schema returned from the endpoint in the dynamic method has a number of endpoints missing. The set of endpoints given in the dynamic schema is /auth/users/activation/ /auth/users/resend_activation/ /auth/users/reset_password/ /auth/users/reset_username/ /auth/users/reset_username_confirm/ /auth/token/login/ which is missing the following endpoints that are present in the full static schema /auth/users/ /auth/users/me/ /auth/users/{id}/ /auth/users/reset_password_confirm/ /auth/users/reset_username_confirm/ /auth/users/set_password/ /auth/users/set_username/ /auth/token/logout/ I am using Djoser to get the endpoints and associated views. I thought, perhaps, that the dynamic schema was affected by authorization, but I tried logging in using the /login/ endpoint prior to requesting the schema and got the same results. I feel like I must be missing something obvious. -
Django - not displaying the images (as urls)
I'm following a ytb video, step by step and everything works fine except for the images. I uploaded the link adresses through django admin, but they are not displaying. models.py: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer (models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() index.html: {% extends 'base.html' %} {% block content%} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image_url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }} RON</p> <a href="#" class="btn btn-primary">Adauga in cosul tau</a> </div> </div> </div> {% endfor %} </div> {% endblock %} views.py: from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('Produse noi') The code is the same as in the video. I tried to ask chat gpt if there's something that doesn't seem right but he didn't find anything. I tried to change the name from "image_url" to anything else but didn't work, as expected. -
Where to set a custom middleware's path in "MIDDLEWARE" in "settings.py" in Django?
I created the middleware simple_middleware() in middleware/sample.py following the doc as shown below. *I'm learning Middleware: django-project |-core | └-settings.py |-middleware | |-__init__.py | └-sample.py # Here |-app1 └-app2 # "middleware/sample.py def simple_middleware(get_response): print("Only once the server starts") def middleware(request): print("Before a view is called") response = get_response(request) print("After a view is called") return response return middleware But, I don't know where to set the custom middleware's path in MIDDLEWARE in settings.py as shown below. The 1st, the last or anywhere in MIDDLEWARE?: # "core/settings.py" MIDDLEWARE = [ # "middleware.sample.simple_middleware" # The 1st? "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", # "middleware.sample.simple_middleware" # Anywhere? "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", # "middleware.sample.simple_middleware" # The last? ] Actually, I know that the doc says below in Activating middleware but I want to know exactly where to set it: The order in MIDDLEWARE matters because a middleware can depend on other middleware. So, where should I set the custom middleware's path in MIDDLEWARE in settings.py? -
how to specify response for specific request methods for API action in django
I have an API action in django which accepts GET and POST requests where each of them will have a distinct response schema. If a request is of method "GET" we will return a list, if it is "POST" we will return only the created entity... from drf_spectacular.utils import extend_schema class SessionsViewSet(viewsets.ModelViewSet): ... @extend_schema( parameters=[query_params["extra_query_param"]], responses={ "GET": serializers.ExampleSerializer(many=True), "POST": serializers.ExampleSerializer(many=False), }, ) @action( detail=True, url_path="example", methods=["GET", "POST"], filter_backends=[], ) def example(self, request, pk, *args, **kwargs): match request.method: case "GET": queryset = MyModel.objects.filter(session_pk_id=pk) page = self.paginate_queryset(queryset) serializer = get_serializer(page, many=True) return self.get_paginated_response(serializer.data) case "POST": serializer = get_serializer(data=request.data, many=False ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_201_CREATED, ) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) case _: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) The problem is that now I am not sure how to define this rule so that the swagger auto-schema will detect and present as such. How can I explicitly state that a response schema or serializer belongs to a specific request method? -
Failing to understand django get_absolute_url
I have this model: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=600) isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre) language = models.ForeignKey( 'Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_detail", kwargs={"pk": self.pk}) And this view: class BookDetail(DetailView): model = Book It will connect me to the template as well called (book_detail.html). My question is, do I need to also specify in the app's urls.py the url path in this case? path('book/<int:pk>/',views.BookDetail.as_view(),name='book_detail') I thought that if I used get_absolute_url(self) I wouldn't need to do that but I am finding some resources where it says it is necessary. I find it confusing since to me it feels like duplicating the code. Thanks! -
Updating status of one field based on multiple conditions from other fields
I have a class 'Contract' in which I want to set a status based on the fulfillment of certain conditions. The status is used for making lists and table of contracts based on their status. For now, I'm thinking the best solution is to split the code into two parts: Conditions that need to be met before updating an object, and conditions for automatic updates. The first example would be where the user would change the status of a contract from 'PLANNED' to an active contract. In order to do this, the field 'award_date' would have to be filled in before the other possible fields 'signature_date', and 'start_date'. Possible statuses can be 'AWARDED_UNACTIVE' ('signature_date' with a empty or future 'start_date), 'UNSIGNED_ACTIVE' ('start_date' without 'signature_date'). Another example would be that one can only set the status to 'TERMINATED' if the the contract has an active status (planned or expired contracts can not be terminated). The second example would be if a contract has been active ('start_date' is before today) and the date passes 'end_date'. In these cases I would like 'status' to change to 'EXPIRED' without needing a manual update. How would I go about to make this? I'm still a … -
Function-Based Middleware vs Class-Based Middleware in Django
I read the doc, then I could understand that we can define a function-based middleware and a class-based middleware in Django as shown below but I could not understand the difference between them. *I'm learning Middleware: Function-Based Middleware: def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): # Code to be executed for each request before # the view (and later middleware) are called. response = get_response(request) # Code to be executed for each request/response after # the view is called. return response return middleware Class-Based Middleware: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response My questions: What is the difference between a function-based middleware and a class-based middleware in Django? Which should I use basically? -
docker nginx django ALLOWED_HOSTS not allowing requests through
I am deploying an api that doesn't require database or gunicorn to be used. With following configurations I am setting up the api: nginx.conf upstream django { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } nginx Dockerfile # Base image for building the Django application FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d ALLOWED_HOSTS django settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] Dockerfile # Base image for building the Django application FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt COPY . /code/ EXPOSE 8000 EXPOSE 80 CMD python manage.py runserver 0.0.0.0:8000 --noreload docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile volumes: - .:/code nginx: build: ./nginx ports: - 80:80 depends_on: - web The purpose is to create an api which will only be called by other client like a Python based client. I am testing this from my local machine but not working. Adding * wildcard works but is too risky. So, what changes should I make for following two cases: 1. To be able to call from my local python client. 2. To be … -
Django - The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance
I have run into a problem that I cannot figure out. First, my code: models.py from django.db import models import random def pass_gen(): password = '' def rand_uni(): return random.randint(33, 126) def rand(): return random.randint(8, 20) code = rand() for num in range(code): r_int = chr(rand_uni()) password += r_int return password # Create your models here. class User(models.Model): username = models.CharField(max_length=200) class Password(models.Model): url = models.CharField(max_length=800) password = models.CharField(default=pass_gen(), max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['url', 'user'], name='unique_url_and_user_id') ] Serializers.py: from rest_framework import serializers from vault.models import User, Password class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class PasswordSerializer(serializers.ModelSerializer): url = serializers.CharField(max_length=800) class Meta: model = Password fields = ('url', 'password', "user") views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from vault.models import User, Password from django.views.decorators.csrf import csrf_exempt from vault.serializers import UserSerializer, PasswordSerializer # Create your views here. # GET list of all users @csrf_exempt def user_all(request): if request.method == 'GET': user = User.objects.all() serializer = UserSerializer(user, many=True) return JsonResponse(serializer.data, safe=False) elif request.method=='POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) #GET and DELETE unique users @csrf_exempt def user_detail(request, id): … -
Ansible URI module throws SSL error in spite of validate_certs set to false
I am trying to do a readiness check on a docker image deployed using Ansible. I am using Ansible module URI. In spite of validate_certs being set to false, I am receiving an SSL error when I try to get an html deployed on it. Verbose log: <my.ip.v4.address> (1, b'\r\n{"redirected": false, "url": "https://127.0.0.1/xxxx_xxxx/xxxx.html", "status": -1, "elapsed": 0, "changed": false, "failed": true, "msg": "Status code was -1 and not [200]: Request failed: <urlopen error EOF occurred in violation of protocol (_ssl.c:1131)>", "invocation": {"module_args": {"url": "https://127.0.0.1/xxxx_xxxx/xxxx.html", "validate_certs": false, "status_code": [200], "force": false, "http_agent": "ansible-httpget", "use_proxy": true, "force_basic_auth": false, "use_gssapi": false, "body_format": "raw", "method": "GET", "return_content": false, "follow_redirects": "safe", "timeout": 30, "headers": {}, "remote_src": false, "unredirected_headers": [], "unsafe_writes": false, "url_username": null, "url_password": null, "client_cert": null, "client_key": null, "dest": null, "body": null, "src": null, "creates": null, "removes": null, "unix_socket": null, "ca_path": null, "mode": null, "owner": null, "group": null, "seuser": null, "serole": null, "selevel": null, "setype": null, "attributes": null}}}\r\n', b'Shared connection to my.ip.v4.address closed.\r\n') <my.ip.v4.address> Failed to connect to the host via ssh: Shared connection to my.ip.v4.address closed. <my.ip.v4.address> ESTABLISH SSH CONNECTION FOR USER: ubuntu <my.ip.v4.address> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o 'IdentityFile="/home/jenkins/agent/workspace/XXXXXX/install/foo.pem"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o … -
Django user.is_superuser not returning true in template if statement
I'm trying to have information about an object show up if the user is a super user. Normally the information is hidden unless the object's public attribute is true. The object.public part works and {{user.is_superuser}} works as expected but {% if user.is_superuser %} does not. <h1>Player Techniques</h1> <h2>{{user.is_superuser}}</h2> {% for object in techniques %} {% if user.is_superuser or object.public%} {% include "unlimited/technique.html" %} {% endif %} {% endfor %} here are my settings TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], }, }, ] I have also tried request.user.is_superuser with the same results, correctly displaying True for superuser and False otherwise in the h2, but not passing the if. -
Running django app + psql in vscode debugger causing FATAL: sorry, too many clients already
I have django app with psql database that I run with docker on port 5432. When I run the app and celery worker using vscode debugger after a few requests I see this error psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: sorry, too many clients already Can't reproduce same error when I run app in standard way by typing python3 main.py in CLI. I used sudo lsof -i:5432 and discovered that if I run app in standard way, processes are being constantly cleaned, but if I run it using VScode debugger, processes are getting stacked and list if getting bigger until I get FATAL. Since I can only reproduce this error using VSCode debuger I assume it is related to that. Are there any settings to make debuger kill processes on the fly? -
django Image field is not loading current value on edit form and user have to upload again the file
I have a django form that have 3 image fields that are required. What I found is that when I use an instance to create an update form, the image is not loaded un the html input field, so when I send the form to the view to save it into database, I get an invalid form error due to images are missing. I defined the imageField as FileField: class Meta: model = Edicion exclude = ['festival'] widgets = { 'logo': FileInput, 'banner': FileInput, 'poster': FileInput, 'fecha_apertura_inscripciones': DateInput(), 'fecha_cierre_inscripciones': DateInput(), 'fecha_inicio': DateInput(), 'fecha_final': DateInput(), 'fecha_notificacion': DateInput(), } If I define again these fields then it works fine, but i'm not being able to send this field from the view. Many thanks Edit: Form Code: Form.py class createNewEdicion(forms.ModelForm): required_css_class = 'required-field' class Meta: model = Edicion exclude = ['festival'] widgets = { 'logo': FileInput, 'banner': FileInput, 'poster': FileInput, 'fecha_apertura_inscripciones': DateInput(), 'fecha_cierre_inscripciones': DateInput(), 'fecha_inicio': DateInput(), 'fecha_final': DateInput(), 'fecha_notificacion': DateInput(), } help_texts = { 'Nombre': ('Some useful help text.'), } error_messages = { 'Nombre': { 'max_length': ("This writer's name is too long."), }, } View.py if request.method == 'POST': form_festival = createNewFestival(request.POST, request.FILES) form_edicion = createNewEdicion(request.POST, request.FILES) # check whether it's valid: if … -
Unable to use `CheckboxSelectMultiple` for choices in wagtails `FieldPanel`: Form field validation raises an error
In a wagtail settings model I have a CharField-based choice field and want that to behave as a multi select in Wagtails FieldPanel. The choices are rendered correctly as multiple checkboxes, but on submit the form validation will raise an error: Select a valid choice. ['OPT1'] is not one of the available choices. So how do I use text-based choices as a multi select in Wagtails FieldPanel? Do I have to override the form field type to a forms.fields.MultipleChoiceField somehow? Setting the widget attribute to Select - instead of CheckboxSelectMultiple - the correctly rendered and populated select dropdown widget works as expected. My current implementation looks (roughly) like this: # models.py @register_setting(icon='cog') class MySettings(BaseGenericSetting): class MyChoices(models.TextChoices): OPT_1 = "OPT1" OPT_2 = "OPT2" choicefield = models.CharField( max_length=4, blank=True, choices=MyChoices.choices, ) panels = [ FieldPanel( 'choicefield', widget=forms.CheckboxSelectMultiple, ), ] I did not find any hints in the Customising generated forms docs. -
How to use django-admin-sortable2 and django-import-export package together in admin panel?
I want to use django-admin-sortable2 django-import-export package together in admin panel. Here is the code: class University(models.Model): name = models.CharField(max_length=50, help_text="University or Institution Name") short_name = models.CharField(blank=True, max_length=10, help_text="University or Institution Short Name") order = models.PositiveIntegerField( default=0, blank=False, null=False, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.id}-{self.name}' class Meta: ordering = ['order'] admin.py: from import_export import resources from import_export.admin import ImportExportModelAdmin from adminsortable2.admin import SortableAdminMixin # Register your models here. class UniversityResource(resources.ModelResource): class Meta: model = University exclude = ('created_at', 'updated_at',) class UniveresityAdmin(ImportExportModelAdmin, SortableAdminMixin, admin.ModelAdmin): resource_classes = [UniversityResource] admin.site.register(University, UniveresityAdmin) But this is not working, If I remove ImportExportModelAdmin then sortable works and if I remove SortableAdminMixin, import-export works. But I want to use both package together. Is there workaround to solve this issue? Thanks in advance. -
My Django project is not displaying some components, I've tried everything but it's not working [closed]
So I have this resume builder web app project, and it has an experiences section. In the experiences, I have main experience and additional experiences. Whereby in a form, a person enters their experience, and if they have additional experiences, they click the "additional experiences" button and add more experiences. However when I visit preview page, the additional experiences are not displaying, only the main experiences are displaying. models.py: class experience(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) position = models.CharField(max_length=200) company = models.CharField(max_length=200) startdate = models.DateField() enddate = models.DateField() roles = models.TextField(max_length=500) is_main_experience = models.BooleanField(default=False) views.py: # Create experiences @login_required def experience_v(request): if request.method == 'POST': position = request.POST['position'] company = request.POST['company'] startdate = request.POST['startdate'] enddate = request.POST['enddate'] roles = request.POST['roles'] main_experience = experience(user=request.user, company=company, position=position, startdate=startdate, enddate=enddate, roles=roles) main_experience.is_main_experience = True main_experience.save() return redirect('education') else: form = ExperienceForm() return render(request, 'experience.html', {'form': form}) # Create additional experiences def addexperience_v(request): if request.method == 'POST': additional_experience_positions = request.POST.get('additional_experience_position') for i in range(len(additional_experience_positions)): additional_experience_position = request.POST.get('additional_experience_position[' + str(i) + ']') additional_experience_company = request.POST.get('additional_experience_company[' + str(i) + ']') additional_experience_startdate = request.POST.get('additional_experience_startdate[' + str(i) + ']') additional_experience_enddate = request.POST.get('additional_experience_enddate[' + str(i) + ']') additional_experience_roles = request.POST.get('additional_experience_roles[' + str(i) + ']') additional_experience = experience.objects.create( user=request.user, position=additional_experience_position, … -
HTTPConnectionPool Max retries exceeded with url" Error in Python Selenium
I have a web application where users can perform searches on specific retailers and view the results in tables. When two users start searching on t:he same retailer at the same time, after a while, I receive an error message saying HTTPConnectionPool(host='localhost', port=57640): Max retries exceeded with url: /session/9b99c06c009ea88cba5295bd6fb3725a/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000021B3ED66310>: Failed to establish a new connection: [WinError 10061])) (Sometimes I also receive InvaliedSessionIdException at /search/) If the retailers being searched are not the same, the program works fine. It also works fine if the searches don't start or end at almost the same time. Python Selenium Code: def standart_analysis(self, product_keys:list[str], category:str,search_method:int=0, img_method:int=0, goal:int=50, sleep_time:float=1): """ It searches for the given product codes in the given retails and analyzes the information it finds. * product_keys: The products from which information will be obtained in the search and analysis should be given as a list of strings. * category: Category type of products to be searched. ----------- * search_method '0': Google search with Request library * search_method '1': Google search with Google library * search_method '2': Google search with Selenium Webdriver * search_method '3': Search in Retail ----------- * img_method '0': Take screenshot * img_method '1': Download … -
django-ses: Connect timeout when using django.core.mail
I am using django-ses==3.4.1 to send email via django.core.mail and both send_mail() and EmailMessage() get the connection timeout after one minute: botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://email-smtp.eu-central-1.amazonaws.com/ Using this configuration in settings.py according to the instructions on https://pypi.org/project/django-ses/ EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_USER = 'my-verified@email' AWS_SES_ACCESS_KEY_ID = '-my-access-key-' AWS_SES_SECRET_ACCESS_KEY = '-my-secret-access-key-' AWS_SES_REGION_NAME = 'eu-central-1' AWS_SES_REGION_ENDPOINT = 'email-smtp.eu-central-1.amazonaws.com' Where I use the variable AWS_SES_USER as from_email while calling email = EmailMessage(subject, message, from_email, recipient_list) email.content_subtype = 'html' email.send() I have also tested if the SES works without Django, i.e. simply using smtplib and it does. The working example derived from https://realpython.com/python-send-email/#option-2-using-starttls smtp_server = "email-smtp.eu-central-1.amazonaws.com" port = 587 # Create a secure SSL context context = ssl.create_default_context() # Try to log in to server and send email try: server = smtplib.SMTP(smtp_server,port) server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(AWS_SES_ACCESS_KEY_ID, AWS_SES_SECRET_ACCESS_KEY) message = """\ Subject: Test SES This message is sent from Python.""" receiver_email = 'my-recipient@email' server.sendmail(AWS_SES_USER, receiver_email, message) I have tried changing the parameters in settings.py in many ways, but without success. -
Is there any workaround to get celery task result if celery result backend is disabled?
I need to get a result of celery task but there is no CELERY_RESULT_BACKEND in the project I'm working on. | -------------- celery@e465919cc343 v5.2.3 (dawn-chorus) | --- ***** ----- | -- ******* ---- Linux-5.19.0-43-generic-x86_64-with-glibc2.31 2023-06-13 18:45:02 | - *** --- * --- | - ** ---------- [config] | - ** ---------- .> app: cms:0x7feb41db9490 | - ** ---------- .> transport: redis://redis-xxxxx:6379/0 | - ** ---------- .> results: disabled:// | - *** --- * --- .> concurrency: 8 (prefork) | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) | --- ***** ----- It means an expression like task = my_task.delay(keyword=domain).get() won't ever work. What can I do? Is there any workaround? Everything I tried failed to work. It seems that it's impossible according to Celery documentation. -
How to write/mock testcases for uidb64 and tokens in DRF
I'm trying to verify user once user signup is done. I'm not sure how i can mock the uidb64 and token fields here. Can I get help with some mock test case here ? I have views.py class VerifyUserEmailAPIView(generics.GenericAPIView): serializer_class = EmailVerificationSerializer def patch(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): user = serializer.validated_data user.is_verified = True user.save() return Response(status = status.HTTP_200_OK) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py class EmailVerificationSerializer(serializers.Serializer): uidb64 = serializers.CharField(min_length = 1, max_length = 20) token = serializers.CharField(min_length = 10, max_length = 100) class Meta: fields = ['uidb64', 'token'] def validate(self, attrs): attrs = super().validate(attrs) uidb64 = attrs.get('uidb64', '') token = attrs.get('token', '') pk = urlsafe_base64_decode(uidb64).decode() if not pk.isnumeric(): raise ValidationError("Invalid type received for user id") if not User.objects.filter(pk = pk).exists(): raise ValidationError("Unable to find user") user = User.objects.get(pk = pk) isTokenValid = account_activation_token.check_token(user, token) if not isTokenValid: raise ValidationError("Invalid or expired token") return user