Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
celery .delay freezes for this task but runs for others
I am trying to send notifications using celery. @shared_task(name="send_notifs_to_devices_task") def send_notifs_to_devices_task(devices_ids, title, message, image=None, link=None): from pills_reminder.models import UserNotifications, UserDevice devices = UserDevice.objects.filter(id__in=devices_ids) for device in devices: UserNotifications.objects.create( uid=device.device_id, title=title, message=message, image=image, linksTo=link ) # TODO: to recieve image here device.send_notification(title=title, body=message, click_action=link) print('task to be done by celery') logger.info(f"successfully sent notifications to {len(devices)} devices") this works without .delay() >>> send_notifs_to_devices_task(devices, ... title=instance.title, ... message=instance.message, ... link=instance.link) {'multicast_ids': [4255826789468640174], 'success': 1, 'failure': 0, 'canonical_ids': 0, 'results': [{'message_id': 'https://updates.push.services.mozilla.com/m/gAAAAABepnOW1plHQRAB5kRMziPs47eXuzEFbJxR891Pps1Okyz_a-waK3jZ2IX3YehnDuuSut6WkVzEVoKODeOOkHFEf6teOyvVVatkjh3Du8UokRbLx8vC59_GbqeuS7wYxjtGGICXkrAK_xBaUjGbYaIII3nqXxGacLkcX2pWt2Ag6wGHmc3U3imzYx-3mde4zpncIVIb'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [7964723727637075692], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [7140533530146400686], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [5226660064264463708], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None} but when i call this using .delay, it freezes. >>> send_notifs_to_devices_task.delay(devices, ... title=instance.title, ... message=instance.message, ... link=instance.link) Note, when i call another task such as add.delay(1,2), this works: >>> add.delay(1,2) <AsyncResult: 61b76768-73ef-4ca2-bbae-445ee528cafe> I don't have much knowledge of celery and i don't know what is wrong here? -
How to change lookup field in Model.viewset to other unique parameter in Django Rest Framework?
I am using Modelviewset in django rest framework. I want to change lookup field to email(unique) instead of id. I have tried adding lookup_field = 'email' inside my Schema viewset but it is not working. This is what i am getting { "detail": "Not found." } How do I resolve this. my Views.py: class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer lookup_field = 'email' my models.py: class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() email = models.EmailField(unique = True ) def __str__(self): return self.email my serializers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version', 'email') -
Maintaining order of querylist
I have a query that looks like this: top_posts= Ranking.objects.all().order_by("-score").values("post") It gets the top posts ordered by score and then this query is executed: Posts.objects.filter(id__in=top_posts) However, the order_by score is thrown away when I run this query. How do I maintain the order of the score? -
Django: return translation text within views
I use translations in the templates. All messages are compiled and configured properly. However I would like to return a translated string directly from the view. How is this possible? from django.utils.translation import gettext as _ def MyView(request): return HttpResponse(_('FILE_TYPE_NOT_ALLOWED')) -
Integrating remote Django/Python applications on a WordPress hosted website
Let's say I have a website hosted on WordPress on an instance A. On an instance B (AWS EC or another cloud) there's a set of Python applications running, that are integrated with Django. These applications in result produce charts (e.g. Plotly) and in general serve requests trough WEB API. All these can be accessed after authenticating using Django user management subsystem. What I would like to do, is provide a means for authentication for accessing the EC hosted services on my WP hosted website. I assume that this should be relatively trivial, as I can simply add a small login form in an iframe, thus creating authorization token locally and this will be used whenever the WP website will contact EC instance e.g. for obtaining charts in few another iframes - please correct me if I'm wrong here. How can I inform the parent website (WP hosted) that it should for instance not display anything in an area where the iframes are located before authentication or when the session is lost (login in)? And then how to tell the parent website to place the iframes after authentication? -
Django elasticsearch unable to import modules
I am new to python and have some experience with Elasticsearch. I am trying to index my Model from Django to Elasticsearch. I have configured django-elasticsearch-dsl as per the official website. However, when I runserver, I got from elasticsearch.helpers import bulk, parallel_bulk ModuleNotFoundError: No module named 'elasticsearch.helpers' This happens only with my project which I worked for almost 2 weeks and have many models and data in it. I tried to create a new project and used 'django-elasticsearch-dsl' where I could connect to elasticsearch without any issues. I am not sure how to resolve this in my existing project/venv. -
How to load html template with parameters in Ajax callback (Django server)
When my user signs in, I want to check localStorage (using AJAX) to see if the user left any items in his basket. If yes, I want to render (or redirect) him to prebasket.html which I would normally do via return render(request, "pizza/prebasket.html", context) as per below in views.py: @login_required def prebasket(request): q_preselection = request.POST.dict() preselection = json.loads(q_preselection["preselection"]) items = [] # iterate thru menu items (ids) in user's selection for id in preselection: dish = Dish.objects.get(pk=id) item = { "id": dish.id, "name": dish.name, "size": dish.size, "price": ("%.2f" % float(dish.price)), "amount": preselection[id], "total": ("%.2f" % (int(preselection[id]) * float(dish.price))) } items.append(item) context = {"items": items} print(f"Context is: ", context) # comes out correctly on terminal return render(request, "pizza/prebasket.html", context) However, prebasket.html is not rendered. And I read that AJAX doesn't work like that, so I tried window.location.href in my JavaScript/AJAX (not using jQuery for now - sorry am new to all this...). But it's not working either - or at least I am not able to pass on the required parameters for the context needed in the url: var preselection = localStorage.getItem("preselection"); function previous_selection () { if (localStorage.getItem("preselection") != null) { const data = new FormData(); data.append("preselection", preselection); const request = … -
Testing an online payment Form using Django Keep getting Not Authenticated Error. Is it because of the Testing Credit Card numbers?
I am making a project for an online payment e-commerce I think I got everything right as am following a Tutorial Keep getting this Error: Not Authenticated Error I used the testing CC Numbers for testing purposes My question is the following codes correct and I'm getting fake Not Authenticated Error because they are testing Credit Card Numbers.? class PaymentView(View): def get(self, *args, **kwargs): # order return render(self.request, "payment.html") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your Order was Successful ! ") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") # Since it's a decline, stripe.error.CardError will be caught return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate Limit Error") return redirect("/") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid … -
Html content not showing up after if statement in Django
Im having some issues with my html content not showing up after putting in some {% if %} {% endif %} statements in my templates I have this snippet in my code where I display the checkout table if and only if the current user's username matches the one from my Order model. (order.customer_name has a foreign key that is set to the current users username) {% for order in latest_order %} {% if user.username == order.customer_name %} <tr> <td>{{ order.order_name }}</td> <td> <form method="post"> {% csrf_token %} <button type="submit" name="remove_quantity" value="{{ order.id }}" class="mr-3 btn btn-outline-info">-</button> {{ order.order_quantity }} <button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn- outline-info">+</button> </form> </td> <td>${{ order.order_individual_price }}</td> <form method="post"> {% csrf_token %} <th><button type="submit" name="delete" value="{{ order.id }}" class="btn btn- danger">Delete Item</button></th> </form> </tr> {% endif %} {% endfor %}` I tried the following to see if it prints out the same username, which it does <h1>{{ user.username }}</h1> {% for order in latest_order %} <h1>{{ order.customer_name }}</h1> {% endfor %} Picture of the page with user.username and order.customername as h1 When I delete the if statement, this is what the website SHOULD look like Proper working table Im pretty sure I'm … -
Redirect From REST_API Response
I am using Angular and Django in my stack for a website, and after a user registers it emails them a link to activate their account. As of right now everything is working but the link takes the user to the Django rest framework page. I've been returning responses in my app like this data = {'success': True, 'message': 'An account has been activated.', 'response': {}} return Response(data, status=status.HTTP_201_CREATED) I am curious on how to redirect a user back to the login page which at the current moment would be a localhost page such as http://localhost:4200/#/authentication/login. From research I have found methods like return redirect('http://localhost:4200/#/authentication/login') but I am wanting to keep my responses consistent. Is there a way to redirect a user while still using the rest api Response object? -
DjangoCMS TypeError: from_db_value() missing 1 required positional argument: 'context' after upgrade to 3.7.2 w/ Django 3.0.1
I had a working DjangoCMS application running DjangoCMS 3.7.1 and Django 2.2, however after I just bumped the DjangoCMS version to 3.7.2 and with it, Django to 3.0.1, I am now getting a render error on a page that I have a simple list view. The site will load my custom account login page just fine, but once logged in, the listview breaks and displays this error: Traceback django.request ERROR 2020-04-26 21:15:16,809 log 461 140647593613056 Internal Server Error: /en/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/usr/local/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/usr/local/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/usr/local/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 903, … -
how do i get the id immediately after inserting the data?
I hope the title is enough to understand what my problem is, I have this code in my views.py enroll = StudentsEnrollmentRecord( Student_Users=student,Old_Student=old,New_Student=new, Payment_Type=payment,ESC_Student=esc,Last_School_Attended=last,Address_OF_School_Attended=add, Education_Levels=educationlevel,School_Year=schoolyear,Courses=course,strands=strands,Student_Types=stype,GWA=gwa ) enroll.save() studentenrolment = StudentsEnrollmentRecord.objects.filter(Student_Users=enroll) return render(request, "print.html", {"studentenrolment":studentenrolment}) This is the error i get -
I do not get show data in the datatable angular 2.x
well, I make a web app with django and angular, the API is good but I'm newbie with angular and I don't understand that I'm wrong. import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ListarPersonasService { public personas:any = null; constructor(private http: HttpClient) { } public obtenerPersonas() { const url = 'http://127.0.0.1:8000/api/v1.0/abogado/personas'; return this.http.get(url).subscribe( res => { this.personas = res; console.log(res); } ); } } this is my service, on the component the service to make the request is called and store the result in the variable datasource import { Component, OnInit } from '@angular/core'; import { ListarPersonasService } from "../servicios/listar-personas.service"; @Component({ selector: 'app-listar-personas', templateUrl: './listar-personas.component.html', styleUrls: ['./listar-personas.component.css'] }) export class ListarPersonasComponent implements OnInit { displayedColumns: string[] = ['documento','nombre', 'apellido']; dataSource : any; constructor(private listar:ListarPersonasService) { } ngOnInit() { this.dataSource = this.listar.obtenerPersonas() } } and here this html. <table mat-table [dataSource]="persona" class="mat-elevation-z8"> <ng-container matColumnDef="documento"> <th mat-header-cell *matHeaderCellDef>documento</th> <td mat-cell *matCellDef="let element">{{element.documento}}</td> </ng-container> <ng-container matColumnDef="nombre"> <th mat-header-cell *matHeaderCellDef> Nombre</th> <td mat-cell *matCellDef="let element"> {{element.nombre}}</td> </ng-container> <ng-container matColumnDef="apellido"> <th mat-header-cell *matHeaderCellDef> Apellido</th> <td mat-cell *matCellDef="let element"> {{element.apellido}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> here is the … -
I want to ignore all the locale files in venv and compile others
I am making a locale directory to store the translations in it but I have venv which contains so many locale files.. I want to ignore them and only compile the ones I have made. I already have written in the setting LOCALE_PATHS = ( os.path.join(BASE_DIR, 'Medical_Healthcare_System/locale'),) but when I use compile messages command it compiles only the venventer image description here -
Environ variables in .env file in Django and docker
Hi I'm using Docker to build a Django web application for production via Docker-Compose and it uses the .env.prod file for the environmental variables. The docker-compose file works fine and deploys to a server with no issues via CI/CD on GitLab. I was hoping to use the same kind of structure but just have a .env.dev file so I don't have to modify the settings file in any way. The problem I'm having is I can't find how to set environment variables from an external file in development mode. The only workaround I can see is having a local_settings.py file which I was hoping to avoid. Example of what I'm trying to achieve below in the settings.py file. DEBUG = int(os.environ.get("DEBUG", default=0)) with a .env.dev file. DEBUG=1 DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 149.28.188.180 [::1] Thanks in advance. I'm sure I'm missing something easy. -
Create Django HTML Button that will Change BooleanField in Model
I am a beginner with Django and am hoping to get pointed in the right direction. I am building a webapp that has job postings on it, and I would like to have an "Accept this job" button on each job description page that will change a BooleanField I defined in the model to True. This way, no other users may be able to take on the job. Are there any suggestions? My database is SQLite. -
Django search view not generating html page I set
I am having trouble getting my search form to work in Django. When I search anything in the search bar I have set, I get an html page that just has the words Search on it. It's not the html page I set, though. My search template is in my projects templates directory. I am trying to search through my blog posts, and have attached my views and urls code. This portion of my base template is within a navbar I grabbed from a sample Bootstrap blog template. This is the sample template. I've changed some things within my form. base.html ... <form class="form-inline my-2 my-lg-0" action="{% url 'search' %}" method="GET"> <input class="form-control mr-sm-2" type="search" name="q" placeholder="Search blog posts..."> <button class="btn my-2 my-sm-0" type="submit">Search</button> </form> ... Nothing within my blocks shows up when I view it. The tags <p>TEST</p> and <p>Is this working?</p> are not showing up. Neither is the block for the jumbo_content. I have set those correctly in my base.html, because they work with my other pages. It's just the search page it doesn't work on. search.html {% extends "base.html" %} {% load static %} {% block jumbo_content %} <h1 class="display-4">Search Results</h1> {% endblock %} {% block page_content … -
PostgreSQL text search in Django not working as expected
I am implementing a search function for my API to return the object's properties when requested. So far I have tried to use Full Text Search which is usable but it has these annoying things: words have to be spelled correctly for the results to be returned and partial search, for example "appl" instead of "apple", won't work. I have also tried Trigram Similarity but it failed for long sentences. How do I implement a search function that is both accurate and fuzzy in Django? This works This won't work This is my views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view from .models import Object_Locations from .serializers import Object_LocationsSerializer from django.contrib.postgres.search import SearchVector, SearchQuery def index(request): return render(request, 'main/base.html', {}) @api_view(['GET',]) def LocationsList(request): if request.method == 'GET': vector = SearchVector('name', 'desc', 'catergory') query = request.GET.get('search') if query: locations = Object_Locations.objects.annotate(search=vector,).filter(search=SearchQuery(query)) else: locations = Object_Locations.objects.all() serializer = Object_LocationsSerializer(locations, many=True) return Response(serializer.data) -
Does it possible that transaction.atomic does not work as expected?
This is a DRF API View for entry like. When someone like a entry, i will insert a like record into table entry_like, and plus by 1 to field likes_num in another table entry. But, something went wrong that some of the count of entry_like records corresponding to one entry is less than the field likes_num in table entry. I do not know why it does not work as expected even the post method is with decorator transaction.atomic on. Are there some cases that the decorator transaction.atomic does not run as expected? -
Is there any way to style the field alerts in Django?
I'm working on the style of my website and I'd like to style this part of the form: I tried with field.errors but that's not it. Any ideas? -
Is there an alternative for django admin for Postgres + Hasura?
I was wondering if there are any tools for auto generated content management systems that built on top of postgres/hasura -
Django form, display through field in a form
I have 3 models, shown below. I want to display a form where i can create a navMenu with posts and then select the position of those posts, I can bring in the post to a form but I don't know how to add the through field post_postiton into the form, any help would be very much appreciated -
Django views.py to call python script to open PDF
Target: I want to develop web app automation tool with Django framework for PDF data extraction. It is not like converting entire data of PDF file, It is like specified field in PDF. Specified field can be specified with mouse clicks. Automation script should perform opening PDF files continuously in the folder and extract specified field. Actions completed I have completed python script to open PDF file, and extracting particular field with mouse listener activity and convert it to image and convert to text. Question Can someone confirm whether i can use above python script in django also. I mean whether mouse listener libraries will work in django. It is kind of desktop automation to be called by web application. please confirm whether this is possible. #opening pdf file. can be changed to open list of PDF files in folder def openFile (): os.system("start " + 'AF0002345_Copy.pdf') # i have extracted image from pdf with help of mouse listener activity # below function to convert image to text def ocr_core(filename): pytesseract.pytesseract.tesseract_cmd = r'C:\Users\150629\AppData\Local\Tesseract-OCR\tesseract.exe' text = pytesseract.image_to_string(Image.open(filename)) return text -
How can I fix "ERROR: Command errored out with exit status 1:" when trying to install django-visits
I am trying to install django-visits, but anytime I run the "pip install django-visits" command, I get the following error: ERROR: Command errored out with exit status 1: command: 'c:\users\samuel\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Samuel\\AppData\\Local\\Temp\\pip-insta ll-8t2j3cs9\\distribute\\setup.py'"'"'; __file__='"'"'C:\\Users\\Samuel\\AppData\\Local\\Temp\\pip-install-8t2j3cs9\\distribute\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__fi le__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3c s9\distribute\pip-egg-info' cwd: C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\ Complete output (15 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.``` How can I fix it? -
change image index using jQuery
I have a list of images rendered from Django as follows: <div class="gallery"> <div class="slider-info"> <span class= "pagenum"> <span class="range"> <span id="currentIndex" class="currentIndex"> 1 </span> - <span id="totalCount" class="totalCount"> {{ item.images_cars_trucks_set.all|length }} </span> </span> </span> </div> <!-- images --> <span class="result-image-act"> <span class="img-group"> {% for image in item.images_cars_trucks_set.all %} {% if image.car_images_exists %} {% if forloop.counter == 1 %} <img src="{{image.car_images.url}}" class="active" id="{{image.id}}"> {% else %} <img src="{{image.car_images.url}}" id="{{image.id}}" class=""> {% endif%} {% endif %} {% empty %} <img src="{% static 'towns/images/list_page/no_image_available.png' %}" class="active" id="{{image.id}}"> {% endfor %} </span> <!--slide images --> <div class="swipe-wrap"> <div class="swipe-wrap-lef"> <span class="move" > <div class="swipe-prev"> <p>&lt;</p> </div> </span> </div> <div class="swipe-wrap-rig"> <span class="move" > <div class="swipe-next"> <p>&gt;</p> </div> </span> </div> </div> </span> </div> I have a jQuery script to change the displayed image when mouse hover on specific one as follows: <script type="text/javascript"> $(document).ready(function(){ $('.thumb-nails img').each(function(){ $(this).mouseover(function(){ $(".thumb-nails img").removeClass('img-border active'); $(this).addClass('img-border active'); var current_img = $(this).attr('id'); var image_displayed = $(this).attr('src'); $(".result-image-act img.active").removeClass('active'); $(".result-image-act img[id="+current_img+"]").addClass('active'); $('.result-image-act img.active').attr('src', image_displayed); }); }); }); The question is: How can I add to the Jquery script to indicate the image index number. I though to add number 1 to the first image and then replace each image ID with …