Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display saved dynamic images in Django
Hi Im trying to display this image that I am generating in my view file. This image is generated on the basis of a search algorithm. It is saved in this variable "mimg". I don't understand how to display in template. I have tried various methods but nothing is helping. im new to django and don't know how to resolve this issue def match(request): this_file=os.path.abspath(__file__) base_dir=os.path.dirname(this_file) entries = os.listdir('static_in_env/db_images/') entries2= os.listdir('media/images/') list_of_files = glob.glob('media/images/*') latest = max(list_of_files, key=os.path.getctime) img=Image.open(latest) r, g, b = img.split() len(r.histogram()) red=r.histogram() green=g.histogram() blue=b.histogram() mr=max(red) mg=max(green) mb=max(blue) nhr = [i/mr for i in red] nnhr = np.multiply(nhr, 255) nhg = [i/mg for i in green] nnhg = np.multiply(nhg, 255) nhb = [i/mb for i in blue] nnhb = np.multiply(nhb, 255) n=1 p=[fname.rsplit('_', 1)[0] for fname in entries] mylist = list(dict.fromkeys(p))[:-1] for i in range(0, len(mylist)): img1=mylist[i]+'_a.jpg' img2=mylist[i]+'_b.jpg' img3=mylist[i]+'_face.jpg' f1='static_in_env/db_images/'+img1 f2='static_in_env/db_images/'+img2 f3='static_in_env/db_images/'+img3 db_img = Image.open(f1) r1, g1, b1 = db_img.split() red1=r1.histogram() green1=g1.histogram() blue1=b1.histogram() db_img2 = Image.open(f2) r2, g2, b2 = db_img2.split() red2=r2.histogram() green2=g2.histogram() blue2=b2.histogram() db_img3 = Image.open(f3) shr = red1+red2 shg = green1+green2 shb = blue1+blue2 shr1=np.divide(shr, 2) shg1=np.divide(shg, 2) shb1=np.divide(shb, 2) smr=max(shr1) smg = max(shg1) smb = max(shb1) nhr1 = [i/smr for i in shr1] nnhr1 … -
How to Retrieve a specific value of a Tuple from Django database
So here I have a table named Product which contains Food name,Category,Price,Image,Dataset id column so i would like to retrieve the value of Dataset id only ,in Django I would like to put parse dataset_id into recommend function but it doesnt give value of 31 while i select Pizza so i tried just printing it and the output in my console is <django.db.models.query_utils.DeferredAttribute object at 0x03B11CE8> here is my code from views.py from .models import Product def cart(request): if request.user.is_authenticated: print(Product.dataset_id) res=recommend(item_id=31, num=3) customer = request.user.customer order , created = Order.objects.get_or_create(customer = customer , complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items print(res) Here is my code for Products in models.py class Product(models.Model): food_id = models.AutoField food_name = models.CharField(max_length=50, default="") cateory = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to='menu/images', default="") dataset_id = models.IntegerField(default = 0) -
Django sends it response to browser it gets this error: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am using Django Rest Framework as my backend and ReactJS as my frontend. My DRF files look like this settings.py ALLOWED_HOSTS=['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'ecom', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True backend/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('ecom.urls')), ] ecom/urls.py from django.urls import path from ecom import views urlpatterns = [ path('categories/',views.CategoryList.as_view(), name = 'categories'), path('categories/<int:pk>/',views.CategoryDetail.as_view(), name = 'categories_detail'), path('products/',views.ProductList.as_view(), name = 'products'), path('products/<int:pk>/',views.ProductDetail.as_view(), name = 'products_detail'), ] REACTJS App.js import React , {Fragment, useEffect, useState} from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({hits: []}); useEffect(async ()=>{ const result = await axios( `http://127.0.0.1:8000/categories/` , ); setData(result.data) }); return( <ul> {data.hits.map(item=>( <li key={item.id} >{item.name}</li> ))} </ul> ) } export default App; Result Access to XMLHttpRequest at 'http://127.0.0.1:8000/categories/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET http://127.0.0.1:8000/categories/ net::ERR_FAILED I tested in Postman, my API response is fine. I can see my API. However, when browser tried to fetch the API, it complains by the CORS (I … -
is there a way that i can connect my app with a gprs tracker?
Car theft becoming a major issue in my country, I am trying to build an app that will communicate with the GPRS tracker, I know there are some apps in the market but I want to add some more enhanced features to the app, how do I go about integrating the app with the GPRS tracker. Thanks! -
Django model ImageField creates a nested folder each time it uploads file
I'm sure I'm missing something silly, but I'm confused. I have the following model for my profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default="default.jpg", upload_to="profile_pics/", validators=[FileExtensionValidator(["jpeg", "jpg", "png"])], ) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): if self.image: self.image = make_thumbnail(self.image, size=(200, 200)) super().save(*args, **kwargs) else: super().save(*args, **kwargs) But the profile_pics folder keep nesting (I'm not sure what triggers it, I'm not uploading a new avatar). So my folder structure starts to look like this: And I can't login with that user, as I get an error that reads: SuspiciousFileOperation at /login/ Storage can not find an available filename for "profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/1_0hOa7bn.jpg". Please make sure that the corresponding file field allows sufficient "max_length". My variables in settings.py look normal, I believe: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" I'm not sure where to look for the cause of this error. Uploading images to the blog posts work fine, it's just the profile photos behaving like this. Could anyone please help? -
Django queryset renders incorrectly. Just displays <QuerySet [<Modelname: Model object (1)>]>
I'm having a problem with rendering an object from a model. Here is the model. class Quarterback(models.Model): name = models.CharField(max_length=20) When I use a queryset like this... QB = Quarterback.objects.all() It doesn't return the object but this instead. <QuerySet [<Quarterback: Quarterback object (1)>]> The object is being saved by a function inside a form. class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) In my admin panel, I can look up this model object and see that it does indeed have the name of a quarterback saved to the table. I'm not sure why my queryset won't return this though. Perhaps it's the save function causing it? -
How to add delete and update functionality to ModelSerializer?
I want to update and delete category instances using api. I have a simple model: class Category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name this is my serializer: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["name"] view: class CategorySerializerView(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() def get_permissions(self): if self.request.method == "GET": self.permission_classes = (AllowAny, ) else: self.permission_classes = (IsAdminUser, ) return super(CategorySerializerView, self).get_permissions() urls: router = DefaultRouter() router.register(r'', CategorySerializerView) urlpatterns = [ path("", include(router.urls)) ] -
Why do I get ValidationError on my serializer when I shouldn't be getting one?
So I have this serializer: class MarkReadDeserializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Message.objects.all()) is_read = serializers.BooleanField() And view: class MarkReadView(CreateAPIView): read_serializer_class = MarkReadSerializer write_serializer_class = MarkReadDeserializer def get_write_serializer(self, *args, **kwargs): kwargs['many'] = True return super().get_write_serializer(args, kwargs) Now my view is being POSTed data in the shape of: [{"id": 1, "is_read": true}, {"id": 2, "is_read": false}] When this happens I get this error: rest_framework.exceptions.ValidationError: {'id': [ErrorDetail(string='This field is required.', code='required')], 'is_read': [ErrorDetail(string='This field is required.', code='required')]} I did override my is_valid method in serializer to see the initial data: def is_valid(self, raise_exception=False): print(self.initial_data) And it is printing expected: {'data': [{'id': 123, 'is_read': True}, {'id': 122, 'is_read': True}, {'id': 121, 'is_read': True}, {'id': 120, 'is_read': True}], 'many': True} Why do I get the ValidationError? -
ModelForm is not generating any form
So my problem is that even though I have created the forms from my model and provided my views with those forms, the related template is not displaying any form: The following is my forms.py : from django import forms from django.contrib.auth.models import User from .models import Account class UserUpdateForm(forms.ModelForm): email = forms.EmailField(max_length=100) class Meta: model = User fields = ['username', 'email'] class AccountUpdateForm(forms.ModelForm): class Meta: model= Account fields = ['image'] And the next one is my views.py: from .forms importUserUpdateForm, AccountUpdateForm def account(request): user_update_form = UserUpdateForm() profile_update_form = AccountUpdateForm() return render(request, 'blog/profile.html', { 'user_update_form':user_upate_form, 'profile_update_form':profile_update_form }) But the following template does not show any form {% extends './base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-12 d-flex flex-column justify-content-center align-items-start"> <img src="{{ user.account.image.url }}" alt="" class="user-profile-pic"> <label for="user-profile-pic-input">Choose an image</label> <input type="file" class="form-control-files w-100" id="user-profile-pic-input" name='user-profile-pic-input'> </div> </div> <div class="row"> <div class="col-12"> <form method="POST"> {% csrf_token %} {{ user_update_form }} {{ profile_update_form }} <input type="submit" value="Save changes!" class="btn btn-info btn-block"> </form> </div> </div> {% endblock %} -
Return two different models in the same queryset in django
Let's use these 2 simple models for example. A product can have multiple images. models.py class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Image(models.Model): image=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) In my viewset, in get_queryset(), I am fetching list of all the products, based on some keyword filter on the product's name and all their images, with queryset = Product.objects.select_related('image').filter(name__contains="Fanta").all() To the client, I want to return: JSON, a table, list of all the products (product_id, product_name, product_description) and, Another JSON, another separate table of all the images of all the products. (image_id, image, product_id) One way to do this is to make a combined Serializer, which will give me the fields (image_id, image, product_id, product_name, product_description) But I don't want this, since for every image, the product_description will be repeated, and since that one can be quite large, 10.000 characters, I want to find a more optimal way. I want to get the product_description as well, but only once, there is no need to repeat it in every row, for every image of that product. Another way to do this is to make two separate viewsets, each one with its own get_queryset(). But for the product model, I will have to filter the product_names … -
Dockerfile error - FROM requires either one or three arguments
I'm trying to import a base image into docker, but when I write the following command in my terminal: docker build . I get the following error: failed to solve with frontend dockerfile.v0: failed to create LLB definition: Dockerfile parse error line 2: FROM requires either one or three arguments It is telling me FROM requires one or three arguments (I'm following a book and they wrote it exactly like that) My Dockerfile contains the following: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ I'm running the code while in the same dir as the Dockerfile - The Dockerfile is named 'Dockerfile' Docker version 19.03.13 Any ideas why this is happening? Thank you in advance -
Error encountered while using py decouple
A string is returned in the settings.py file but SPOTIPY_REDIRECT_URI goes unnoticed. .env SPOTIPY_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxx SPOTIPY_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx SPOTIPY_REDIRECT_URI=http://localhost/ settings.py SPOTIPY_CLIENT_ID= config('SPOTIPY_CLIENT_ID') SPOTIPY_CLIENT_SECRET= config('SPOTIPY_CLIENT_SECRET') SPOTIPY_REDIRECT_URI= config('SPOTIPY_REDIRECT_URI') ERROR: decouple.UndefinedValueError: SPOTIPY_REDIRECT_URI not found. Declare it as envvar or define a default value. -
Run Django commands on Elastic Beanstalk SSH -> Missing environment variables
So this has been a long-running problem for me and I'd love to fix it - I also think it will help a lot of others. I'd love to run Django commands after ssh'ing on my Elastic Beanstalk EC2 instance. E. g. python manage.py dumpdata The reason why this is not possible are the missing environment variables. They are present when the server boots up but are unset as soon as the server is running (EB will create a virtual env within the EC2 and delete the variables from there). I've recently figured out that there is a prebuilt script to retrieve the env variables on the EC2 instances: /opt/elasticbeanstalk/bin/get-config environment This will return a stringified object like this: {"AWS_STATIC_ASSETS_SECRET_ACCESS_KEY":"xxx-xxx-xxx","DJANGO_KEY":"xxx-xxx-xxx","DJANGO_SETTINGS_MODULE":"xx.xx.xx","PYTHONPATH":"/var/app/venv/staging-LQM1lest/bin","RDS_DB_NAME":"xxxxxxx":"xxxxxx","RDS_PASSWORD":"xxxxxx"} This is where I'm stuck currently. I think need would need a script, that takes this object parses it and sets the key / values as environment variables. I would need to be able to run this script from the ec2 instance. Or a command to execute from the .ebextensions that would get the variables and sets them. Am I absolutely unsure how to proceed at this point? Am I overlooking something obvious here? Is there someone who has written … -
Django Saving files in database with username
I am getting multiple file entries from the user. And I save all of these in the database in one go. But I don't want these files to get mixed up when multiple users use the system. Therefore, when I save each file, I want the username that uploaded that file to be saved in the database. Models.py class users(models.Model): person_name = models.CharField(max_length=50, null=False, blank=True, verbose_name="name") person_surname = models.CharField(max_length=50, null=False, blank=True, verbose_name="surname") email = models.CharField(max_length=100, null=False, blank=True, verbose_name='email') user_name = models.CharField(max_length=30, null=False, blank=True, verbose_name="username") user_password = models.CharField(max_length=35, null=False, blank=True, verbose_name="password") class files(models.Model): owner= models.OneToOneField(User, unique=True, related_name="owner", on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) excelFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) wordFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) txtEmailFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) txtContentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) attachmentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) forms.py class DocumentForm(forms.ModelForm): class Meta: model = files fields = ('description', 'excelFile', 'wordFile', 'txtEmailFile', 'txtContentFile', 'attachmentFile') views.py ( only one func ): @login_required(login_url="login") def sendmail(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sendmail') else: form = DocumentForm() return render(request, 'sendmail.html') I am not adding the html file here because I received multiple file entries from the user and the html file is mixed. Database ( MySql Workbench ): How can I do it ? -
Django Rest Framework Error: JSON parse error - Expecting ':' delimiter: line 4 column 21 (char 103)
I want to save a new user via POST request using the @api_view decorator in DRF but got the following error : { "detail": "JSON parse error - Expecting ':' delimiter: line 4 column 21 (char 103)" } models.py code: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.conf import settings class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'users/default.jpg', upload_to = 'users/profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) views.py code: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from .serializers import UserSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['GET', 'POST']) def user_list(request): if request.method == 'GET': users = User.objects.all().order_by('id') serializer = UserSerializer(users, many = True) return Response(serializer.data) elif request.method == 'POST': serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_created) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py code: from rest_framework import serializer from django.contrib.auth.models import User from .models import Profile from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only = True) … -
NameError: name 'MyModel' is not defined. Why?
I dont really understand what is happening in my code but it says the my Book model is undefined. Below is my code: This is my forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class BooksForm(forms.ModelForm): class Meta: model = Books fields=('book_id',) my models.py class Books(models.Model): book_id = models.CharField(primary_key=True, max_length=50) book_title = models.CharField(max_length = 100) book_author_id = models.ForeignKey(Author, on_delete=models.CASCADE) book_cover = models.ImageField(upload_to='media/') book_file = models.FileField(upload_to='media/') book_year = models.DateField(default = timezone.now) book_tags = models.CharField(max_length = 100) book_summary = models.CharField(max_length = 100) book_category_no = models.ForeignKey(Category, on_delete=models.CASCADE) book_info = models.CharField(max_length = 100, default="") is_bookmarked = models.BooleanField() is_downloaded = models.BooleanField() is_read = models.BooleanField() class Meta: db_table = "Books" -
How to make an API using DRF to accept and verify a JWT?
I need to make an API which can take in a JWT token and an ID parameter and create multiple endpoints which will serve data( like '../api/contact/', '../api/qualifications/', etc). I do not understand how to take in the JWT and the ID parameter. Should I make another API endpoint where the user can POST the data but how do I save it in Django and design a way to serve the other endpoints? This is the first time I'm making any sort of APIs. -
Djongo: objects.all() on model having ArrayReferenceField
I'm using Djongo(a mongo database connector for django). Model.objects.all() causes issues on a model containing ArrayReferenceField (documentation: https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/). The code works as expected when I remove all the ArrayReferenceFields from the model In the code below, Projects.objects.all() gives the error: from_db_value() missing 1 required positional argument: 'context'. However, printing Projects.objects gives database_models.Projects.objects irrespective of whether the model contains an entry. So the error lies in the all() method. Any one of the following will help: Syntax to fetch all records Modification of model such that it supports all functionalities of ArrayReferenceField Any other workaround so I can store and fetch the values Traceback: Traceback (most recent call last): . . . File "Path_to_file_having_method\project.py", line 85, in fetch_projects_of_user print(Projects.objects.all()) File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 276, in __iter__ self._fetch_all() File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 74, in __iter__ for row in compiler.results_iter(results): File "\env\lib\site-packages\django\db\models\sql\compiler.py", line 1095, in apply_converters value = converter(value, expression, connection) TypeError: from_db_value() missing 1 required positional argument: 'context' My model: from .users import Users from djongo import models class Projects(models.Model): project_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200) description =models.CharField(max_length=200,default='') mentor = models.CharField(max_length=200,default='') max_members = models.IntegerField() … -
Django Rest Framework - Calling .update() from an overriden .create() method inside ModelViewSet
I'm using Django 2.2.x and djangorestframework 3.11.1. Inside a ModelViewSet I had to override the .create() method to customize the default behavior. Sometimes I need to really create a new model instance upon receiving a POST http request, sometimes I need to .update() an existing instance but all I can receive are POST requests (the source is an external server I don't have control over). I know it's a bad idea to conflate create and update... The problem is that whenever my update-instead-of-create logic kicks in, I get the following error: AssertionError: Expected view EventViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly I tried two other ways to work around this issue: directly call Event.objects.update() but I realized this is a no go for me, since I overrode the get_serializer() method to alter the raw json payload coming from the external server and I don't want to duplicate the customization logic here. calling the django built-in .update_or_create() method but the filtering was a bit too complex and I still have the same problem of the first bullet My view: class EventViewSet(LoggingMixin, viewsets.ModelViewSet): """this is … -
How to deserialize array of objects with no name?
So I have array of object being POSTed to my view with shape like this: [{"id": 5, "is_read": true}, {"id": 6, "is_read": false}] I want to find a way of deserializing that in my DRF serializer. It is possible to have nested serializers when your array has name, that is, is like this: "arrayName": [] instead of just like this: []. With nested serializers I could write something like this: class MarkReadItemDeserializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Message.objects.all()) is_read = serializers.BooleanField() class MarkReadDeserializer(serializers.Serializer): arrayName = MarkReadItemDeserializer(many=True) Now this obviously doesn't work in my case because my array is not named arrayName. Any idea how I could go about this? -
filedescriptor out of range in select() when using Celery with Django
I am using Django, Celery and Channels(with redis backend) to handle tasks in Dajngo based backend. Recently, as the things have scaled, I am facing the issue of : ValueError('filedescriptor out of range in select()',) Traceback (most recent call last): File "/home/cbt/backend/venv/lib/python3.6/site-packages/asgiref/sync.py", line 46, in __call__ loop.run_until_complete(self.main_wrap(args, kwargs, call_result)) File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete self.run_forever() File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever self._run_once() File "/usr/lib/python3.6/asyncio/base_events.py", line 1415, in _run_once event_list = self._selector.select(timeout) File "/usr/lib/python3.6/selectors.py", line 323, in select r, w, _ = self._select(self._readers, self._writers, [], timeout) File "/home/cbt/backend/venv/lib/python3.6/site-packages/gevent/monkey.py", line 831, in _select return select.select(*args, **kwargs) File "/home/cbt/backend/venv/lib/python3.6/site-packages/gevent/select.py", line 145, in select sel_results = _original_select(rlist, wlist, xlist, 0) ValueError: filedescriptor out of range in select() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/cbt/backend/venv/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(*args, **kwargs) File "/home/cbt/backend/venv/lib/python3.6/site-packages/celery/app/trace.py", line 648, in __protected_call__ return self.run(*args, **kwargs) File "/home/cbt/backend/cbproj/tasks/tasks.py", line 1095, in start_new_subgame_timer add_users_to_subgame(game, game_type) File "/home/cbt/backend/cbproj/tasks/tasks.py", line 1405, in add_users_to_subgame async_to_sync(group_send_empty_subgame_audio_game_response)(game, game_type) File "/home/cbt/backend/venv/lib/python3.6/site-packages/asgiref/sync.py", line 50, in __call__ loop.run_until_complete(loop.shutdown_asyncgens()) File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete self.run_forever() File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever self._run_once() File "/usr/lib/python3.6/asyncio/base_events.py", line 1415, in _run_once event_list = self._selector.select(timeout) File "/usr/lib/python3.6/selectors.py", line 323, in … -
Whe I am starting my server i am getting values of my form printed on my html page, which i have not taken as input yet
[![enter image description here][1]][1] Here i have to take input for city ,but instead it showing these default values.. [![enter image description here][2]][2].stack.imgur.com/CnWLz.png This is my views.py [![enter image description here][3]][3] this is index.html [1]: https://i [2]: https://i.stack.imgur.com/0ocRa.png [3]: https://i.stack.imgur.com/HVcS5.png -
django NoReverseMatch when trying to delete an object from database
I'm new to django and I've been stuck on a problem when trying to delete objects in my project's database. I've made a function in my views.py that should delete objects that are passed to it. Problem is, my template doesn't seem to be passing information correctly to the url so the whole chain is breaking. Here's the delete function in views.py def delete_player(request, id): quarterback = Quarterback.get(id=id) quarterback.delete() return redirect('show') The model "Quarterback" is here in models.py class Quarterback(models.Model): name = models.CharField(max_length=20) in my template called "show.html" I have this <tr> <td>{{ QB }} <a href="{% url 'delete_player' quarterback.id %}">Delete</a> </td> </tr> Here's the path in urls.py path('delete_player/<int:id>', views.delete_player, name="delete_player") This all keeps returning a "NoReverseMatch: Reverse for 'delete_player' with arguments '('',)' not found. 1 pattern(s) tried: ['game/delete_player/(?P[0-9]+)$']" The error message also keeps referring to my show() in views.py like this... C:\Users\Leigh\Desktop\fantasyfootball\game\views.py, line 321, in show return render(request,"game/show.html", context) … ▼ Local vars Variable Value K 'Greg Zuerlein K 10.0' QB 'Russell Wilson QB 41.34' RB 'Mark Ingram RB 31.5' TE 'Austin Hooper TE 18.6' WR 'Mike Evans WR 37.0' context {'K': 'Greg Zuerlein K 10.0', 'QB': 'Russell Wilson QB 41.34', 'RB': 'Mark Ingram RB 31.5', 'TE': 'Austin Hooper … -
Caching list of id's of django queryset, and reusing that list for another Viewset
Let's use these 4 simple models for example. A city can have multiple shops, and a shop can have multiple products, and a product can have multiple images. models.py class City(models.Model): name=models.CharField(max_length=300) class Shop(models.Model): name = models.CharField(max_length=300) city = models.ForeignKey(City, related_name='related_city', on_delete=models.CASCADE) class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=5000) shop=models.ForeignKey(Shop, related_name='related_shop', on_delete=models.CASCADE) class Image(models.Model): image=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) For an eCommerce website, users will be writing keywords and I filter on the products names, to get the matching results. I also want to fetch together the related data of shops, cities and images, relevant to the products I will be showing. To achieve that I am using .select_related() to retrieve the other objects from the foreignKeys as well. Now, my question is, what is the best way to send that to the client? One way is to make a single serializer, that groups all data from all 4 tables in a single JSON. That JSON will look like 1NF, since it will have many repetitions, for example, there will be new row for every image, and every shop that the product can be found, and the 10.000 character long description will be repeated for each row, so this is not such a good … -
How to avoid displaying form errors twice when using messages?
When showing a form in a template, I have a block that displays form errors: {% if field.errors %} {% for error in field.errors %} <div class="d-block">{{ error }}</div> {% endfor %} {% endif %} However on the same page I also have a block to display messages from the Django message system: {% for message in messages %} <div class="alert alert-{% if message.level_tag %}{{ message.level_tag }}{% endif %} alert-dismissible fade show" role="alert"> {% if message.extra_tags and 'safe' in message.extra_tags %} {{ message|safe }} {% else %} {{ message }} {% endif %} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} This means the form errors are displayed twice on the page, both in the messages block and the field.errors block. How do I avoid this?