Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
What are the differences between Django and Express.js?
Since, Django and Express.js are both web frameworks for Python and Node.js respectively. So, This is a very basic difference between them. But, there might be other important differences. So, if somebody can explain that here, it will be very beneficial to me. -
How can i fetch a specific to a variable
Hello i want to fetch a specific field to a variable For that I have Order model: class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here I want to fetch total field in a variable.But I am new for that reason I am really confused about this topic -
get variable from method that have a parameters without sending the parameter (dynamic Django Chart Js)
So i have views method in my Django Project like this def analyticindex(request): token = request.GET.get('token') return render(request, 'analytic.html') And another method for viewing the chart into that template ('analytic.html') def respon(request): nama_token = #GET_VARIABLE_token_FROM_analyticindexMethod from .getChart import barFunc, pieFunc model = [Detik,Kompas,Antara] dtk_bar = dict(zip(barFunc(Detik,10)[0],barFunc(Detik,10)[1])) ant_bar = dict(zip(barFunc(Antara,10)[0],barFunc(Antara,10)[1])) kmp_bar = dict(zip(barFunc(Kompas,10)[0],barFunc(Kompas,10)[1])) pie = {} data_bulan = [] for x in pieFunc().items(): pie[x[0]] = x[1] for i in model: for x in i.objects.filter(token=nama_token).values_list('january','february','march','april','may','june','july','august','september','october','november','december'): data_bulan.append(list(x)) data ={ 'pie' : {'nama':list(pie.keys()),'angka':list(pie.values())}, 'dtk_bar':{'nama':list(dtk_bar.keys()),'angka':list(dtk_bar.values())}, 'kmp_bar':{'nama':list(ant_bar.keys()),'angka':list(ant_bar.values())}, 'ant_bar':{'nama':list(kmp_bar.keys()),'angka':list(kmp_bar.values())}, 'jamet':[sum(x) for x in zip(*data_bulan)] } return JsonResponse(data) as we can see, that i need the 'token' variable from analyticindex method into the respon method, so i can dynamicaly get the data into my templates (from user input) Thank you! -
How do I send form data to my email for approval as a post on my django webapp?
I think I know how to send the form data to email with existing django documentation but I am wondering how I'd go about the post pending approval part. also how could I implement the ability to edit the post's contents before the form data gets finally submitted as a post? -
displaying data from Django in React Native app
I am trying to send pull from Postgres database in Django to my React Native app. const [gardens,setGardens] = useState([]); useEffect(() => { fetch("http://127.0.0.1:8000/Home/Gardens/",{ method:'GET', headers:{ 'Content-Type': 'application/json', 'Authorization': 'Token ***' } }) .then( res => res.json()) .then(jsonRes => setGardens(jsonRes)) .catch( error => console.log(error)); }, []); <FlatList data={gardens} renderItem={({item}) => ( <View style={styles.item}> <Text style={styles.itemText}>{item.name}</Text> </View> /> The app is displaying no data and I am getting the following message: [native code]:null in callFunctionReturnFlushedQueue. Please help me solve this issue. -
Boolean expression not returning the right logic
I have a simple code which is supposed to return True or False, if a user is following another user or not. this is the code below, everything is fine that is return "False" all the time even when the user is actually following. I think im missing something. What do you think? def get_is_following(self, obj): is_following = False context = self.context request = context.get("request") if request: user = request.user is_following = user in obj.followers.all() return is_following -
How are databases/table laid out in real life for blog/article websites?
I am building a blog/articles website and wanted to know what is the professional way of laying out the table for it. I am novice web developoer still in the process of learning. Hope someone helps :). -
How to get Authorization Code after successful login -- Linkedin OAuth - Django, Python
I have a Django website where users can fill in an profile form using Linkedin login. My logic was to have the user first sign-in using LinkedIn credentials & then retrieve/parse their profile & populate the fields. I was able to successfully make a user login using 'social-auth-app-django'. Now I believe my next step should be to generate an Access token. However, to generate this access token, I need the authorization code. This is where I need help. I referred to many resources, which all said, copy the authorization code manually & use it for generating access token. But I don't understand, how that's gonna work in my case, as it could be any random user accessing the form.. or am i completely in the wrong path?? Any leads or help will be greatly appreciated. -
Solving IOError while generating a pdf using reportlab and generated qr code image
I am trying to generate a qr code from text, and then insert into a reportlab pdf. My code: def qr_code_as_image(text): from io import BytesIO print("In show_qr") img = generate_qr_code(text) print(img, type(img)) i = Image(img) print(i, type(i)) return i def add_patient_header_with_qr(self): line1 = ("Name", self.linkedcustomer.name, "Age", self.linkedcustomer.age()) line2 = ("MRD No.", self.linkedcustomer.cstid, "Date", self.prescription_time) line3 = ("No.", "#", "Doctor", self.doc.name) datatb = [line1, line2, line3] patientdetailstable = Table(datatb) patientdetailstable.setStyle(self.patientdetails_style) col1 = patientdetailstable checkin_url = reverse('clinicemr', args=[self.checkin.checkinno]) qr_image = qr_code_as_image(checkin_url) qr_image.hAlign = 'LEFT' col2 = Table([[qr_image]]) tblrow1 = Table([[col1, col2]], colWidths=None) tblrow1.setStyle(self.table_left_top_align) self.elements.append(tblrow1) def final_generate(self, footer_content, action=None): with NamedTemporaryFile(mode='w+b') as temp: from django.http import FileResponse, Http404 from functools import partial # use the temp file cmd = "cat " + str(temp.name) print(os.system(cmd)) print(footer_content, type(footer_content)) doc = SimpleDocTemplate( temp.name, pagesize=A4, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=80, allowSplitting=1, title="Prescription", author="MyOPIP.com") frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') template = PageTemplate( id='test', frames=frame, onPage=partial(footer, content=footer_content) ) doc.addPageTemplates([template]) doc.build(self.elements, onFirstPage=partial(footer, content=footer_content), onLaterPages=partial(footer, content=footer_content) ) print(f'Generated {temp.name}') I get the following output: 2020-11-29 13:06:33,915 django.request ERROR Internal Server Error: /clinic/presc/k-0NGpApcg Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 655, in open_for_read return open_for_read_by_name(name,mode) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 599, in open_for_read_by_name return open(name,mode) ValueError: embedded null byte During handling of … -
How to Merge Slashes in uWSGI When Using HTTP-Socket [Django]
I have a problem where the frontend engine sometimes adds an extra slash / in the URLs as such: /api/v1/sample//path If my UWSGI is set in socket mode, this would not cause an issue. I guess it merges the slashes internally. But, if I put the uWSGI in http-socket mode, I get the 404 because of the double slashes. How can I resolve it through uWSGI settings? Note: I have activated merge_slashes on; in Nginx configs [which is proxy passing the requests to my UWSGI]. But, it does not resolve the issue. -
Cashing all the static assets at once in a service worker in PWA
My question is about caching all the static assets present in a seperate directory (for me it is 'static') at once in the service worker in a PWA. As we know we need to provide a path to the asset to be cashed. E.g, if we want to cache an image 'img.png' then we need to do something like this; cache.add(/static/img.png) where cache is the element returned by caches.open(). And if we want to add multiple files we can do something like this; assets = [ 'static/img1.png', 'static/img2.png' ] // and so on. cache.addAll(assets); What i want to know is that if there is any way to pass directly all the files present in static folder like; cache.add(/static); But the above line is not working as we can only pass a valid path(URL) not a folder or just a file. -
I want to only fetch a specific field data
Hello in my order model i have these fields : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True, blank=True) From here i have total field where i want to create a result depend on quantity and price.For an example price * quantity = total After that i want to fetch only the total I am new in django really confused about this Please help -
"Permission Denied" when accessing private keys downloaded from S3 to elastic beanstalk
I stored Firebase Admin SDK credential into elastic beanstalk env from amazon S3 on app's deployment according to the official AWS doc. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/https-storingprivatekeys.html When Firebase Admin SDK tries to access the key it raises error. PermissionError: [Errno 13] Permission denied: '/etc/pki/tls/certs/my_cert.json' How can I setup make it work? -
docker - How to set up environment database for docker-compose.yml file from env.ini file outide?
This is my docker-compose.yml which I hard-code the information of database, I want to input in it from a file env.ini of mine before pushing it to GitLab for safety but dont know how to do it. version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=####### Hide these information and take it from - POSTGRES_USER=##### another file when running it - POSTGRES_HOST=172##### - POSTGRES_PASSWORD=######### web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Plus: my file env.ini is quite complicated since its contains a lot of others information, it looks like this: [sv_info] host = ######### user = ######## password = ######## database = # venus_base_url = ################# venus_auth_key = cargo_base_url = ################# cargo_awb_acckey = ################# cargo_awb_cusnum = ################# cargo_awb_user = ################# cargo_awb_revkey = ################# [heremap_info] url = ################# api_key = ################# Usually, I use from configparser import ConfigParser in Python to work with this env.ini in my code. -
Django file upload shows None: HTTP 400 Bad Request
I am receiving multipart/form-data in my django api.My task is to send same data to other server(api). class CreativeUploadViewset(viewsets.ViewSet): def create(self,request, format=None): file_path = request.query_params.get('file_path', None) file_type = request.query_params.get('file_type', None) member_id = request.query_params.get('member_id', None) in_memory_uploaded_file = request.FILES['file'].file.getvalue() files = {'file': in_memory_uploaded_file, 'type': ('image')} response_data = CREATIVE_UPLOAD.create(data = None, files=files,headers={"Content-Type": "multipart/form-data", "boundary":request.headers["Content-Type"][30:]}) return Response(response_data) CREATIVE_UPLOAD.create() hits the other server api. When i hit the other server i get following error: **"None: HTTP 400 Bad Request"** When i googled i got to know we should include 'boundary' parameter in headers. Things to note I tried this in both python 3.6 and later versions. in_memory_uploaded_file looks somethind like this: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\x1d\x00\x00\x01\xe2\x08\x06\x00\x00\x00\xfc\x95\r4\x00\x00\x00\x04sBIT\ ......... It works if i directly sent image or video file from postman to the other server. -
Using Validators to validate Words in Comments not working
I am trying to validate Comments in Posts to ensure that there are no bad words used in it. I have checked about Writing validators but it is not working and I am not sure what is the reason. The badwords.txt location is: C:\Users\User\Desktop\Project\badwords.txt The function lives in the models.py: with open("badwords.txt") as f: CENSORED_WORDS = f.readlines() def validate_comment_text(text): words = set(re.sub("[^\w]", " ", text).split()) if any(censored_word in words for censored_word in CENSORED_WORDS): raise ValidationError(f"{censored_word} is censored!") class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text,]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) My question: What am I doing wrong and how do I get this function to work? -
Same api endpoint for CRUD operations in Django generic apiview
I have been creating different api endpoint for different requests, for eg every single api for get, post, delete and update in generic apiview. But my frontend developer has told me it's a very bad practice and I need to have a single api for all those 4 requests. When I looked it up in the documentation, there is a ListCreateApiView for listing and creating an object, but I cant use it for delete and also for update. How can I include those two in a single endpoint. I don't use modelset view and also functional view. I mostly use generic api views. -
How to correctly use Django reverse FK lookup to show instances of the child model in CBV
I have two models, field of one of them pointing to the other as shown below: class Group(models.Model): group_company_id = models.CharField(primary_key=True, ...) class Company(models.Model): company_id = models.CharField(primary_key=True, ...) group_company = models.ForeignKey(Group, related_name="related_grp_company", ...) I am trying to get all the Companies that have been created for a particular Group. So I am trying to get the company_id (and other) values in Djnago UpdateView as a list in the template. My CBV is as shown: class GroupCompanyChangeView(UpdateView): template_name = ... model = Group form_class = ... success_url = reverse_lazy('group_list') grp_coy_units = GroupCompany.objects.prefetch_related('related_grp_company') # I am trying to get the values of `company_id` in the template but nothing is displayed. Could somebody please let me know how to get this to work? -
Adding get_context_data method to a class based view breaks django-tables2
I have a class-based view that I use to obtain a queryset and pass to django-tables2 which renders the result. That aspect all works fine. I am trying to pass a record instance from a different queryset to the template, so I can display information above the table django-tables2 produces. Upon searching, it seems the 'right' way to do so is via the get_context_data method. However when I attempt do add this method to my view, simply obtaining the queryset and returning it, it produces an error Expected table or queryset, not str. I isolated this to being due to {% render_table table %} in my template. Without that, I can access my 'team' object as intended. Why is this happening? The qs queryset was being passed fine to django-tables2 before I added my get_context_data method. Does the qs queryset have to be returned via get_context_data as well? If so, why? This is my attempt: class myteam(LoginRequiredMixin, SingleTableView): def get_queryset(self): qs = Contestant.objects.filter(assigned_team=self.request.user.contestant.assigned_team) qs = qs.exclude(id=self.request.user.contestant.id) return qs def get_template_names(self): return 'xgames/viewteam.html' def get_table_class(self): return TeamsTable def get_context_data(self): team = Team.objects.get(id=self.request.user.contestant.assigned_team.id) return {"team": team} -
i created a django software its running on localhost,but not working on heroku its log is showing this
ink to github for that software is https://github.com/ShubhamSjain2000/stockware.git 2020-11-28T07:50:10.254987+00:00 app[api]: Release v4 created by user shubham1900jain@gmail.com 2020-11-28T07:50:10.531132+00:00 app[api]: Deploy d9583d0a by user shubham1900jain@gmail.com 2020-11-28T07:50:10.531132+00:00 app[api]: Release v5 created by user shubham1900jain@gmail.com 2020-11-28T07:50:20.000000+00:00 app[api]: Build succeeded 2020-11-28T07:50:35.159601+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=stockware.herokuapp.com request_id=0b1c2b67-1ac9-4247-8f90-fb928da59cd6 fwd="182.70.189.243" dyno= connect= service= status=503 bytes= protocol=https 2020-11-28T07:50:36.170169+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=stockware.herokuapp.com request_id=af302f4c-e5cc-405e-ba97-30a07516c784 fwd="182.70.189.243" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:12:18.801989+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=stockware.herokuapp.com request_id=e9644275-2548-4405-8dab-7f58291c79ec fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:12:23.337106+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=stockware.herokuapp.com request_id=54638bf1-67b2-4982-8e2c-365826a046f2 fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:19:50.571393+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=stockware.herokuapp.com request_id=ac335c25-ed5e-4faa-909d-9208375721f7 fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:19:51.945843+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=stockware.herokuapp.com request_id=ba9f09fb-8aff-4096-af16-cb673534520e fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https