Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display the value instead of the ID in the form in Django
I need to display the time, but the form outputs the ID models.py class Ticket(models.Model): concert = models.ForeignKey('Concert', related_name='concert_name', on_delete=models.PROTECT) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) place = models.ForeignKey('Place', on_delete=models.PROTECT) date_time = models.ForeignKey('Time', on_delete=models.PROTECT) price = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.first_name}, {self.last_name}, {self.date_time}" class Concert(models.Model): name_concert = models.CharField(max_length=50) description = models.TextField(max_length=500) length = models.TimeField() type = models.ForeignKey('Type', on_delete=models.PROTECT) janr = models.ForeignKey('Janr', blank=True, null=True, on_delete=models.PROTECT) regisser = models.ForeignKey('Regisser', blank=True, null=True, on_delete=models.PROTECT) date_time = models.ForeignKey('Time', on_delete=models.PROTECT) img = models.ImageField(upload_to='photo/', blank=True, null=True) price = models.IntegerField(blank=True, null=True) def __str__(self): return self.name_concert class Time(models.Model): date_time = models.DateTimeField() def __str__(self): return format(self.date_time, "%d.%m.%y %H:%M") forms.py class ticketForm(forms.ModelForm): class Meta: model = Ticket fields = ['first_name', 'last_name', 'concert', 'date_time', 'price', 'place'] widgets = { "first_name": TextInput(attrs={ 'class': 'input-style', 'placeholder': 'Имя' }), "last_name": TextInput(attrs={ 'class': 'input-style', 'placeholder': 'Фамилия' }), "concert": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.concert_name', 'readonly': 'readonly' }), "date_time": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.date_time', 'readonly': 'readonly' }), "price": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.price', 'readonly': 'readonly' }), "place": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': '', 'readonly': 'readonly' }) } views.py def ticketsSite(request, concert_id): ticket = get_object_or_404(Concert, id=concert_id) form = ticketForm(initial={'concert': ticket.name_concert, 'price': ticket.price, 'date_time': ticket.date_time}) context = { 'ticket': ticket, 'form': form … -
Authenticate method in django returns None
It is the first time I do a project in Django. As a first step, I am creating methods to sign-up and sign-in users. The sign-up works well. However, after registering an user, I try to sign-in without success. My models.py file is: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **extra_fields): user = self.model(username=username, email=email, **extra_fields) # set_password will handle the password before saving it in the database # It hash the password before saving it user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=256) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username class Meta: managed = True db_table = "users" and the sign-in method in views.py is the following one: def signin(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") # Authenticate the user user = authenticate(request, username=username, password=password) # If it is not None - user exists and right credentials if user: login(request, user) fname = … -
Implementing Autocomplete for M2M Fields in Wagtail CustomUser Model
I have added two additional fields to my CustomUser model in my Wagtail project. These two fields are many-to-many (m2m) fields, and in the form, I want these fields to be represented as an Autocomplete feature. How can I achieve this? models.py class User(AbstractUser): journal = models.ManyToManyField("journal.Journal", verbose_name=_("Journal"), blank=True) collection = models.ManyToManyField("collection.Collection", verbose_name=_("Collection"), blank=True) forms.py class CustomUserEditForm(UserEditForm): journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) class CustomUserCreationForm(UserCreationForm): journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) -
Python - remove commas and leave decimal points from string as number
As of title, I need to remove commas from string number and leave decimal point, but the problem is input can be with . or ,. This input will be saved for Django model's DecimalField For example: Input: 250,000,50 250,000 250000.00 25,000 Output: 250000.50 250000.00 250000.00 25000.00 What I have tried: def _normalize_amount(self, value -> str): normalized_amount = value[:-3].replace(",", "") + value[-3:] return Decimal(normalized_amount) Problem is that this function can not handle the cases where user enters , as decimal point. How to solve this case ? -
Website wont load! How do i get my website files online via Hostinger?
Im starting up a website company that compares dentists' prices and lets you book online. Ive had a freelancer develop a python coded website using Django creating the back end and the front end. Think he used ubuntu. He showed me a loom recording of the website working and then sent me the files. I just cant get the website to load/work Ive set up my domain in godaddy - www.toothpik.co.uk I have hosting on hostinger, got a VPS server at their instruction to allow python code. Ive uploaded the files to the shared web server, then i also configured the SFTP via WinSCP and i can see the files that the Dev send me from an expanded zip file. I have linked my VPS IP to keys generated in puTTY for SSH which is enabled on my hostinger using a public key into hostinger Sorted all my DNS out so it points from godaddy to hostinger (i want to do cloud flare in future, god help me on that) getting Hello World message when visiting the website URL to Hostinger. Im not very techy, but im learning Ive read about Git, PuTTY etc. Ive been talking with the hostinger … -
Display unique records in a django table
I have three models: class Member(models.Model): person_id = models.CharField(max_length=100, null=True) first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) minit = models.CharField(max_length=1, null=True) dob = models.DateField(null=True) class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=100) project_owner = models.CharField(max_length=100) dos_from = models.DateField() dos_to = models.DateField() class Review(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='review_rel') project = models.ForeignKey(Project, on_delete=models.CASCADE) dos= models.DateField() review_type= models.CharField(max_length=25) Some members will have no reviews at all, some will have multiple reviews even within the same project. I would like to create a table with one row per member and project for the members who are assigned a review. When I start with the Review model, I get multiple rows for the same member (if the member has more than one review within the same project) I don’t know how to dedup it. import django_tables2 as tables class Reviews_Table(tables.Table): class Meta: model = Review fields = ( "project__project_name", "member__person_id", "member__first_name", "member__last_name", "member__minit", "member__dob", ) I also tried starting with the Member Model, but I can’t figure out how to go backwards and link to the Review model. I have been stuck on this for a while. I would truly appreciate help. Thank you -
Managing ALLOWED_HOSTS in Django for Kubernetes health check
I have a Django application running on Kubernetes, using an API for health checks. The issue I'm facing is that every time the IP associated with Django in Kubernetes changes, I have to manually update ALLOWED_HOSTS. django code: class HealthViewSet(ViewSet): @action(methods=['GET'], detail=False) def health(self, request): try: return Response('OK', status=status.HTTP_200_OK) except Exception as e: print(e) return Response({'response': 'Internal server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) deployment code : livenessProbe: httpGet: path: /health/ port: 8000 initialDelaySeconds: 15 timeoutSeconds: 5 Error: Invalid HTTP_HOST header: '192.168.186.79:8000'. You may need to add '192.168.186.79' to ALLOWED_HOSTS. Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py", line 135, in __call__ response = self.process_request(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/http/request.py", line 148, in get_host raise DisallowedHost(msg) django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '192.168.186.79:8000'. You may need to add '192.168.186.79' to ALLOWED_HOSTS. Bad Request: /health/ Is there a way to dynamically use ALLOWED_HOSTS and avoid manual updates? (Every deployment IP changed.) ALLOWED_HOSTS ALLOWED_HOSTS = [localhost', '127.0.0.1'] Any guidance or suggestions for the best solution in this regard would be appreciated. -
Adding several object on the same djangoform
There is this code to register devices in a database. You fill the form with some data, like MAC, and save it. I want to implement a function where you split up several MACs with ,(comma) and for each MAC a new device is added to DB(this table has an autoincrement sequence). Basically my code is: for i in listmac.split(","): form2 = form.save(commit=False) #next_id = Net.objects.order_by('-id_seq').first().id_seq+1 #form2.id_seq=next_id form2.mac = i form2.save() The problem:\ Let's say my next id is 150.\ With the code like that, if I put 3 MACs, the code tries to add 3 devices with the seq=150, therefore only the last one is saved.\ If i uncomment those two lines, it adds correctly 150, 151 and 152, but it does not save the sequence in the autoincrement field. So if I try to insert another register directly through the database for example, it tries to insert 151 and it gives me an error. -
Adding attributes to functions outside function scope
Does this add new attributes to the view function in the View Class of python? This is the definition of as_view() function in View class of view.generic.base module. @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError( "The method name %s is not accepted as a keyword argument " "to %s()." % (key, cls.__name__) ) if not hasattr(cls, key): raise TypeError( "%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key) ) def view(request, *args, **kwargs): self = cls(**initkwargs) self.setup(request, *args, **kwargs) if not hasattr(self, "request"): raise AttributeError( "%s instance has no 'request' attribute. Did you override " "setup() and forget to call super()?" % cls.__name__ ) return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # __name__ and __qualname__ are intentionally left unchanged as # view_class should be used to robustly determine the name of the view # instead. view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__annotations__ = cls.dispatch.__annotations__ # Copy possible attributes set by decorators, e.g. @csrf_exempt, from # the dispatch method. view.__dict__.update(cls.dispatch.__dict__) # Mark the callback if the view class is async. if … -
SimpleListFilter does nothing - but neither does any other list_filter
when applying a SimpleListFilter in Django 5 admin, I get the same queryset no matter the value. After some testing I realized, the matter is not only with the SimpleListFilter, but all fields of list_filter. class Monitor(models.Model): serial = models.CharField("serial", max_length=9, primary_key=True) status = models.PositiveSmallIntegerField("status", default=0) class StatusFilter(admin.SimpleListFilter): title = "status" parameter_name = "status" def lookups(self, request, model_admin): return [(0, "off"), (1, "busy"), (2, "on")] def queryset(self, request, queryset): print("value:", self.value(), type(self.value())) if self.value() == 0: qs = queryset.filter(status=0) print("queryset count", qs.count()) return qs elif self.value() == 1: qs = queryset.filter(status=1) print("queryset count", qs.count()) return qs elif self.value() == 2: qs = queryset.filter(status=2) print("queryset count", qs.count()) return qs print("no filter") return queryset The example of the SimpleListFilter shows the correct amount tough: The numbers in this screenshots are correct (29, 0, 6) When pressing once (!) on a filter, for example "on" I get multiple prints returned, which is many more than I would expect: value: 2 <class 'str'> no filter value: 0 <class 'int'> queryset count 29 value: 1 <class 'int'> queryset count 0 value: 2 <class 'int'> queryset count 6 value: 2 <class 'str'> no filter value: 2 <class 'str'> no filter value: 2 <class 'str'> no filter … -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS DJANGO_SETTINGS_MODULE
Does anyone know if there are any import or project organization problems? I have mainly seen views and models to see if there was a problem there but I have no solution enter image description here I have tried everything, sorry, I'm just starting with django on my own. enter image description here -
expected str, bytes or os.PathLike object, not NoneType for subprocess of ffmpeg
I dont know much about ffmpeg, subprocess and its functions, im trying to take a screenshot form a video and save it at my other field of my model. this is my model: class SubSong(models.Model): song = models.ForeignKey(SongPage, on_delete=models.CASCADE, related_name='related_song') create = jmodels.jDateField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='related_user') video = models.FileField(upload_to='sub_video/',) like = models.ManyToManyField(User, blank=True, ) total_like = models.PositiveIntegerField(default=0) is_allowed = models.BooleanField(default=False) image_sub = ThumbImage(upload_to='sub_songs/', default='1.jpg') def __str__(self): return self.song.title and views.py if request.method == 'POST': authen(request) form = MyTryForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data x = SubSong.objects.create(song_id=id, user_id=request.user.id, video=data['video'], ) path = x.video.name out = path.replace('sub_video/', '').replace('mp4', 'jpg') z=subprocess.check_output( ffmpeg.input('media/' + path, ss='00:00:50').filter( 'thumbnail').output('media/sub_songs/' + out, vframes=1).run(), text=True) x.image_sub=z x.save() messages.success(request, 'ویدیوی شما با موفقیت ارسال شد ، پس از بررسی منتشر خواهد شد') return redirect(request.META.get('HTTP_REFERER')) else: messages.error(request, 'ویدیوی شما بارگداری نشد') return redirect(request.META.get('HTTP_REFERER')) it can save the video and also default picture 1.jpg at image_sub. also it can save scrrenshot at the media/sub_song/.but my problem is that it gives me error: expected str, bytes or os.PathLike object, not NoneType how i should return the screen from subprocess to save it as my image_sub field? and why do this error raise? i dont want to see this error … -
Django log out problems
I am developing a tweet application and while I can log in during the authentication process, my logout function does not work. I leave my source codes to explanation. I'm waiting for your help The error I get is as follows: (http://127.0.0.1:8000/logout/?next=/) and i get This site cannot be reached error! More precisely, I cannot access the page I want. When I click on logout, I have to log out of the account. I should also mention that I am using Python 3.12.0 and Django. my urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("",include('tweetapp.urls')), path("",include('django.contrib.auth.urls')),] my views.py from django.shortcuts import render, redirect from . import models from django.urls import reverse from tweetapp.forms import AddTweetForm, AddTweetModelForm def listtweet(request): all_tweets = models.Tweet.objects.all() tweet_dict = {"tweets":all_tweets} return render(request,'tweetapp/listtweet.html',context=tweet_dict) def addtweet(request): if request.POST: nickname = request.POST["nickname"] message = request.POST["message"] models.Tweet.objects.create(nickname=nickname, message=message) return redirect(reverse('tweetapp:listtweet')) else: return render(request,'tweetapp/addtweet.html') def addtweetbyform(request): if request.method == "POST": form = AddTweetForm(request.POST) if form.is_valid(): nickname = form.cleaned_data["nickname_input"] message = form.cleaned_data["message_input"] models.Tweet.objects.create(nickname=nickname, message=message ) return redirect(reverse('tweetapp:listtweet')) else: print("error in form") return render(request,'tweetapp/addtweetbyform.html', context={"form":form}) else: form = AddTweetForm() return render(request,'tweetapp/addtweetbyform.html', context={"form":form}) def addtweetbymodelform(request): if request.method == "POST": form = AddTweetModelForm(request.POST) if form.is_valid(): print(form.cleaned_data) return redirect(reverse('tweetapp:listtweet')) … -
How to edit list_editable only to be available before 30 days pass Django_Admin
So I've got some transactions and every transaction has some editable fields from list editable, now this way they are editable all the time, but what I want to do is make them be editable only if they are not older then 30 days, when they get older then 30 days list_editable is just empty "list_editable = []". class Transaction(BaseModel): date = models.DateField( blank=False, null=False, db_index=True, default=datetime.now) user = models.ForeignKey(User, blank=False, null=False, on_delete=models.PROTECT) amount = models.IntegerField(blank=False, null=False) description = models.CharField(max_length=500, blank=True, null=True) ... class TransactionAdmin (ExportActionMixin, BulkModelAdmin): list_editable = ['date', 'user', 'amount', 'description'] **Now I tried to put this in an if statement that if the transaction dates + 30 days are older then the date now list editable should be the normal list editable with the fields else it should be empty, thats just what the latest thing I tried was. I tried it in every possible variation **( that I could think of ) but I always end up with the same result It either gives me all the list **editable fields for all transactions or none list editable fields. Now my question is what am i doing wrong, am I going about it the wrong way or … -
How to get the average of a specific value in Django queryset
I have two models 'Teams' and 'Members'. One of the fields in Members is 'favorite_team' and a field in Teams is 'favorite_avg' I am trying to get an average of the favorite_team field by entering in a value. I am trying to find a better/faster way to do this: all_members = Members.objects.all().count() giants_fans = Members.objects.filter(favorite_team='New York Giants').count() team = Teams.objects.get(name='New York Giants') team.favorite_avg = giants_fans/all_members team.save() -
Django Rest Framework best way to delete an object
So I"M Trying to make this delete method in my drf project. i setuped the @api_view(['DELETE']) to the views function and setuped a form method to delete the object. but it didn't worked well. so i have to make the @api_view to post method and set the form method to post to delete the object. is there any way i can make this using delete method?. this is my view @api_view(['POST']) @permission_classes([IsAuthenticated]) def delete(request,article_id): if request.method == 'POST': article = get_object_or_404(Article, pk=article_id) if article.author == request.user: article.delete() return redirect('/') return Response(status=status.HTTP_400_BAD_REQUEST) this is my form method <form action="{% url 'news:delete' article.id %}" method="post"> {% csrf_token %} <input type="submit" value="delete"> </form> -
Django migrations on celery not stoping after .save()
I have a django application and celery, and one of the tasks is to create a tenant in '/admin' @app.task def create_tenant_account(form_data): ... tenant = Company(...) tenant.save() ... After tenant.save() all of the migrations start applying, but suddenly the celery crashes because the code dont stoped after tenant.save() (after the save, I have some tenants setup that needs to run after) This only happens on celery, locally it stops and runs normally. Is there a way to prevent the code from runing? My solution was to create another function to run after the tenant.save(), but for now, I need the setup to run in the same function. -
How to implement subquery in Django ORM?
I have a Postgres sql query that looks like below SELECT Date_trunc('hour', batch_time) + Date_part('minute', batch_time) :: INT / 10 * interval '10 min', Round(Avg(min_metric) :: NUMERIC, 2), metric_notify FROM (SELECT batch_time, Min("uptime") AS min_metric, Coalesce(CASE WHEN notify LIKE '%HIGH%' THEN 'HIGH' ELSE '' END, '') AS metric_notify FROM lt_store WHERE batch_time >= '2024-01-14 09:01:26.656059' AND batch_time <= '2024-01-15 09:01:26.656055' GROUP BY 1, 3 ORDER BY 1 ASC) AS subq GROUP BY 1, 3 As you can see, there are two queries. In the inner query, I do min aggregation on the metric with a group by on time and in the outer query, I do avg aggregation on the metric with a 10 min time interval truncation. Now I plan to replicate the same in django query and this is what I do result1 = LtStore.objects.filter(batch_time__gte='2024-01-14 09:01:26.656059', batch_time__lte='2024-01-15 09:01:26.656055' ).values ('batch_time').annotate(min_metric=Round(Min('uptime')), metric_notify=Coalesce(Max( Case( When(notify__contains='HIGH', then=Value('HIGH')), default=Value(''), )), Value('') ), ).order_by("batch_time") trunc_query = "date_trunc('hour', LtStore.batch_time) + date_part('minute', LtStore.batch_time)::int / 10 * interval '10 min'" result2 = LtStore.objects.annotate( min_metric=Subquery(result1.values('min_metric')[:1]), metric_notify=Subquery(result1.values('metric_notify')[:1]) ).extra({"trunc": trunc_query}).values( 'trunc', 'metric_notify' ).annotate( avg_metric=Avg('min_metric') ).order_by("trunc") The above django query works but I get a different result as compared to the one with sql query. What am I doing wrong? -
Safari Takes Excessive Time to Load and Render Server-Sent Events (SSE) in Django Application
Here's a brief overview of our implementation: Backend (Django): Sends SSEs using django-eventstream. Events are sent to a URL like https://devbackend.marshallgoldsmith.ai/events/{session_id}, where {session_id} is a unique identifier. Frontend: Uses fetchEventSource to listen to the events from the above URL. We handle various event scenarios such as onmessage, onerror, and onclose. The event stream opens fine in Chrome and even displays correctly when the URL is opened directly in a Chrome browser tab. Issue with Safari: When accessing the event stream URL in Safari, it keeps loading indefinitely and does not display any events, unlike in Chrome. There are no apparent error messages in the Safari console. we checked cross-origin issues and other compatibility issues and searched. But no luck. So if anyone face this kind of issue, please let us know. that will be more helpful. Thanks -
How to connect package django-storages[azure] with docker container?
I have dockerized a django app. And the docker container is working and running smoothly.But now I have installed the package django-storages[azure] for a seperate server for the css and image files. And I can upload images to the azure environment. So if I start the django app with the command python manage.py runserver I can upload images to the Azure container. But if I try to build the docker container with the commands: docker compose -f docker-compose-deploy.yml build and docker compose -f docker-compose-deploy.yml up And I go to: http://localhost/admin/ I will get an: admin/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) dockerfile: # pull official base image FROM python:3.9-alpine3.13 # ENV PATH="/scripts:${PATH}" # set work directory # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./scripts /scripts WORKDIR /usr/src/app EXPOSE 8000 # install psycopg2 dependencies ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client jpeg-dev && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ … -
<rest_framework.request.Request: PATCH catching the whole debugging instead of the id/url
So i'l using a class Class(ApiView) in my code and create a patch request from the front i'm getting this error api- | /v1/a06300db-30bc-4890-8154/ api- | heeeeeeeeeeello world api- | print id <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> api- | Good bye world api- | ["“<rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'>” is not a valid UUID."] api- | 112.00.0.10 - "PATCH /v1/claims/a06300db-30bc-4890-8154-d1813a08f68e/ HTTP/1.0" 500 145 so when i make the http axios patch request i pass the id as arg a06300db-30bc-4890-8154 and it undestand very well since i'm able to make the request now the problem is that when i print the id instead of getting just a06300db-30bc-4890-8154 i get the whole object <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> and since this is not valid a get the error is not a valid UUID."] i don't undestand why im getting the whole url as the id <rest_framework.request.Request: PATCH i tried, usinkg the pk, the arks, kwargs and the id itself to retrieve the id, but i always get <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> i tried `def patch(request, id):` or even just `def patch(request):` still getting the same ` <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> `as id -
Issue with Forbidden Error when Accessing Django Backend through AWS API Gateway
My web application faces a perplexing 403 Forbidden Error when calling the Django backend (hosted on Railway.app) through AWS API Gateway (proxy). This error curiously only manifests in live scenarios, as testing the API Gateway endpoint from the AWS console works flawlessly. I've meticulously ruled out potential culprits like authorization mechanisms, Web ACL, and API key requirements. Interestingly, swapping out Django for a different backend, the Starwars API in this case, completely eliminates the error, hinting at a potential compatibility issue between AWS and Django in my specific configuration. To further isolate the source of the problem, I undertook the following actions: Deployed the Django app on both Railway.app and an EC2 instance, eliminating any platform-specific hosting issues. Configured Django to allow all origins and request headers, preemptively addressing potential CORS restrictions. Verified that no access-limiting resource policies were associated with either the API Gateway or the Django app. These steps successfully ruled out both hosting and CORS as potential culprits, narrowing the investigation down to the intricate configuration of the API Gateway or the logic within the Django application itself. -
Zappa is not deploying all the packages in my virtual env to Lambda
I am deploying a django application using Zappa. My application's dependencies are bigger than 1GB in size for this reason I am using slim_handler:true parameter in zappa settings as well as increasing ephemeral size of lambda using "ephemeral_storage": {"Size": 10240}, but still i am getting error django not found in my cloudWatch logs. All my configurations are attached below: My zappa_settings.py file: { "test-staging": { "ephemeral_storage": {"Size": 10240}, "aws_region": "us-west-1", "django_settings": "lu_development.settings", "profile_name": "default", "project_name": "linkedunion-bac", "runtime": "python3.10", "s3_bucket": "zappa-sultan-test-migration", "slim_handler": true } } All the packages installed in my virtual env: aioredis==1.3.1 amqp==2.6.1 anyio==4.0.0 argcomplete==3.2.1 asgiref==3.7.2 async-timeout==4.0.3 attrs==23.1.0 autobahn==23.6.2 Automat==22.10.0 autopep8==2.0.4 backoff==2.2.1 billiard==3.6.4.0 boto==2.49.0 boto3==1.24.8 botocore==1.27.8 celery==4.4.3 certifi==2023.7.22 cffi==1.15.1 cfn-flip==1.3.0 channels==3.0.5 chardet==3.0.4 click==8.1.7 constantly==15.1.0 cryptography==41.0.3 daphne==3.0.2 Deprecated==1.2.14 Django==4.0.10 django-cacheops==7.0.1 django-cors-headers==3.14.0 django-debug-toolbar==4.0.0 django-environ==0.4.5 django-mysql==3.9.0 django-ninja==0.22.2 django-redis==5.3.0 django-simple-history==2.12.0 django-storages==1.10 djangorestframework==3.14.0 djangorestframework-simplejwt==4.6.0 durationpy==0.6 exceptiongroup==1.1.3 factory-boy==3.3.0 Faker==19.3.1 funcy==1.18 gcloud==0.18.3 geographiclib==2.0 geopy==2.4.0 googleapis-common-protos==1.52.0 grpcio==1.60.0 gunicorn==20.0.4 h11==0.14.0 hiredis==2.2.3 hjson==3.1.0 httpcore==0.17.3 httplib2==0.22.0 httpx==0.24.1 hyperlink==21.0.0 idna==2.10 importlib-metadata==6.11.0 incremental==22.10.0 jmespath==0.10.0 JSON-log-formatter==0.5.2 jws==0.1.3 kappa==0.6.0 kombu==4.6.11 markdown-it-py==3.0.0 MarkupSafe==2.1.3 mdurl==0.1.2 mysql-connector==2.2.9 mysql-connector-python==8.0.21 mysqlclient==2.0.1 numpy==1.25.2 oauth2client==4.1.2 onesignal-sdk==2.0.0 opentelemetry-api==1.19.0 opentelemetry-distro==0.40b0 opentelemetry-exporter-otlp==1.19.0 opentelemetry-exporter-otlp-proto-common==1.19.0 opentelemetry-exporter-otlp-proto-grpc==1.19.0 opentelemetry-exporter-otlp-proto-http==1.19.0 opentelemetry-instrumentation==0.40b0 opentelemetry-instrumentation-celery==0.40b0 opentelemetry-instrumentation-dbapi==0.40b0 opentelemetry-instrumentation-django==0.40b0 opentelemetry-instrumentation-logging==0.40b0 opentelemetry-instrumentation-psycopg2==0.40b0 opentelemetry-instrumentation-redis==0.40b0 opentelemetry-instrumentation-requests==0.40b0 opentelemetry-instrumentation-urllib3==0.40b0 opentelemetry-instrumentation-wsgi==0.40b0 opentelemetry-proto==1.19.0 opentelemetry-sdk==1.19.0 opentelemetry-semantic-conventions==0.40b0 opentelemetry-util-http==0.40b0 pandas==2.0.3 pdf2image==1.16.3 pep8==1.7.1 Pillow==10.0.1 placebo==0.9.0 protobuf==3.20.3 pyasn1==0.5.0 pyasn1-modules==0.3.0 pycodestyle==2.11.0 pycparser==2.21 pycryptodome==3.10.1 pydantic==1.9.1 Pygments==2.17.2 PyJWT==2.8.0 pymssql==2.2.5 … -
Django Rest Framework generic views, so clunky to get the object/instance
Often I wish to use the created/updated object, for say to log it in some history, or use it in an email. E.g.1. CreateAPIView def create(self, request, *args, **kwargs): ret = super().create(request, *args, **kwargs) # Do something with the create object here, e.g. create a history log return ret E.g.2. UpdateAPIView def update(self, request, *args, **kwargs): ret = super().update(request, *args, **kwargs) # Do something with the create object here, e.g. create a history log return ret Answers that are not solutions Use ret.data to see a dict of the object data ... because I wish to access the object so so I can look up foreign keys, call methods on it etc. Create a new object using ret.data ... wasteful to create object, through it away, and recreate it again Copy and paste most of the original create/update method just so one can save a reference to the object ... this is terrible because it's the meat of the generic view, so why event use it in the first place. The best I have come up: A CreateAPIView, e.g.: def perform_create(self, serializer): self.object = serializer.save() return self.object def create(self, request, *args, **kwargs): ret = super().create(request, *args, **kwargs) # Do something … -
pytest-django could can't find modules correctly
I have a django project with a structure like below project_root/ │ ├── Tia/ │ ├── manage.py │ ├── Tia/ │ │ ├── __init__.py │ │ ├── my_settings.py │ │ └── ... │ └── repository/ │ ├── __init__.py │ ├── tests/ │ └── ... └── pytest.ini I installed pytest-django and created a pytest.ini file. the context of the file are below: [pytest] DJANGO_SETTINGS_MODULE=MKalender.settings_local_prod_connection python_files = tests.py test_*.py *_tests.py Now I'm getting this Error when running the test only. runserver command works fine: ModuleNotFoundError: No module named 'Tia.repository' Any Idea on how to solve this?