Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When i try to send post request I get error 403
When I try to add an image to the backend using the form with post request, I get a 403 error. I don't know where I made a mistake so I give a link to the github repository https://github.com/Cichyy22/imagur-like-site -
Error when using form.changed_data, "argument of type 'cached_property' is not iterable"
When trying to check if the "author" field has changed I keep getting the error "argument of type 'cached_property' is not iterable". form.py class BookForm(forms.ModelForm): class Meta: model = Product fields = '__all__' **def clean(self): if 'author' in BookForm.changed_data and Book.objects.filter(author=self.cleaned_data['author'], title=self.cleaned_data['title'], genre=self.cleaned_data['genre']).exists(): raise ValueError("Author, title and genre must not be repeated")** models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='product', default=None) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) class Book(Product): author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) admin.py class ItemInline(admin.StackedInline): model = ProductIndex extra = 0 @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'genre', 'price', 'quantity', 'is_available'] list_filter = ['genre', 'is_available'] search_fields = ['title'] exclude = ['popularity'] inlines = [ItemInline] form = BookForm Please point out the error or indicate another alternative to check if the field has changed -
Django Manager-Employee relation
I need some support for this problem i'm facing right now. I created a django app that allows a user(Manager) to register, the user(Manager) can then log in and create accounts for the Employees, they receive an email to set a password, and then can log in, having limited accesibility to the platform. So far I managed to have the manager be able to, edit, activate-deactivate the employee account and even delete it, but there is no relation between the users. If I log in with 2 manager accounts, they both can see all the employee accounts in my employee_list. how can I create a OneToOne relation between the manager and employee so that the manager who created his employee accounts can see them. class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField(default=True) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) manager = models.ForeignKey(User, related_name='employees', on_delete=models.CASCADE) is_employee = models.BooleanField(default=True) def __str__(self): return self.user.username so far this is what I came up with Any help will be so much appreciated. -
ImproperlyConfigured at /watchlist-detail/1 Could not resolve Url for hyperlinked relationship
from .models import WatchList,StreamPlatform from rest_framework import serializers class WatchListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=WatchList fields='__all__' class StreamPlatformSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=StreamPlatform fields='__all__' urls.py file from django.urls import path from . import views urlpatterns = [ path("",views.WatchListAV.as_view()), path("watchlist-detail/<int:pk>",views.WatchListDetailsAV.as_view()), ] views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from .models import WatchList,StreamPlatform from .serializers import WatchListSerializer,StreamPlatformSerializer from rest_framework import status # Create your views here. class WatchListAV(APIView): def get(self,request): # print(self) # print("1") movies=WatchList.objects.all() # print("1") serializer=WatchListSerializer(movies,many=True,context={'request': request}) print(request) # print(serializer.data) return Response(serializer.data) def post(self,request): serializer=WatchListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) class WatchListDetailsAV(APIView): def put(self,request,pk): try: movies=WatchList.objects.get(pk=pk) except: return Response(status=status.HTTP_404_NOT_FOUND) serializer=WatchListSerializer(movies,data=request.data) print("1") if serializer.is_valid(): print("2") serializer.save() return Response(serializer.data) return Response({"error":"Data invalid format"},status=status.HTTP_400_BAD_REQUEST) def get(self,request,pk): try: movie=WatchList.objects.get(pk=pk) except WatchList.DoesNotExist: return Response({'error':"movie not found"},status=status.HTTP_404_NOT_FOUND) serializer=WatchListSerializer(movie,context={'request': request}) print(request) return Response(serializer.data) def delete(self,request,pk): movie=WatchList.objects.get(pk=pk) movie.delete() return Response(status=status.HTTP_404_NOT_FOUND) models.py from django.db import models # Create your models here. class WatchList(models.Model): title=models.CharField(max_length=50) storyline=models.CharField(max_length=200) active=models.BooleanField(default=True) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title i am beginner and i am unable to understand this error.i have searched for solution at different places but not found any solution. I am getting this error. "ImproperlyConfigured at / Could not resolve URL for hyperlinked relationship using … -
How to integrate React with Django api
I started a React project with npm run vite@latest for frontend and a django project for the backend. I created a simple notes app that works with each other. But they have different ports. How to integrate React with Django so when I go to localhost:8000 ReactJS shows up? -
Custom filter backend or Django-Filter?
I work on simple Django project that uses DRf and I have small problem. I want to add filtering and searching to my API endpoints, but I don't know which way is better: Make custom filter backend for filtering and searching logic. Use Django-Filter package for this task. Here is part of my code now: from django.db import models from rest_framework import viewsets, filters class MyModel(models.Model): title = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer filter_backends = [filters.SearchFilter] search_fields = ['title', 'description'] I am just wondering, which method is better for performance, easy to maintain, and follows best practices? Can you tell me pros and cons for both methods and any problems I can have? For example, if I make custom filter backend, how to make it good? If I choose Django-Filter, are there problems or limits I should know? I am very thankful for any help and advice! -
Will i be able to host my django web app on heruko if i have a github student developer pack
So, I have a Django web app I need to host, and I want to host it for free. But Heroku's service is not free, but I have the Github student developer pack and saw Heroku's service on it. Will I be able to host my Django project on it now, and if yes, then how do I do it? My Django web app has data that goes to the Django console and Firebase real-time database. Or can I get a free alternative? -
What is a better way to use 'request' in a ModelChoiceField
Is there any way to use user=request.user inside ModelChoiceField when I use this method I got an error: NameError: name 'request' is not defined. class AlbumForm(forms.Form): album = ModelChoiceField(queryset=Album.objects.filter(user=request.user) The model: class Album(models.Model): name = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE) -
django application on AWS fargate with postgresql persistent database
I have django + reactjs application. It used postgresql db. Currently i am using a docker compose on my pc and able to spin up the applicaiton. I have volume where the postgresql db is stored. Now What the right way to put this application in to the aws ECS. Also i am not sure how to create migrations in fargate, because we may not have access using ssh. -
'int' object is not iterable - sum up 2 variables after an if statement in django/python
I am looking to sum 2 variables together and getting error: 'int' object is not iterable. In summuary, I have a sort of todo list. Every time an action is validated by creating an Validation object model, the action is given 1 point. If all actions within the task have received 1 point, then the task is considered completed. I am stuck at the sum of points. I feel I need to write a sort of for loop after my if statement to add up each point in each action together. I tried different combos, but none seem to work. Am I getting this wrong? (I am sure my code is also far from being optimal, so I wont be offended if you offer an alternative) models class Action(models.Model): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class ValidationModel(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(Action, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class Task(models.Model): title = models.CharField(verbose_name="title",max_length=100, null=True, blank=True) venue = models.ManyToManyField(Action, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class TaskAccepted(models.Model): name = models.ForeignKey(Task,null=True, blank=True, on_delete=models.SET_NULL, related_name='task_accepted') user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) accepted_on = models.DateTimeField(auto_now_add=True, null=True, blank=True) views def function(request, taskaccepted_id): instance_1 = Action.objects.filter(task__id=taskaccepted_id) action_count = instance_1.count() instance_2 = get_object_or_404(Task, … -
E2E tests using selenium giving requested image's platform does not match the detected host platform (linux/arm64/v8)
For E2E tests for a Django app I was using selenium/standalone-chrome selenium: image: selenium/standalone-chrome container_name: selenium ports: - "4444:4444" but then started to get the following error selenium The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested How to proceed to get E2E tests? -
Admin. Register model in other app administration
In admin panel I'm looking to having all user related models in one app administration, including Group and Permission models, which are by default included in Authentication and authorization app. Is there a way of changing default render place of model in admin? Also, I'm understand that I can inherit a Group class to make my own, but I'd like to avoid that. I've tried making custom ModelAdmin and to ugregister and register with it, but it's still in Authentication and authorization. My code right now (as starting point): from django.contrib.auth.models import Group class GroupAdmin(admin.ModelAdmin): filter_horizontal = ('permissions',) admin.site.unregister(Group) admin.site.register(Group, GroupAdmin) -
LOG: unexpected EOF on client connection with an open transaction
I am getting LOG: unexpected EOF on client connection with an open transaction from postgresql log when saving object on django admin and no any log or error from django, and browser gives me following error: Everything was fine before I started to use Celery for schedule tasks. I couldn't find where the proble is coming. signals.py @receiver(post_save, sender=Posts) def send_save_obj(sender, instance, created, **kwargs): # Translate to latin relates_to = instance title = to_latin(instance.title) author = instance.author ... # Creating latin obj if created and language == 'uz': def save_latn_obj(): # create latin post post = PostUzLatn.objects.create( relates_to=relates_to, title=title, ... ) post.tags.add(tags) transaction.on_commit(save_latn_obj) # Sending to telegram channel # Get the current time in the server's local time zone server_time = datetime.now() # Create a timezone object for Tashkent tashkent_tz = pytz.timezone('Asia/Tashkent') # Convert the server time to Tashkent time tashkent_time = server_time.astimezone(tashkent_tz) if 'tg' in instance.social_network \ and publish <= tashkent_time: send_news( title=instance.title, ) # Update status after sending msg Posts.objects.filter(id=instance.id).update(is_sent=["is_sent_tg",]) # Delete the cache key to invalidate the cache for this view cache.clear() bot.py def send_news(title): if tizer: bot.send_video(CHANNEL_ID, video=tizer, caption=title, supports_streaming=True) else: bot.send_photo(CHANNEL_ID, image, caption=text) -
Gow ot save info about search in django?
I want to do pagination. And when I press to button 'Next' on my page, my website breaks down. It happens because for the next page variable 'searched' is empty. 'Searched' is name of tag input in my form I don't know how to save variable 'searched' for the next page. def search(request): if request.method == 'GET': # API-call searched = request.GET.get('searched') headers = { 'Authorization' : basic_auth(login, password)} params = {'PIN':searched,'VKORG':'4000','KUNNR_RG':'43282126'} res = requests.post(url_for_search,headers=headers,data=params) if 200 <= res.status_code < 300 : names = get_unique_names(res.json()) if not Profile.objects.filter(NAME__in = names).exists(): # Deserialization serializer = ProfileSerializer(data=res.json()['RESP'],many = True) serializer.is_valid() serializer.save() # Getting data from ORM products = Profile.objects.filter(NAME__in = names).distinct() # Pagintation p = Paginator(products,10) page = request.GET.get('page') page_obj = p.get_page(page) return render(request,template,{"page_obj":page_obj,'searched':searched}) else: return HttpResponse('Error') Maybe you can help me? :) -
Django Chained Dropdown implementation on Django admin
the issue i'm facing is I set a district and the city which is under the district and save it. It saves correctly to the database. And when I come back to the page and change the city and save, the city is set to null and the district too is set to null in the database How do i solve it Context: Trying to overwrite django admin change_form for SchoolProfileForm and for the dependable dropdown of province, district, city and ward. when trying to change the already saved city from before, the district value is resetted to nothing and also the city's value(same issue with the ward , the city is also resetted) Javascript Functions: function resetDistrict() { let $ = django.jQuery; let district_list = '<option value="" selected="">---------</option>' $('#select2-id_district-container').html(district_list); console.log(district_list) } function getDistrict(province_id) { resetDistrict() let $ = django.jQuery; $.get('/school/district/' + province_id, function (resp){ let district_list = '<option value="" selected="">---------</option>' $.each(resp.data, function(i, item){ district_list += '<option value="'+ item.id +'">'+ item.name +'</option>' }); $('#id_district').html(district_list); }); } function getDistrictfromDb(province_id) { let $ = django.jQuery; $.get('/school/district/' + province_id, function (resp){ let district_list = '<option value="" selected="">---------</option>' $.each(resp.data, function(i, item){ district_list += '<option value="'+ item.id +'">'+ item.name +'</option>' }); $('#id_district').html(district_list); }); } function … -
Django asking wrong
I have a problem that my first home page see css file but /about/ page not. In terminal I have Home page asking: static/welcome.css About page asking: about/static/about.css and I don't know how to fix that tried reloading server rewriting code -
Create Django Authentication using Amazon Cognito
I am trying to run my Django login and signup authentication using Amazon Cognito and all other services using default database. But I am not able to find any suitable example for that. I have followed the following documentation. But didn't get any success. https://github.com/labd/django-cognito-jwt I am usinng the following libraries: Django==4.1.7 djangorestframework==3.14.0 django-cognito-jwt==0.0.4 Can anyone please help me in this? Thank you. -
Django, Swagger and Cors
I have a Django Rest Framework API that I have deployed on Azure Web App, I installed and configured coresheaders and drf_yasg as shown below.. BASE_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'rest_framework', 'corsheaders', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'drf_yasg', ] CREATED_APPS = [ 'authentication.apps.AuthenticationConfig', 'administrator.apps.AdministratorConfig', ] INSTALLED_APPS = BASE_APPS + THIRD_PARTY_APPS + CREATED_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://abcdefg.azurewebsites.net", ] I have also added ALLOWED_HOSTS = ["abcdefg.azurewebsites.net", "127.0.0.1"] When I make any kind of request from Swagger UI I get CORS error but when I use an endpoint like http://abcdefg.azurewebsites.net/auth/login/ I do not get any error. What could I have missed in configuring Swagger or CORS? In ALLOWED_HOSTS, why does it fail if I add http:// or https:// to the domain? Packages: drf-yasg==1.21.4 django-cors-headers==3.13.0 -
How to debug this error import error in django
ImportError at / templates doesn't look like a module path Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Exception Type: ImportError Exception Value: templates doesn't look like a module path Exception Location: C:\Users\Kabilan KB\Desktop\PK\PFA\registration\venv\Lib\site-packages\django\utils\module_loading.py, line 27, in import_string Raised during: app.views.SignUpPage Python Executable: C:\Users\Kabilan KB\Desktop\PK\PFA\registration\venv\Scripts\python.exe Python Version: 3.11.2 Python Path: ['C:\Users\Kabilan KB\Desktop\PK\PFA\registration', 'C:\Users\Kabilan KB\Desktop\PK\PFA\registration', 'C:\Program Files\JetBrains\PyCharm ' '2022.3.3\plugins\python\helpers\pycharm_display', 'C:\Users\Kabilan ' 'KB\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\Kabilan KB\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\Kabilan KB\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\Kabilan KB\AppData\Local\Programs\Python\Python311', 'C:\Users\Kabilan KB\Desktop\PK\PFA\registration\venv', 'C:\Users\Kabilan ' 'KB\Desktop\PK\PFA\registration\venv\Lib\site-packages', 'C:\Program Files\JetBrains\PyCharm ' '2022.3.3\plugins\python\helpers\pycharm_matplotlib_backend'] Server time: Fri, 31 Mar 2023 09:22:56 +0000 How to solve this type of error in django -
how can i download files in aws s3 buckets with Django and boto3
I've been trying to download a file through this view after users pay for it, but i can't seem to make it work. i first tried using file response urls.py urlpatterns = [ path('download-files/<int:id>/<str:order_id>/', download_file, name='download_file'), ] views.py def download_file(request, id, order_id): obj = Product.objects.get(id=id) order = Order.objects.get(order_id=order_id) file = obj.file response = FileResponse(open(file, 'rb')) return response But all i kept getting was this error venv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'bool' object has no attribute 'get' I tried using boto3 to download the file viewa.py def download_file(request, id, order_id): obj = Product.objects.get(id=id) order = Order.objects.get(order_id=order_id) file = obj.file client = boto3.client('s3', aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')) bucket_name = os.environ.get('AWS_STORAGE_BUCKET_NAME') # url = 'https://' + settings.AWS_S3_CUSTOM_DOMAIN + '/media/' + f'{file.name}' url = client.generate_presigned_url('get_object', Params = {'Bucket': bucket_name, 'Key': file.name, }, ExpiresIn = 600, ) return HttpResponseRedirect(url) and i go this error <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>files/it_report_edited.docx</Key> <RequestId>JR7XHE6A8D7F2872</RequestId <HostId>LiQyKEyHsw/xerU2lJXTEZG+m3obOoUdlVH06d2vE+KHHWQVspOqOb9mN9JmJqBW7DVb8Gc63uZmuLSVqcvbYO7SJ3GNLbzlvNnVAxLOvls=</HostId> </Error> It looks to me that i'm not giving the correct key that's why it can't find it, is there a coorect way to handle this? i've tried everything -
Custom requests in Django REST Framework
I see that Django , in the REST Fremework module provide only CRUD requests made for object of a pre-defined model. Is there a way to create custom Rest API that is available in REST framework or swagger? Thank you. Until now I have a workaround to create a model like "request" or "task" , and manage objects of this model with CRUD requests in Swagger. -
Why makemessages generates *.html.py file from my *.html in the component (django_components) and base.html template?
I am creating my Django website and using django_components in the project. Now I'm thinking about creating a multilingual site: I created the necessary translate tags, added an i18n loader, created a locale folder in the root of the project. Now I am running the following command: $> python manage.py makemessages --locale=en Today, this command is working correctly. But yesterday, when I was doing it, an error about the inability to read the file dropped out /component/my_widget/my_widget.html.py. Initially, there was no such file at all, there was only my_widget.html and my_widget.py , but this file was created when executing the command. Inside this file there were different sets of letters X and B of different lengths, and in structure it resembled tags from a template my_widget.html . The most interesting thing is that in this file I did not use the translate tag at all. Next is an example of this strange .html.py file: BBBB BBBBBB XXXX XXXXXX XXXXXXX XXXXX XX XXXXXXX XXXXXX XX XXX XX XXXX XXX XXX XXXX XXXXXXXXXXXXXXX XXX BB BBBBBBBBBBBBBBBBB BB BBBBBBBBBBBB XXXX XXXX XX XXXX XXXXXXX XXX XX XXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXX XXXXXXXXXXXXXXXXXX XXXX XXXXXX XXX XXXXXXXXXX XXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXX XXXX X XXXXXXXXXXXXX … -
Why is simply adding "_id" suffix to a ForeignKey field automatically allowed in Django Serializer?
If I had the following model, I could set foo to foo_id by supplying foo_id = serializers.PrimaryKeyRelatedField(source='foo',queryset=Foo.objects.all() in the BarSerializer. from django.db import models class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) However, I can also set foo to foo_id as follows, without that specified line of code. from rest_framework import serializers class BarSerializer(serializers.ModelSerializer): # foo_id = serializers.PrimaryKeyRelatedField(source='foo',queryset=Foo.objects.all() class Meta: model = Bar fields = ['foo_id'] Why exactly can I provide 'foo_id' rather than 'foo' in the fields list here? One difference is that attempting to save a new Bar object with the BarSerializer results in django.db.utils.IntegrityError: (1048, "Column 'foo_id' cannot be null"), even when {foo_id: 1} is provided in the request data. -
in my API view i want to upload video in background using serializer , i want to return response and i dont want to wait until video upload complete
Here is my ApiView and i am uplaoding video to GCP bucket using serializer and video is filefield i am new to djngo DRF so can you please help me. how can use threading my case? class TestsApi(APIView): def post(self, request, *args, **kwargs): if request.method == "POST": if request.data.get('video') is not None: serializervideo = VideoSerializer(data=request.data) if(serializervideo.is_valid()): serializervideo.save() "Rest of the code" return Response(result) i want to upload video completely in background, i dont want to wait until video uploaded to my bucket i want to return response. Thank you in advance. -
Angular routes to localhost in k8s cluster
I have a problem with my Angular 15 Frontend app inside Minikube cluster. For deploying my app in Minikube, I add the k8s services URLs to environment files and Angular/Nginx sends me back to localhost - not to desired servcice URL. environment.development.ts export const environment = { production: false, serviceURL: 'http://backend.namespace.svc.cluster.local:8000', }; service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; import { User } from './user'; import { environment } from '../../environments/environment' @Injectable({ providedIn: 'root' }) export class MainService { baseUrl = environment.serviceURL+'/user/' httpHeaders = new HttpHeaders; constructor( private http: HttpClient, ) { } user(user:any): Observable<User> { return this.http.get<User>(this.baseUrl) } } With these settings Angular sends me back to localhost, where I get an 404 error where cannot find the 'http://localhost:4200/user/' When I try to curl service url ( curl http://backend.namespace.svc.cluster.local:8000 ) from frontend pod I get a correct response. Can someone advise me how to correctly connect angular frontend with django backend, please?