Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgres asking unknown password
installing PostgreSQL for my Django Project. (vent) my_name@Name-MBP dir % createuser my_user createuser: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL: password authentication failed for user "my_name" Problem: I do not specify any password for user "my_name" and don't even create such user. HELP PLEASE!!! -
How to encrypt responses in DRF?
I want to encrypt my DRF project APIs responses Is there a way to encrypt large responses so that I only have access to the data on the front end side? I want to encrypt all responses. -
How can i split the value of a dropdown list option and pass it in two different input fields
How can i split the value of a dropdown list option and pass it in two different input fields scripts <script> function getsciname() { ("#selectsci").change(function() { var sciname = (this).val().split(','); ("#sid").val(sciname[0]); ("#sname").val(sciname[1]); }}; </script> (dropdown) select option code <select id="scinameid" class="scinameclass" onchange="getsciname()"> <option disabled="true" selected>-- Scientific name --</option> {% for getData in TaxonmyDistributionInsert %} <option value={{getData.id}},{{getData.ScientificName}}>{{getData.id}} - {{getData.ScientificName}}</option> {% endfor %} </select> input box code <input type="text" style="font-size: 16px" placeholder="Shrimp Prawn ID" name="ShrimpPrawnID" id="sid" /> <input type="text" style="font-size: 16px" placeholder="Scientific Name" name="ScientificName" id="sname" /> -
Check for a certain condition before processing each view in Django
I'm building a multi-tenant Django app, where I need to check for a certain condition before processing each view, similar to the login_required decorator which checks if user is authenticated or not. And if the condition is not true, stop processing the view and send the user to the login page. How can I implement this for each view in my app My condition - def index_view(request): domain1 = Domain.objects.get(tenant=request.user.client_set.first()) domain2 = request.META["HTTP_HOST"].split(":")[0] // Condition if str(domain1) != domain2: return redirect("accounts:login") return render(request, "dashboard/index.html") -
How can i run a python script in django
So a python script like Sherlock on Git hub, which sources usernames. Can that be run by clicking a button on a HTML page in a Django project and return a CSV file. How would this be done ? -
Stock quantity update when and order is placed in Django app
I have a product and order create models where I'd like to update the quantity of the product when and order is placed for that product. Using a ForeignKey, I am able to select the product but so far I'm definitely missing something as nothing i have tried seems to work, please take a look at my code below and assist. Thank you in advance Models.py #Product Model class Product(models.Model): SKU = models.CharField(max_length=30, unique=False,default='input SKU') Category = models.CharField(max_length=200,default='Input Category') Name = models.CharField(max_length=250,unique=False, default='Input product name') Platform = models.CharField(max_length=50, default='platform') Price = models.PositiveIntegerField(default='price') Discount = models.PositiveIntegerField(default='discount') Prod_Qty = models.PositiveIntegerField(unique=False, default=0) Date = models.CharField(max_length=30, default='Char field') Cost = models.PositiveIntegerField() created_date = models.DateField(auto_now_add=True) def __str__(self): return self.Name class Order(models.Model): STATUS_CHOICE = ( ('pending', 'Pending'), ('decline', 'Decline'), ('approved', 'Approved'), ('processing', 'Processing'), ('complete', 'Complete'), ('bulk', 'Bulk'), ) SALE_CHOICE = ( ('platform1', 'platform1'), ('platform2','platform2') ) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False) sale_type = models.CharField(max_length=50, choices=SALE_CHOICE, null=True) cost_goods_sold = models.PositiveIntegerField(default=6) shipping_fee = models.PositiveIntegerField(null=False) shipping_cost = models.PositiveIntegerField(default=0) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE, null=True) manifest = models.ForeignKey(Manifest, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS_CHOICE) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.product.Name Views.py # Product views @login_required(login_url='login') def create_product(request): forms = ProductForm() context = {"form": forms} if request.method … -
1v1 Game Django using Javascript / Html
I'm having for the moment a memory card game using JS & html on Django I would know where do I have to search to make it like a 1v1 game. People would be able to create a 1v1 room (lobby) and then play this memory card game If you guys have any clues, will appreciate. Bru -
CS50w commerce project: 'The bid must be as large as the starting bid, and must be greater than any other bids that have been placed (if any)'?
So I have solved this particular problem, but there is something that I noticed and didn't get why was it behaving the way it did. So the below code worked the way I wanted it to work: def bid_placed(request,listing_id): if request.method == "POST": recent_bid = Bid( Bid_amount = request.POST["bid_amount"], listing = Listing.objects.get(pk=listing_id) ) listing = Listing.objects.get(pk=listing_id) starting_Bid = listing.Starting_Bid recent_bid_int = int(recent_bid.Bid_amount) if recent_bid_int > starting_Bid: listing.Starting_Bid = recent_bid_int listing.save() return HttpResponse("Bid SUCCESSFULLY Placed") else: return HttpResponse("Bid CANNOT be placed") But the below code is NOT working as desired, even though the starting_Bid variable has been declared: def bid_placed(request,listing_id): if request.method == "POST": recent_bid = Bid( Bid_amount = request.POST["bid_amount"], listing = Listing.objects.get(pk=listing_id) ) listing = Listing.objects.get(pk=listing_id) starting_Bid = listing.Starting_Bid recent_bid_int = int(recent_bid.Bid_amount) if recent_bid_int > starting_Bid: starting_Bid = recent_bid_int listing.save() return HttpResponse("Bid SUCCESSFULLY Placed") else: return HttpResponse("Bid CANNOT be placed") ``` Can someone please guide, why it might be the case.? Thanking you in advance.! -
Why I am getting the NGINX welcome page instead of my Django application
I have deployed my Django Application on a VPS server. I have configured NGINX and uWSGI server. Here is my Nginx configuration # the upstream component nginx needs to connect to upstream django { server unix:///root/PIDC/ProjetAgricole/ProjetAgricole.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name my_public_IP_address; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/PIDC/ProjetAgricole/media; } location /static { alias /root/PIDC/ProjetAgricole/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/PIDC/ProjetAgricole/uwsgi_params; } } Here is my mysite_uwsgi.ini file # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /root/PIDC/ProjetAgricole # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /root/my_project/venv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe … -
How to get data from a running task in Python(Django)
I have a script to compare and move my files around, which is to be called by cmp_object = my_cmp.Compare('/mnt/f/somedir', '/mnt/f/newdir') cmp_object.main() and the Compare class is defined as class Compare: def __init__(self, path1, path2): self.path1 = path1 self.path2 = path2 self.totalFileNumber = getTotalFileNumber(path1) self.totalFileSize = getTotalFileSize(path1) self.progress = 0 self.progressPercent = 0 self.status = 'Not started' self.started = False self.finished = False def start(self): self.status = 'Started' self.started = True self.finished = False def update(self, index): self.progress = index self.progressPercent = round( self.progress / self.totalFileNumber * 100, 2) self.status = f'{self.progressPercent}%' if self.progressPercent == 100: self.status = 'Finished' self.finished = True def getStatus(self): return self.status def getProgress(self): return self.progressPercent def getTotalFileNumber(self): return self.totalFileNumber def getTotalFileSize(self): return self.totalFileSize def isStarted(self): return self.started def isFinished(self): return self.finished def main(self): self.start() for index, file in enumerate(listAllFiles(self.path1)): compareFiles(file, self.path2 + file[len(self.path1):]) self.update(index) self.update(self.totalFileNumber) self.finished = True , which has functions to get and set some states like progress, status and finish. I am running this on Django backend, where I would be retrieving information from the backend by setting an interval... I am using cache to set and get the states across different views, but I'm not sure how can I keep on … -
Django Terraform digitalOcean re-create environment in new droplet
I have saas based Django app, I want, when a customer asks me to use my software, then i will auto provision new droplet and auto-deploy the app there, and the info should be saved in my database, like ip, customer name, database info etc. This is my terraform script and it is working very well coz, the database is now running on terraform { required_providers { digitalocean = { source = "digitalocean/digitalocean" version = "~> 2.0" } } } provider "digitalocean" { token = "dop_v1_60f33a1<MyToken>a363d033" } resource "digitalocean_droplet" "web" { image = "ubuntu-18-04-x64" name = "web-1" region = "nyc3" size = "s-1vcpu-1gb" ssh_keys = ["93:<The SSH finger print>::01"] connection { host = self.ipv4_address user = "root" type = "ssh" private_key = file("/home/py/.ssh/id_rsa") # it works timeout = "2m" } provisioner "remote-exec" { inline = [ "export PATH=$PATH:/usr/bin", # install docker-compse # install docker # clone my github repo "docker-compose up --build -d" ] } } I want, when i run the commands, it should be create new droplet, new database instance and connect the database with my django .env file. Everything should be auto created. Can anyone please help me how can I do it? or my approach is … -
django.db.utils.OperationalError: sequence must have same owner as table it is linked to
I am trying to update the USER auth model in Django in the middle of a project. I am also trying to learn a bit more, so I chose to do the "hard way" and switch out the standard auth model with a modified AbstractUserModel than doing the 'profile' 1-to-1 method often suggested. I feel I am quite close, as I am trying to apply the final migration with walkthrough suggestions from here and here. There is some inclination that Django runs the ALTER SEQUENCE OWNED BY with a different (auth user maybe?) user than the database user (who you are logged in as maybe?). I have confirmed that the OWNER of the tables and sequences are owned by all the same OWNER, but am still getting the migrate error. Thank you all in advance :) When trying to run ./manage.py migrate --verbosity 3, I get the following error: IN DEV XXXXXXX Operations to perform: Apply all migrations: account, … trucks Running pre-migrate handlers for application auth … Running pre-migrate handlers for application account Running pre-migrate handlers for application trucks Running migrations: Applying accounts.0004_auto_20220424_0024...Traceback (most recent call last): File "/Users/me/.virtualenvs/virtualENV/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ObjectNotInPrerequisiteState: sequence must … -
Incorrect padding when attempting to update profile picture
My project is built on React and Django. I would like to enable users to update profile information. Noticed that I was initially getting a 304 error when it specifically comes to updating the profile picture. and realized that this had something to do with Django requiring multipart form data. I then tried to upload the profile picture using a base64 encoding string, but now getting the error Incorrect padding Here is my serializers.py: #upload profile picture using base64 encoding string instead of raw file (not supported by default) class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid #check if this is base64 string if isinstance(data, six.string_types): #check if the base64 is in the data format if 'data:' in data and ';base64' in data: header,data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') #Generate file name: file_name = str(uuid.uuid4())[:12] #Get the file name extension file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = … -
Reverse for 'list-events' not found
Im currently following a Django tutorial to learn views and URLs. I have watched the tutorial over and over and cant see what I am doing wrong. I receive the error: Exception Value: Reverse for 'list-events' not found. 'list-events' is not a valid view function or pattern name. Views.py from django.shortcuts import render, redirect import calendar from calendar import HTMLCalendar from datetime import datetime from .models import Event, Venue from .forms import VenueForm, EventForm from django.http import HttpResponseRedirect # Create your views here. # all events is listed in the urls.py hence why the function is named all_events def update_event(request, event_id): event = Event.objects.get(pk=event_id) form = EventForm(request.POST, instance=event) if form.is_valid(): form.save() return redirect('list-events') return render(request, 'events/update_event.html', {'event': event, 'form':form}) def add_event(request): submitted = False if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/add_event?submitted=True') else: form = EventForm if 'submitted' in request.GET: submitted = True return render(request, 'events/add_event.html', {'form': form, 'submitted': submitted}) def update_venue(request, venue_id): venue = Venue.objects.get(pk=venue_id) form = VenueForm(request.POST, instance=venue) if form.is_valid(): form.save() return redirect('list-venues') return render(request, 'events/update_venue.html', {'venue': venue, 'form': form}) def search_venues(request): if request.method == "POST": searched = request.POST['searched'] venues = Venue.objects.filter(name__contains=searched) return render(request, 'events/search_venues.html', {'searched': searched, 'venues': venues}) else: return render(request, 'events/search_venues.html', {}) … -
Test of Django ProfileListView fails with ValueError: Cannot assign "<SimpleLazyObject:....>": "Profile.user" must be a "User" instance
I am a Django beginner and a SOF newbie, sorry if this question sounds a silly to some. I am struggling with my integration tests. In my app I have a one-to-one User/Profile relationship. I have a list view to show registered users' profile data: class ProfileListView(views.ListView, LoginRequiredMixin): model = Profile template_name = 'registration/profile_list.html' paginate_by = 8 def get_context_data(self, *, object_list=None, **kwargs): context = super(ProfileListView, self).get_context_data() # superuser raises DoesNotExist at /accounts/profiles/ as they are created with createsuperuser in manage.py # hence are not assigned a profile automatically => create profile for them here try: context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) except ObjectDoesNotExist: Profile.objects.create(user=self.request.user) context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) # get all other users' profiles apart from staff and current user regular_users = User.objects \ .filter(is_superuser=False, is_staff=False, is_active=True) \ .exclude(pk=self.request.user.pk) context['non_staff_active_profiles'] = Profile.objects.filter(user__in=regular_users) return context I want to test the get_context_data() method to ensure it returns: correct logged in user correct queryset of non-staff profiles My test breaks as soon as I try something like: response = self.client.get('/accounts/profiles/') I understand I need to pass user/profile data to the client but I could not figure out how to do that. It looks like it fails because of context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) and I have no idea why. … -
Embed Plotly in html with responsive behavior: can I change legend position based on screen width?
I am using Plotly to embed a plot on an HTML page. My website is responsive, but I am not satisfied with the legend of the plot that I have embedded. Here you can see two screenshots: on the left, we see the plot on a widescreen, and on the right with a narrow one. vs As shown in the figure, the plot looks good on the widescreen (left). However, when the screen is narrow (right), the legend takes too much space and the plot is shrunk. Moving the legend below when the screen is small would solve the issue (as depicted with the red drawing). Is it possible to embed such a responsive behavior in Plotly when adding the legend? Thanks in advance! :) -
How I can use a django variable in if statement of django template into a javascript string variable
I want to add a div to my page using a javascript variable. This div must take a class right or left ,but my if condition doesn't work in this variable, And it works if I try it without javascript. This is my view : def chat(request,sender_id,receiver_id): if request.user.is_authenticated: if request.user.profile == 'C' or request.user.profile == 'A': user = User.objects.filter(id=request.user.id).get() receiver_user = User.objects.filter(id=receiver_id).get() if request.user.profile == 'A': chat = Chat.objects.filter(Q(sender_id=sender_id) | Q(receiver_id=sender_id)).all() elif request.user.profile == 'C': chat = Chat.objects.filter(Q(sender_id=sender_id,receiver_id=receiver_id) | Q(sender_id=receiver_id,receiver_id=sender_id)) context = { 'user': user, 'chat': chat, 'receiver_user': receiver_user, } return render(request,'chat/chat.html',context) return render(request, 'Login/logout.html') And this is my javascript : $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'getMessages' request.user.id receiver_user.id %}", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.chat) { var temp='<div class="msg-box {% if request.user.id == chat.sender_id %} right {% else %} left {% endif %}">\ <div class="details">\ <p class="msg">'+response.chat[key].message+'</p>\ <p class="date">'+response.chat[key].msg_time+'</p></div></div>'; $("#display").append(temp); } }, error: function(response){ console.log('An error occured') } }); },100); }); -
Django Polymorphic Serializer Object of type ListSerializer is not JSON serializable
I'm working on a django view to return a nested list inside another list of records, to do this I use a nested serializer. The thing is that nested serializer is a Polymorphic serializer that decomposes to many other serializers. When I'm using a normal serializer instead of the polymorphic one the approach works fine, but when I use a polymorphic serializer it gives the following error Object of type ListSerializer is not JSON serializable Here is how I'm calling the first serializer in my view return Response(serializers.FormEntriesHistorySerializer(forms,many=True,context={'device_id': kwargs.get('device_id')}).data) And this is the parent serializer class FormEntrySerializer(serializers.ModelSerializer): #form = FormSerializer(read_only=True) response_set = ResponsePolymorphicSerializer(many=True,read_only=True) class Meta: model = models.FormEntry fields = '__all__' def to_representation(self, instance): response = super().to_representation(instance) response["response_set"] = sorted(response["response_set"], key=lambda x: x["id"],reverse=True) return response def validate(self, attrs): print("Validation in on going") return attrs The error is triggered by the ResponsePolymorphicSerializer, as I said this approach works fine if I use a normal serializer instead. But in this case I need to do it with the polymorphic. Here's my polymorphic serializer's definition class ResponsePolymorphicSerializer(PolymorphicSerializer): model_serializer_mapping = { models.FreeTextResponse: FreeTextResponseSerializer, models.ShortTextResponse: ShortTextResponseSerializer, I'd gladly appreciate some guidance on this. Thanks. -
How to use memray with Gunicorn and Django?
I have a project with Django and I did a multiread with Gunicorn. but my project has a memory leak. I want to monitor memory with "memray" but I don't know how to use "memray". -
Form not submitting to database in Django
I have created a form in Django and the information from this form must be registered in the database. But I have a problem. The information is not recorded in the database. I guess it's the JavaScript file that's blocking it. I remove the JavaScript file and the form works fine. But I don't want to remove the JavaScript file. How can I solve this problem? views.py def index(request): if request.POST: fname_lname = request.POST.get('name') number = request.POST.get('number') newForm = models.Form(fname_lname=fname_lname, number=number) newForm.save() return render(request, 'index.html') return render(request, 'index.html') model.py class Form(models.Model): fname_lname = models.CharField(max_length=50) number = models.IntegerField(max_length=15) send_date = models.DateTimeField(auto_now_add=True) index.html <div class="formbg"> <div class="formcolor"> <form class="forminput" method="post" action="/"> {% csrf_token %} <div class="label"> <label class="labels">Ad və Soyadınız <span>:vacibdir</span></label> <div class="input"> <input name="name" required type="text" class="inputs" /> </div> </div> <div class="label"> <label class="labels">Telefon nömrəniz <span>:vacibdir</span></label> <div class="input"> <input name="number" required type="number" class="inputs" /> </div> </div> <div class="formbut"> <button type="submit" class="btnsubmit">Göndər</button> </div> </form> </div> </div> </div> </div> <!-- SECTION19 --> <!-- SECTION20 --> <div class="security"> <i class="fa-solid fa-lock"></i> <p>SİZİN MƏLUMATLAR YADDAŞDA QALMIR VƏ 3-CÜ TƏRƏFƏ GÖSTƏRİLMİR</p> </div> <!-- SECTION20 --> <!-- SECTION21 --> <div class="finish"> <p>Məxfilik siyasəti</p> <h1>* - Q7 GOLD KİŞİ GÜCÜNÜN FORMULU</h1> </div> <!-- SECTION21 --> <script src="{% static … -
Django not redirecting to the web page
I am creating a messaging application in django with a built-in DLP system. I want to redirect to a web page when a sensitive word is detected in the message. But the webpage is not being redirected to. It is showing in the terminal but not on the front-end. In consumers.py async def chat_message(self, event): message = event['message'] username = event['username'] if (re.findall("yes|Yes", message)): response = await requests.get('http://127.0.0.1:8000/dlp/') print('message') else: await self.send(text_data=json.dumps({ 'message': message, 'username': username })) The output in the terminal WebSocket CONNECT /ws/2/ [127.0.0.1:32840] HTTP GET /dlp/ 200 [0.00, 127.0.0.1:32842] message -
Django doesn't create session cookie in cross-site json request
I want to make cross-site JavaScript call from third-party domain (in this case my desktop/localhost server) to my remote Django server hosted on my_domain.com/ and calling REST WS exposed on my_domain.com/msg/my_service with using session/cookies for storing session state. But when I call this service (hosted on remote Django server) from my desktop browser or localhost Django server (JS is in index.html), Django doesn't create session cookie and on remote server are doesn't store session state. But when i call this service from Postman or from same localhost JS to localhost instance of same Django service it works and session is created. My JS script in index.html which make call to WS send_message: fetch('http://my_domain.com/ws/my_service', { method:"POST", credentials: 'include', body:JSON.stringify(data) }) .then(res => res.json()) .then(json => { showResponse(json.message); }) When I run this script from my desktop browser or my localhost server it runs correctly with cookies and sessions parameters. Django my_service implementation view @csrf_exempt def my_service(request): if request.method == "POST": message_bstream= request.body request.session.set_expiry(0) message= json.loads(message_bstream) out,sta=state_machine_response(message["message"],int(request.session["state"])) request.session["state"] =sta respo={"message":out} response = HttpResponse(json.dumps(respo), content_type="application/json") response.set_cookie(key='name', value='my_value', samesite='None', secure=True) #return JsonResponse(respo, safe=False, status=200) return response else: return HttpResponseNotFound ("Sorry this methode is not allowed") Or I try generate response like return JsonResponse(respo, safe=False, … -
Django Framework: Reading Data from MSSQL-Database directly? Or import the dataset to sqlite3?
I would like to build an admin dashboard in Django framework. So far I have only worked with sqlite3 databases in Django. However, the admin dashboard should read statistics from an MSSQL database and display them accordingly. (Sales figures as a graph, other sales in a table, etc.) The turnover figures are very extensive. There are several thousand entries per month and the client would like to be able to filter by any date period. Only data from the MSSQL database should be read. Writing or updating the data is not desired. So far this is no problem, but I wonder what is the better solution to implement the project. Should I connect the MSSQL database directly to Django or should I read the MSSQL database in certain intervals and cache the "results" in a sqlite3 database? Caching seems to me to be the nicer solution, as we don't need real-time data and the performance of the MSSQL server might not suffer as a result. But I would have to build an additional connector to transfer the data from MSSQL to sqlite3. How would you approach such a project? Short version: I´d like to display data in django-framework App, should … -
How to nest models fields under another key for serializer
I have this type of Post model class Post(models.model): id = models.UUIDField(primary_key=True, default=uuid4) user = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE) tags = models.ManyToManyField("Tags", blank=True, related_name="posts") title = models.CharField(max_length=200) body = RichTextField(blank=True, null=True) post_views = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, verbose_name=("created_at")) in the serializer, I want to nest title, body, created_at under another key named article serializers.py class ArticleSerializer(serializers.ModelSerializer): title = serializers.CharField() content = serializers.CharField(source="body") created_at = serializers.CharField() class Meta: model = Post fields = ("title", "body", "created_at") class PostSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(slug_field="email", read_only=True) article = ArticleSerializer(required=True) tags = TagSerializer(many=True, required=False) post_views = serializers.IntegerField(read_only=True) def to_representation(self, instance): data = super().to_representation(instance) cat = data.pop("category") title = data.pop("title") content = data.pop("body") created_at = data.pop("created_at") data["categories"] = cat data["article"] = {"title": title, "content": content, "created_at": created_at} return data class Meta: model = Post fields = "__all__" views.py class ArticleView(APIView): def get_object(self, pk: int): try: if pk: return Post.objects.filter(pk=pk, draft=False) return Post.objects.filter(draft=False) except Post.DoesNotExist: raise Http404 def get(self, request: Request, pk=None): post = self.get_object(pk) serializer = PostSerializer(post, many=True) return Response(serializer.data) The error that I'm getting AttributeError: Got AttributeError when attempting to get a value for field `article` on serializer `PostSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. … -
" pip install django-deep-serializer" doesn't work
I keep trying to install django-deep-serializer but I keep on getting this error. I have uninstalled python and reinstalled it already. I currently have python 3.10.4 and pip is 22.0.4 Defaulting to user installation because normal site-packages is not writeable WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnWARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ ERROR: Could not find a version that satisfies the requirement django-deep-serializer (from versions: none) ERROR: No matching distribution found for django-deep-serializer