Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to get related table field data using select_related django
using Select_related i got the query what exactly i need. but i unable to figureout how to see anyfield or all field of related tables. prod = ProblemProductBind.objects.all().select_related('prod_id') >>> print(prod.query) SELECT "repair_problemproductbind"."id", "repair_problemproductbind"."prob_id_id", "repair_problemproductbind"."prod_id_id", "repair_problemproductbind"."A_price", "repair_problemproductbind"."B_price", "repair_problemproductbind"."A_buying_price", "repair_problemproductbind"."B_buying_price", "repair_problemproductbind"."A_ISmash_price", "repair_problemproductbind"."B_ISmash_price", "repair_problemproductbind"."isLCD", "repair_problemproductbind"."askQuote", "repair_problemproductbind"."time_stamp", "products_products"."id", "products_products"."pName", "products_products"."cat_id_id", "products_products"."subCat_id_id", "products_products"."type_id_id", "products_products"."brand_id_id", "products_products"."pImage", "products_products"."weRepair", "products_products"."weRecycle", "products_products"."time_stamp" FROM "repair_problemproductbind" INNER JOIN "products_products" ON ("repair_problemproductbind"."prod_id_id" = "products_products"."id") -
How to reorder the fields when we have two forms of two models in Django?
How can I reorder the fields in the form of my Django models ? I have two models : Student inherited from the User class inherited from an AbstractBaseUser class. I want the student to register on my webpage having these fields in this order : firstname ; lastname ; address ; email ; password. But Firstname and Lastname are in the User class, address in the Student class, then email and password in the User class. How can I reorder them ? Here is my code : forms.py : class CreateUserForm(UserCreationForm): class Meta: model = CustomUser fields = ('firstname', 'lastname', 'email') class StudentForm(forms.Form): address = forms.CharField(max_length = 30) class Meta: model = Student fields = ['address'] models.py : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) firstname = models.CharField(max_length = 30, null = True) lastname = models.CharField(max_length = 30, null = True) class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) address = models.CharField(max_length = 60, null = True) register.html : <div> <form method="POST" action="{% url 'register' %}"> {% csrf_token %} {{ form.as_p}} {{student_form.as_p}} <button class="btn btn-secondary"> Je m'inscris </button> </form> </div> -
How to make custom filter based on user
I have an application which is being used globally at my company. It is used to track internal hardware inventory. Each product is associated with a category (for example a product could have a category of 'cable', or 'development kit', or 'PC peripheral'). Now, each category is associated with a location (for example 'Boston', 'Budapest', and so forth). I have extended the user model in django to allow for a location to be associated with each admin user. I want to create a dropdown list filter in the admin space for each user. The user should be able to filter by product categories, but only the categories with the same location as the user. models.py ##product model class dboinv_product(models.Model): pk_product_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False ) product_creation_time = models.DateTimeField( auto_now_add=True, null=True ) product_name = models.CharField( max_length=50, null=False ) product_description = models.CharField( max_length=500, null=True ) current_qty = models.IntegerField( null=False ) fk_location_name = models.ForeignKey( dboinv_location, verbose_name="Location name", default='Boston', on_delete=models.CASCADE, null=True, blank=True ) fk_product_category = models.ForeignKey( dboinv_product_category, verbose_name='Product category', on_delete=models.CASCADE, null=True, blank=True ) def __str__(self): return f"{self.product_name}, {self.fk_location_name}" class Meta: db_table = "dboinv_product" verbose_name = "Product" managed = True ##category model class dboinv_product_category(models.Model): pk_category_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False … -
Session variable (Django) in one route exists, and in other is None
Currently I'm working on a project where I'm using React as frontend and Django as backend. In react i created a login page, where I through axios send files to django, and in this route index i sent all the information from the login page, and define a session variable reqeuset.session['id']=150 in it. But when i call reqeust.session['id'] in a diffrent route, it says that it is type None. This is the code: @api_view(['POST']) def index(request): data=request.data.get('data') korisnik = Korisnik.objects.filter(korisnicko_ime=data.get('user'), if korisnik.exists(): korisnik_json=serializers.serialize('json',korisnik) request.session['id']=150 print(request.session['id']) # if not request.session.session_key: # request.session.create() return HttpResponse(korisnik_json) else: return HttpResponse(status=404) @api_view(['GET']) def korisnik(request,id): print(request.session.get('id')) korisnik=Korisnik.objects.filter(pk=id) korisnik_json=serializers.serialize('json',korisnik) return HttpResponse(korisnik_json) This is the output from python console Image Also note, I'm using django restframework. Did anyone, have this problem before, any help is appreciated. -
How to display items in a row of 4 across using django, html, and python
this is my code. I want the items to be displayed horizontally. I've tried changing the col-md-3 and still no luck <title>Document</title> </head> <body> <div class="container"> <div class="row"> {% for product in product_objects %} <div class="col-md-3"> <div class="card"> <img src="{{ product.image }}" class="card-img-top"> <div class="card-body"> <div class="card-title"> {{ product.title }} </div> <div class="card-text"> {{ product.price }} </div> </div> </div> </div> {% endfor %} </div> </div> </body> </html> -
How can i pass a Django form to Html Asynchronously with intial data
I am representing data in a table and taking input for new data using a form on the same webpage. In my table at the end column, there is an update button for each row. When I will click the button, I want the existing form will populate with the data of the row. I want to update the data of a selected row asynchronously. I did it quite well with regular Django. But when I tried to do it with ajax/jquery. I have encountered a problem passing the form with populated data to HTML/script(Django view to frontend). I have added few lines of code below. Here is my Django view, def update_view(request,pk): p = People.objects.get(pk=pk) if request.method == 'POST': form = RecordUpdateForm(request.POST,instance=p) if form.is_valid(): form.save() else: form = RecordUpdateForm(instance=p) return !!! here is the url path, path('<int:pk>/update_view',views.update_view,name="update-view"), -
Cannot Debug Django using pdb
I am trying to add a breakpoint() to a particular line in a Django code which is running on an ec2 instance. I have tried ipdb, pdb tried import pdb;set_trace() it quits giving a BdbQuit error. tried simply adding breakpoint This simply gets ignored None of them stop the code. If I run the code like this python -m pdb manage.py runserver , it immediately drops into pdb and fails after executing 2 lines. How exactly should I use pdb in Django correctly? Old answers don't work. -
Filtering parent/child using NestedTabularInline in Django
Stuck in getting conceptually my head around a Django/ORM problem for a few days. Searching online (stackoverflow) didn’t address my problem. Furthermore I’m quite new to Django and Python and trying to understand the concepts of abstract models, multitable inheritance and proxy models but I don’t think that’s the solution. Outline: I’ve a general description of a activity/method/task model which describes a general assembly instruction. See my Activity/Method/Task/TaskImage model. On a actual product I want to execute a plan, in which I concretize a series of activity steps, hence my PlanActivity and PlanMethod models. Moreover for each actual plan I want to assign a bill of materials to make the product (therefore the TaskBOM). For convenience I’m heavily using NestedTabularInline for both drag/drop and inline properties. My problem is a bit twofold: Any activity step can have only one single method (Q1) and the available method’s need to be filtered (Q2) on it’s parent (activity). The tasks need to be filtered on the same way based on it’s parent (method). I think/hope my model is sane (thus no need for abstract models, multitable inheritance and proxy models) and I believe I need to use get_queryset or formfield_for_foreignkey functions in some … -
How to Remove " Password Condtions text " in django crispy form
I have added Password and using django crispy form. But can anyone help me how to remove the Password conditions text? Is there any easy way to remove """" Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. Your password can’t be a commonly used password. Your password can’t be entirely numeric. New password confirmation* "" enter image description here this text -
Django Rest Registration (3rd party package) asking for signature to verify registration.. What signature?
I'm using 'django rest registration' and when I create a new user everything works fine. The issue is that the 'verify-registration' endpoint requires a user_id, timestamp and a signature and I have no idea what timestamp and signature I'm supposed to post to the endpoint. The documentation is not really giving me any clues. Can anyone tell me what exact signature this 'verify-registration' endpoint is asking to have posted to it please? Here's the piece from the docs: and then it should perform AJAX request to https://backend-host/api/v1/accounts/verify-registration/ via HTTP POST with following JSON payload: { "user_id": "<user id>", "timestamp": "<timestamp>", "signature": "<signature>" } -
ValueError when i try to visit the dashbord of my app (( Cannot query "adivaumar@domain.com": Must be "FriendList" instance.))
Here is my dashboard view.py the error I think is coming from the user_data instance, I just couldn't think of a way to go about it. I have also search on stack overflow for solutions but they happens to be different issue but the same Value error. what could possibly be the problem with my code? def dashboard(request, session_username): user_videos = VideoPost.objects.filter( user__username=request.user.username).order_by('-id') user_data = User.objects.get_or_create( user=User.objects.get( username=request.user.username))[0] user_video_likes = 0 user_videos_views = 0 for video in user_videos: user_video_likes += video.likes.count() user_videos_views += video.video_views.count() params = {'videos': user_videos, 'user_data': user_data, 'total_likes':user_video_likes, 'total_views': user_videos_views} return render(request, 'dashboard.html', params) -
Django how to show correct pagination object to it's right user?
Right now my paginations is same for all user. Let you explain. Assume I listed 2 items per page if user Jhone have 4 items then he will see total 2 page number. see the picture: But User Mick haven't any items in his account but why he is seeing only page numbers? see the picture here is my code: views.py def ShowAuthorNOtifications(request): user = request.user notifications = filters.NotificationFilter( request.GET, queryset=Notifications.objects.all().order_by('-date') ).qs paginator = Paginator(notifications, 5) page = request.GET.get('page') try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) notification_user = Notifications.objects.filter(user=user).count() Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True) template_name ='blog/author_notifications.html' context = { 'notifications': notifications, 'notification_user':notification_user, 'page_obj':page_obj, } print("##############",context) return render(request,template_name,context) #html {% for notification in page_obj.object_list %} {%if user.id == notification.blog.author.id %} #my code {%endif%} {%endfor%} #my pagination code: <!-- Pagination--> <ul class="pagination justify-content-center mb-4"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page=1">First Page</a></li> <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">← Back</a></li> {% endif %} {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">Next Page →</a></li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item"><a class="page-link" href="#!">{{ i }}</a></li> {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %} <li class="page-item"><a … -
fetching data shows as undefined [duplicate]
import React, { Component } from 'react' export default class Main extends Component { constructor(props){ super(props) this.state = { name: 'NA', author: 'NA', } this.getBooks() } getBooks() { fetch('http://127.0.0.1:8000/api/get-books') .then((response) => { return response.json() }) .then((data) => { console.log(data) this.setState({ name: data.name, author: data.author, }) }) } render() { return ( <div> Name: {this.state.name} <br></br> Author: {this.state.author} </div> ) } } When I console.log(data) it logs: Object { id: 1, name: "book1", author: "Author1", passcode: "123" }, Object { id: 2, name: "book2", author: "Author2", passcode: "321" }, but for some reason data.name is undefined... how can i fix this? -
DRF exception 'NotAuthenticated' raising 500 Internal Server Error in place of 401/403
I have a Django middleware where I verify a firebase IDToken. from rest_framework import exceptions def process_request(request): ... try: decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] except: raise exceptions.NotAuthenticated(detail='not authenticated') When the verification fails, auth raises an exception, which is caught by the try except block. But instead of raising 401/403 error, 500 Internal Server Error is raised by NotAuthenticated. Is it because of some working of DRF Exceptions that this is happening ? -
Creating Files dynamically with django
i m have 2 models Uploades and File one for an image and one for the OCR result of the image, so whenever i upload an image a file with the result is generated, when working on the admin panel and with DRF api root it works fine but when i try Postman i get 500 sever error and the image is submitted by no file is created, i don't really know what the reason is so i would appreciate some help. These are my models class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=100,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) this part is to create the file super(Uploads, self).save(*args, **kwargs) if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.txt') )) The Create_Pdf function is simply running pytesseract this is my File model: class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) label=models.CharField(max_length=100, default='none') title=models.CharField(max_length=200,default='test') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) -
How to calculate the amount with property price and get remaining balance in Django?
info I am trying to create a monthly installment app using Django. I don't know how I could calculate Property' price with amount. I want to calculate the property price with the Payment amount and get the remaining price and save it to database. Customer has multiple payments so every month i get new payment from single customer and compare with remaining amount and get new remaining amount. i don't know how can i do that? models.py class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) remaining = models.IntegerField(default=0) -
ModuleNotFoundError("'kafka' is not a valid name. Did you mean one of aiokafka, kafka?")
I am using Celery and Kafka to run some jobs in order to push data to Kafka. I also use Faust to connect the workers. But unfortunately, I got an error after running faust -A project.streams.app worker -l info in order to run the pipeline. I wonder if anyone can help me. /home/admin/.local/lib/python3.6/site-packages/faust/fixups/django.py:71: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn(WARN_DEBUG_ENABLED) Command raised exception: ModuleNotFoundError("'kafka' is not a valid name. Did you mean one of aiokafka, kafka?",) File "/home/admin/.local/lib/python3.6/site-packages/mode/worker.py", line 67, in exiting yield File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/base.py", line 528, in _inner cmd() File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/base.py", line 611, in __call__ self.run_using_worker(*args, **kwargs) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/base.py", line 620, in run_using_worker self.on_worker_created(worker) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/worker.py", line 57, in on_worker_created self.say(self.banner(worker)) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/worker.py", line 97, in banner self._banner_data(worker)) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/worker.py", line 127, in _banner_data (' transport', app.transport.driver_version), File "/home/admin/.local/lib/python3.6/site-packages/faust/app/base.py", line 1831, in transport self._transport = self._new_transport() File "/home/admin/.local/lib/python3.6/site-packages/faust/app/base.py", line 1686, in _new_transport return transport.by_url(self.conf.broker_consumer[0])( File "/home/admin/.local/lib/python3.6/site-packages/mode/utils/imports.py", line 101, in by_url return self.by_name(URL(url).scheme) File "/home/admin/.local/lib/python3.6/site-packages/mode/utils/imports.py", line 115, in by_name f'{name!r} is not a valid name. {alt}') from exc -
My problem is Invalid password format or unknown hashing algorithm
I try to do sign up and login form using Modelform. I have form to sign up user but it can't set password becouse in admin panel in user lap in password field I have "Invalid password format or unknown hashing algorithm." Can anyone help me? My form succesful submit form. Please help me solve this problem. view def sign_up(request): context ={} who ={"teacher": Teacher, "student": Student} form = UserSignUpForm(request.POST or None) if request.method == "POST": if form.is_valid() and request.POST.get("who"): user = form.save() person = who[request.POST.get("who")] person(user=user).save() return render(request, 'school/index.html') context['form'] = form return render(request, 'registration/sign_up.html', context) form class UserSignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserSignUpForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], label="", required=True, widget=forms.RadioSelect( attrs={'style':'max-width: 20em; ', 'autocomplete':'off', }) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={}), 'first_name': forms.TextInput(attrs={}), 'last_name': forms.TextInput(attrs={}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm password does not … -
Why is this Django view failing to run a Powershell script via subprocess.call?
The following tests.py works correctly and executes a Powershell script via subprocess.call: import subprocess subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./testers.ps1\";", "&Foo(10)"]) Trying to execute the same call from within a Django/REST view, fails to do so: import subprocess from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view @api_view(['POST']) def bar(request): if request.method == 'POST': subprocess.call([f"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./testers.ps1\";", "&Foo({request.data})"]) return Response(request.data, status=status.HTTP_201_CREATED) else: return Response(request.errors, status=status.HTTP_400_BAD_REQUEST) Error: [09/Jul/2021 08:31:52] "POST /profile-eraser/ HTTP/1.1" 201 5646 . : The term './testers.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:3 + . "./testers.ps1"; &Foo({request.data}) + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (./testers.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException & : The term 'Foo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:21 + . "./testers.ps1"; &Foo({request.data}) + ~~~~~ + CategoryInfo : ObjectNotFound: (hello:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS Script: Function Foo($intIN) { … -
how to filter images from a list of files in django-rest-framework
I have a Django rest server which server a list of files to react frontend. I would like to know if I can filter those files by images and display only images to my react frontend. I have searched a lot but cannot find anything useful. Please help me. Thank you in advance. class FileListView(generics.ListAPIView): serializer_class = ListFileSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): owner = self.request.user.username return File_Uploader.objects.filter(owner=owner) -
Exception Type: TemplateDoesNotExist login templete doesn't exist
TemplateDoesNotExist at /login/ login.html Request Method: GET Request URL: http://localhost:8000/login/ Django Version: 3.2.5 Exception Type: TemplateDoesNotExist Exception Value: login.html Exception Location: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['C:\Users\LISHITHA\virl\logp', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Sat, 10 Jul 2021 18:20:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\LISHITHA\virl\logp\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\login.html (Source does not exist) """"' from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), path('register/',views.register,name='register'), path('login/',views.login,name='login'), ] from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.urls import path def home(request): return HttpResponse('welcome home') def register(request): return render(request,'register.html') def login(request): return render(request,'login.html') 'DIRS': [os.path.join(BASE_DIR, 'templates')], and declared login templetes in that empty pasted starter templete """ http://localhost:8000/login/# -
How to display JavaScript alert in Django?
I am creating a simple website in Django. I have a form, and when it is submitted, the user is redirected to a new page. I want to display a javascript alert (example bellow) on the new page when the form is submited. I have looked and gotten the django messages way to work, but I do not want to use messages, I want a javascript alert. Can someone please help me? Javascript Alert -
How to configure Scrapy, ScrapyD, Django and Docker together?
I am building a scraping backend based on the libs mentioned in the title. I want Django to receive a URL, schedule scraping using ScrapyD, handle scraping by Scrapy (it persists the data into DB). I am currently using Docker and it looks this way: version: '3.1' volumes: init-db: data-db: services: mongo: image: mongo restart: always environment: MONGO_INITDB_ROOT_USERNAME: name MONGO_INITDB_ROOT_PASSWORD: password ports: - 27021:27021 command: mongod --quiet --logpath /dev/null scrapyd: image: zwilson/scrapyd build: . ports: - 6800:6800 volumes: - ./data:/home/scrapyd/data - ./scrapyd.conf:/usr/src/app/scrapyd.conf entrypoint: scrapyd splash: image: scrapinghub/splash ports: - "8050:8050" restart: always redis: image: "redis:alpine" ports: - "6379:6379" web: build: . restart: unless-stopped command: > bash -c "pip install -r requirements.txt && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8001" tty: true volumes: - .:/usr/src/app ports: - 8001:8001 depends_on: - mongo And I initialize the scrapyd connection this way: from scrapyd_api import ScrapydAPI scrapyd = ScrapydAPI('http://0.0.0.0:6800') Now inside my views when I try use the scrapyd service through: crapyd.schedule(project="default", spider="BookSpider", url=url) I get the following error: web_1 | DEBUG: Waiter future is already done <Future cancelled> web_1 | ERROR: Exception inside application: HTTPConnectionPool(host='0.0.0.0', port=6800): Max retries exceeded with url: /schedule.json (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f330c1c42e0>: … -
Django REST get nested data in request
I'm new usigng django and drf . I have an issue with request a model with a foreig key. I have this 3 models : class Order(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") fecha = models.DateTimeField(auto_now=True) def __str__(self): return f"Orden : {self.id}" class Product(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class OrderDetail(models.Model): order = models.ForeignKey(Order, related_name="orders", on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name="products", on_delete=models.CASCADE) I want to retrieve all order data with its products from detail: Example : { id : 1 , user : 1 , fecha : 01/02/2021, products : [ { id : 1 , name : "product1" } { id : 2 , name : "prodcut2" } } My serializers are : class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "name"] class OrderDetailSerializer(serializers.ModelSerializer): class Meta: model = OrderDetail fields = ['order' ,'product'] class OrderSerializer(serializers.ModelSerializer): products = OrderDetailSerializer(many=True) class Meta: model = Order fields = ['id', 'user', 'fecha' ,'products'] But I'm getting this error : AttributeError: Got AttributeError when attempting to get a value for field 'products' on serializer 'OrderSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'Order' instance. Original exception text … -
DRY-rest-permissions somehow does not check my object permissions except global permissions
I have recently started implementing dry-rest-permissions, but I can't seem to get it to check the has_object_permissions, it appears that only the global permissions work for me. I am fairly new to implementing permissions and this is my first time implementing DRY-rest-permissions and have only recently started coding in django rest framework, so apologies for the lack of knowledge in advance. At the moment I am trying to delete a company object by simply having a user call a URL, that URL then gets the current user's active_company and then deletes it only if the current user is the active_company's company_owner. But what I discovered, is that I somehow can't get has_object_permissions to work anywhere? I have noticed that if I delete has_write_permission(request), and hit the company_delete URL it gives me the following error: '<class 'company.models.Company'>' does not have 'has_write_permission' or 'has_company_delete_permission' defined. This means that it doesn't even look for the has_object_company_delete_permission. Meaning it only checks the global permissions rather than any of the object permissions, what am I possibly doing wrong here? My model: class Company(models.Model): company_name = models.CharField(max_length=100) company_orders = models.IntegerField(blank=True, null=True) company_icon = models.ImageField( upload_to='media/company_icon', blank=True) company_owner = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) company_employees = models.ManyToManyField( …