Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
use nginx to serve dynamically created media images in Django/React
I have a React front-end and a Django backend. I am also using nginx server. In the admin panel, I am able to add pdfs which go directly into a 'media' folder inside of the django application. In development, everything works correctly but In production, when Debug = false, the media files do not show up. I am thinking of using the nginx server to re-route to the media folder. But I think something is wrong, as the media files do not show up. Also, is this the best method to redirect to the media files? Below is my ngnix server server { listen 80; client_max_body_size 60M; location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /api { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /admin { proxy_pass http://backend:8000/admin; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location ~^ /media { autoindex on; alias /path/to/media; } location /nginx-health-check { access_log off; return 200; } } -
TypeError at /formpage '>' not supported between instances of 'str' and 'int' also the error is specific in form.is_valid
This is forms.py from django import forms from django.core import validators def check_for_z(value): if value[0].lower() !='z': raise forms.ValidationError("NAME NEEDS TO START WITH Z") class FormName(forms.Form): name = forms.CharField() email = forms.EmailField() text = forms.CharField(widget= forms.Textarea) botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxValueValidator(0)]) This is views.py from django.shortcuts import render from . import forms from .forms import FormName from django.http import HttpResponseRedirect def index(request): return render(request,'formapp/index.html') def form_name_view(request): form = forms.FormName() if request.method == "POST": form = forms.FormName(request.POST) if form .is_valid (): # do something code print("Validations scuces") print("NAME: "+form.cleaned_data["name"]) print("EMAIL: "+form.cleaned_data["email"]) print("TEXT:"+form.cleaned_data['text']) # return HttpResponseRedirect("/thanks/") else: form= FormName() return render(request,'formapp/form_page.html',{'form' : form}) Now actually it is throwing error on the line form.is_valid() and is showing TypeError at /formpage '>' not supported between instances of 'str' and 'int' And this is happening when I change/add attribute in the botcatcher i.e i add value='joke' Everything else is similar to normal django -
Are coding applications such are android app dev, normal django, python coding and some ethical hacking use many cores or a single core
I am planning to buy a pc, and I am confused between some parts because I don't know what type of hardware likes coding. Like a good 6 core 12 thread would be better, or an 8 core, 16 thread be better. If both are superior overpowered, Would a good 4 core machine with 8 threads do the work? -
how to display the nut,date fields in html template ? how to access foreign key fields in html tamplate?
I have three models in models.py which are Topic,Webpage and AccessRecord. class AccessRecord has foreign key relation with class Webpage i wanna use AccessRecord fields nut,date in html template which is used to display class Webpage content how we can access AccessRecord fields in which has a foreign relation with class Webpage ? this is my model: class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() nut = models.CharField(max_length=56) def __str__(self): return str(self.date) this is my view: def index(request): webpage_list = Webpage.objects.all() web_dict = {"web_records":webpage_list} return render(request,'first_app/index.html',web_dict) this is my template: <body> <h1>Hi, welcome to Django Level Two!</h1> <h2>Here are your access records:</h2> <div class="djangtwo"> {% if web_records %} <table style="float: left"> <thead> <th>Topic Name</th> <th>Site name</th> <th>Url Accessed</th> <th>Date Accessed</th> <th>Webpage nut</th> </thead> {% for web in web_records %} <tr> <td>{{ web.topic }}</td> <td>{{ web.name }}</td> <td>{{ web.url }}</td> <td>{{ web.nut }}</td> <td>{{ web.date }}</td> </tr> {% endfor %} </table> {% endif %} </div> </body> -
Serializer processes one file instead of multiple files?
I am trying to upload multiple images ,but it only takes and uploads one image . Here is the code: class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('images','id','author') def create(self, validated_data): images_data = self.context.get('view').request.FILES article = Article.objects.create(**validated_data) for image_data in images_data.values(): ArticleImages.objects.create(article=article, image=image_data) return article Here is the output when i post multiple images: "images": [ { "id": "6ee3eebe-0b78-4da3-8d18-435db788c1bf", "image": "http://127.0.0.1:8000/images/images/download2_lhbtF5T.png" }, ], "id": "e1534f99-fc48-4892-b11c-8224a84abd15", "author": "4e9ae720-e823-4e2f-83b3-144573257d73",} The problem here is that it posted one image only when i upload multiple images. How can i solve it? -
Django Models inheritance and Serializers
I want to have several models inhering from NoticeModel but currently I only have one: class NoticeModel(SpicerModel): userId = models.ForeignKey( 'account.User', on_delete=models.CASCADE, null=False, blank=False, related_name='notice_user' ) is_read = models.BooleanField(null=False, blank=False, default=False) context = models.CharField(max_length=64, null=False, blank=False, choices=NoticeContext.CHOICES) message = models.CharField(max_length=255, null=False, blank=False, default='') class BookingRequestNotice(NoticeModel): booking_request = models.ForeignKey( BookingRequest, on_delete=models.CASCADE, null=False, blank=False, related_name='booking_event_notice' ) And here are the serialisers: class NoticeModelSerializer(serializers.HyperlinkedModelSerializer): userId = serializers.ReadOnlyField(source='userId.email') class Meta: model = NoticeModel fields = [ 'id', 'userId', 'is_read', 'context', 'message' ] class BookingRequestNoticeSerializer(NoticeModelSerializer): class Meta: model = BookingRequestNotice fields = NoticeModelSerializer.Meta.fields + ['booking_request'] To get all of the Notices, I do: class NoticeList(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request): user = getCurrentUser(request) notices = NoticeModel.objects.filter(userId=user).filter(is_read=False) serializer = NoticeModelSerializer(notices, many=True, context={'request': request}) return Response(serializer.data) The problem is that, since I am using NoticeModelSerializer I am only getting objects with the common fields (I do not get booking_request). How can I return the specific serializers without having to query each one of them individually? -
django template refresh causing session data loss
I am having a problem where I don't seem to be able to identify the root cause. I explain. I have a template where the user make a search and graphs and data make it to the page. From the query value that the user inputed, I need to pass it in a session to another template. here is what the view look like: @method_decorator(login_required, name='dispatch') class SupplierPage2(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) print(query) context = {} #if query and request.method == 'GET': Supplier = supplier2.objects.filter(supplier = query) labels = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] labels = list(labels) default_items = Item2.objects.filter(fournisseur = query).values_list('number_of_sales', flat=True)[:10] default_items = list(default_items) label1s = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] label1s = list(label1s) default_item1s = Item2.objects.filter(fournisseur = query).values_list('number_of_orders_placed', flat=True)[:10] default_items1s = list(default_item1s) context.update({'Supplier' : Supplier, 'labels':labels, 'default_items':default_items,'label1s':label1s, 'default_item1s':default_item1s}) context2 = {'query':query} print("context",context2) request.session['query_dict'] = context2 return render(request, 'Supplier2.html',context) and here is what I get in the log when trying to query 'BOLSEI': BOLSEI context {'query': 'BOLSEI'} start 2020-11-11 14:32:10.714716 start 2020-11-11 14:32:10.715460 None context {'query': None} start 2020-11-11 14:32:20.765804 start 2020-11-11 14:32:20.766572 supplier name {'query': None} it works in a first time, as the query contains a value and all, but then when the … -
Django REST Framework | Ordering by Count from a ManyToMany Field
I'm following a Django REST Framework's Course, but I got stuck trying to set the ordering configuration from django_filters into a ViewSet. ordering = ('-members__count') In the original code of the Course, -members__count is used as query to return total members count, but when I try to use the same syntax I got this error: Error: Cannot resolve keyword 'count' into field. Choices are: auth_token, circle, created, date_joined, email, first_name, groups, id, invitation, invited_by, is_active, is_client, is_staff, is_superuser, is_verified, issued_by, last_login, last_name, logentry, membership, modified, password, phone_number, profile, user_permissions, username Maybe I'm misunderstanding this error, but all these suggested options correspond to Fields from my model. Also, in the Course its indicated that is a query representation format to get the total count of that field, so I'm a little confuse about that. Anyway, this is a resume of my code but you also can see my full detailed code in this repo in case to be required: https://github.com/cadasmeq/comparte_ride/tree/master/cride/circles. View: # Filters from rest_framework.filters import SearchFilter, OrderingFilter from django_filters.rest_framework import DjangoFilterBackend class CircleViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """Circle view set.""" serializer_class = CircleModelSerializer lookup_field = 'slug_name' # Filters filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) search_fields = ('slug_name', 'name') ordering_fields = ('rides_offered', … -
OpenStack Keystone python client, Failed to contact the endpoint at "example:5000" for discovery
I'm new to OpenStack clients and APIs Today I was trying to connect to Keystone, And create a Client object like this: from keystoneauth1.identity import v3 from keystoneclient.exceptions import ClientException from keystoneauth1.session import Session from keystoneclient.v3.client import Client def keystone_client(version=(3, ), auth_url=None, user_id=None, password=None, project_id=None): auth = v3.Password(auth_url=auth_url, user_id=user_id, password=password, project_id=project_id) sess = Session(auth=auth) try: return Client(session=sess) except ClientException as e: print(e) # TODO: USE LOGGING When I try to use the client with admin user credentials, and fetch users list, project list, any of keystone functionality like : client = keystone_client(...) clinet.services.list() client.users.list() First, this line in the client source code in a try-except block encounters exception and logs the bellow warning message LOG.warning('Failed to contact the endpoint at %s for discovery. Fallback ' 'to using that endpoint as the base url.', url) Then finally throws a time out exception, traceback: Failed to contact the endpoint at https://example:5000 for discovery. Fallback to using that endpoint as the base url. Traceback (most recent call last): File "/home/arthur/codes/dir/test/venv/lib/python3.8/site-packages/urllib3/connection.py", line 159, in _new_conn conn = connection.create_connection( File "/home/arthur/codes/dir/test/venv/lib/python3.8/site-packages/urllib3/util/connection.py", line 84, in create_connection raise err File "/home/arthur/codes/dir/test/venv/lib/python3.8/site-packages/urllib3/util/connection.py", line 74, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out During handling of the above … -
Django cannot find lightbox and bootstrap js file. Can someone solve this problem?
[11/Nov/2020 20:13:11] "GET /about HTTP/1.1" 200 3615 [11/Nov/2020 20:13:12] "GET /static/js/lighbox.min.js HTTP/1.1" 404 1677 [11/Nov/2020 20:13:12] "GET /static/js/bootstrap.bundle.min.js.map HTTP/1.1" 404 1716 Here's the relevant part of my base.html for bootstrap: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- Custom --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- LightBox --> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> <title>Real Estate</title> </head> <body> <!-- Top Bar --> {% include 'partials/_topbar.html' %} <!-- Navbar --> {% include 'partials/_navbar.html' %} {% block content %} {% endblock %} <!-- Footer --> {% include 'partials/_footer.html' %} <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'js/lighbox.min.js' %}"></script> <script src="{% static 'js/main.js' %} "></script> </body> </html> Relevant code from settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'real_estate_btre/static') ] And here's how my django project is laid out: admin db.sqlite3 project_name manage.py app_name static - admin, css, js, img template base.html I even ran the python mange.py runserver command as well, but I dont know why … -
How to annotate a queryset with time extracted from timestamp in seconds?
I have model with record_time field which is of IntegerField type. It stores timestamp in second (Unix epoch time). I need to annotate the queryset with time only which should be extracted from record_time. I came up with this so far annotated_qs = WorkerData.objects.annotate( time_e=datetime.fromtimestamp(F('record_time')).time() ) But this results in error (which make sense): an integer is required (got type F) How can I make this to work? -
Django: Ordering by last item in reverse ForeignKey relation
I'm trying to implement a qs.sort_by operation, but I'm not sure how to go about it. Given the following models class Group(models.Model): name = models.CharField(max_length=300) ( ... ) class Budget(models.Model): ( ... ) amount = models.DecimalField( decimal_places=2, max_digits=8, ) group = models.ForeignKey( Group, related_name="budgets", on_delete=models.CASCADE, ) Where each Group has either 0 or > 5 budgets assigned I am trying to sort a Group.objects.all() queryset by the amount of their last (as in, most recently assigned) Budget. I know that if it was a OneToOne I could do something like the following: Group.objects.all().order_by('budget__amount') With ForeignKey relations I was hoping I could do something like Group.objects.all().order_by('budgets__last__amount') But alas, that is not a valid operation, but I am not sure on how to proceed otherwise. Does anyone know on how to perform this sorting operation? (if it is indeed possible) -
NoReverseMatch in django (relative urls with templates)
I tried many of the solutions published but neither of any solution works so that's why I am looking for the solution which helps me I am trying this code:-please tell any error if I did #in my basics_app.urls from basics_app import views from django.urls import path #template tagging app_name='basics_app' urlpatterns=[ path('relative/',views.relative,name="relative"), path('other/',views.other,name="index again"), ] #in my relative.html page <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>relatives url page</title> </head> <body> <h1>welcome to relatives url templates</h1> <a href="{% url 'basics_app:views.other' %}">other page</a> </body> -
How to decode SAMLResponse in Django View?
I am writing a view to create a user in project that has logged into another site. Whenever the user logins to that site he/she gets redirected to url:https://localhost:127.0.0.1:8000/auth/ad/reply/. The site sends me an SAMLResponse from which I want to extract the email address, firstname & lastname for the user. Following is my views.py and urls.py: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def ad_auth(request): response = request.POST.get('SAMLResponse') return HttpResponse(response) urls.py from django.urls import path from .views import * urlpatterns = [ path('auth/ad/reply/', ad_auth, name='ad_auth'), ] Output: PHNhbWxwOlJlc3BvbnNlIElEPSJfOTJmYjAyYTMtN2ZiMC00NjZlLTk0NGItNTQxMjhlOGI5NGM2IiBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAyMC0xMS0xMVQxNDowMDoxMi43NzlaIiBEZXN0aW5hdGlvbj0iaHR0cHM6Ly9sb2NhbGhvc3Q6ODAwMC9hdXRoL2FkL3JlcGx5LyIgeG1sbnM6c2FtbHA9InVybjpvYXNpczp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G5TdGF0ZW1lbnQ+PC9Bc3NlcnRpb24+PC9zYW1scDpSZXNwb25zZT4= How do I extract information from the following SAMLResponse? Thanks in Advance. -
How to change django views into django rest farmework
I'm creating a shopping cart for my project. I created the cart but I got some help for the writing views for it but they give me Django view instead of django rest framework. I'm creating django rest api . I don't know how to change functions into rest framework in the code there is form but in django rest framework we don't create form. can you help me change the view's functions??? actually my problem is in cart_add function in the views.py #cart CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = int(item['price']) * item['quantity'] yield item def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def get_total_price(self): return sum(int(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[CART_SESSION_ID] self.save() views.py def detail(request): cart = Cart(request) return … -
How to Remove Item In the Django Admin for ManyToMany Multiple Select
My Django admin interface is rendering a multiple select, reflecting a many-to-many relationship between Contact and Email. E.g. I can choose multiple emails per contact in the add Contact page. The emails are stored in a separate table that contains just the emails. From the admin interface is it possible to remove one or all of the emails from a Contact that is already created? Is it some setting/argument used in the email admin class? -
Django seed with m2m field
I'd like to make seed data but there is an error : TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use participants.set() instead. is there any way to create dummy data with many to many field? my django-seed managemeny commands file is like below: class Command(BaseCommand): help = "This command creates unions" def add_arguments(self, parser): parser.add_argument( "--number", default=1, type=int, help="How many unions do you want to create?", ) def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() fake = Faker("ko_KR") users = User.objects.all() reviewers = Reviewer.objects.all() seeder.add_entity( Union, number, { "name": lambda x: str(fake.bs().split(" ")[0]) "participants": lambda x: random.choice(users), # this part is problem. I'd like to assign some of users in the field. "reviewer": lambda x: random.choice(reviewers), }, ) seeder.execute() self.stdout.write(self.style.SUCCESS(f"{number} unions created!")) -
head-up notification by using FCM in django
I am implementing head-up notification in django using firebase_admin. To do this, the following code was made because the priority property had to be included, but the head-up notification did not work. What's wrong with my code? message = messaging.Message( notification=messaging.Notification( title=title, ), android=messaging.AndroidConfig( priority='high', data={ 'channel_id': 'Channel Id', 'priority': 'high', 'sound': 'default', 'title': F'{title}', }, notification=messaging.AndroidNotification( priority='high', channel_id='Channel Id', ), ), token=registration_token, ) -
Django ModelChoiceField shows Customers objects(1) etc on list, how do i get it to show name of customers?
models.py class Customers(models.Model): Name = models.CharField(max_length=100) class Staff(models.Model): Name = models.CharField(max_length=100) class Cereals(models.Model): Name = models.CharField(max_length=100) Operator = models.CharField(max_length=100) forms.py class EditCereals(forms.ModelForm): class Meta: model = Cereals fields = ['Name', 'Operator'] widgets = { 'Operator': Select(), 'Name': Select(), } def __init__(self, *args, **kwargs): super(EditCereals, self).__init__(*args, **kwargs) self.fields['Name'] = forms.ModelChoiceField(queryset=Customers.objects.all().order_by('Name')) self.fields['Operator'] = forms.ModelChoiceField(queryset=Staff.objects.all().order_by('Name')) When i run the form 'Name' shows Customers Objects (1), Customers objects (2), etc and same with 'Operator' it shows Staff Objects (1), Staff Objects (2), etc How do i get it to show the actual names, eg Bill, Fred, -
JQuery link onClick event sends image - how to get the link object instead?
I have a dropdown list with image and text on each link item. The data tags are on the link which wraps both text and image. When I click on the text, the jQuery.fn.init gives me the a.dropdown-item as I'd expect, but if the image gets clicked, it gives me the image object instead with the a.dropdown-item as parent. I thought I'd specified the filter correctly in the function call, but obviously not - can anyone point me in the right direction? Dropdown item contruct: <a class="dropdown-item" href="/i18n/setlang/" data-nextpage="/ca" data-languagecode="ca"> <img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Català </a> Script start: $(document).ready(function() { $('#languagelist a').on('click', function(event) { event.preventDefault(); let target = $(event.target); let nextpage = target.data('nextpage'); let url = target.attr('href'); let language_code = target.data('languagecode'); ..... I thought specifying 'a' would just give me the link object, but when the image is clicked that's what comes as target (without data tags obviously). Any help much appreciated :) -
How to django seeding manytomany field
I'd like to seed manytomany field but I can't find the way to solution. Is there any method to make a dummy DB with manytomany field? -
Django and postgresql project
i am new to django and postgresql .So i try to develop sample project and after develop few module try to migrate modle to database.then i got following error. (venv) Asankas-MacBook-Air:venv asankasudesh$ python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 290, in check_consistent_history applied = recorder.applied_migrations() File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 199, in connect conn_params = self.get_connection_params() File "/Users/asankasudesh/Desktop/BurnJ_realState/backend/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 160, in get_connection_params if len(settings_dict['NAME'] or '') > self.ops.max_name_length(): … -
Django NoReverseMatch - Amadeus API
I'm attempting to use an API as part of a project I'm working on and am having some difficulty currently: API https://developers.amadeus.com/self-service/category/air/api-doc/airport-and-city-search API - Python SDK https://github.com/amadeus4dev/amadeus-python Django API Guide https://developers.amadeus.com/blog/django-jquery-ajax-airport-search-autocomplete I have followed the instructions from the above guide; however, I am receiving the following error when trying to render the index page which contains the code: Reverse for 'origin_airport_search' not found. 'origin_airport_search' is not a valid view function or pattern name. Index Template: {% extends "flightfinder/layout.html" %} {% block body %} <div id="mainhomepagediv"> <div class="container-fluid px-0" id="mainhomepagediv"> <div class="row mx-0"> <div class="col-12 px-0"> <img src="https://i.ibb.co/rHYzcyc/Landscape2.jpg" class="img-fluid w-100"> </div> </div> </div> <div> <h1 id="homepageh1">Where are you flying to?</h1> <div id="homepagebox"> <div> <form id="homepageform" method="POST"> <div class="row"> <div class="col"> <label id="homepageformlabel">From</label> <input type="text" class="form-control" placeholder="Origin city" id="inputOrigin"> </div> <div class="col pb-3"> <label id="homepageformlabel">To</label> <input type="text" class="form-control" placeholder="Destination city"> </div> </div> <div class="row"> <div class="col"> <label id="homepageformlabel">Depart</label> <input type="date" class="form-control" placeholder="Origin city"> </div> <div class="col"> <label id="homepageformlabel">Return</label> <input type="date" class="form-control" placeholder="Destination city"> </div> <div class="col-6"> <label id="homepageformlabel">Class</label> <select id="inputState" class="form-control"> <option selected>Economy</option> <option>Business</option> <option>First</option> </select> </div> </div> <div class="row"> <div class="col"> </div> <div class="col-3 pt-3"> <button class="btn float-right" id="homepageformbutton" type="submit">Search flights</button> </div> </div> </form> </div> </div> </div> </div> <script> // Amadeus … -
How to create a queue for python-requests in Django?
REST API service has a limit of requests (say a maximum of 100 requests per minute). In Django, I am trying to allow USERs to access such API and retrieve data in real-time to update SQL tables. Therefore there is a problem that if multiple users are trying to access the API, the limit of requests is likely to be exceeded. Here is a code snippet as an example of how I currently perform requests - each user will add a list of objects he wants to request and run request_engine().start(object_list) to access the API. I use multithreading to speed up requests. I also allow retrying failed API requests via setting a limit on the number of requests for each request object upper_limit. As I understand there should be some queue for API requests. I anticipate there must be a more elegant solution for this, however, I could not find any similar examples. How can one implement/rewrite this for usage with Django? import requests from multiprocessing.dummy import Pool as ThreadPool N=50 # number of threads upper_limit=1 # limit on the number of requests for a single object class request_engine(): def __init__(self): pass def start(self,objs): self.objs={obj:{'status':0,'data':None} for obj in objs} done=False … -
Pass data from django view to Javascript file
I have table data in PostGreSQL which is easily accessed in my Django View. Now I want to pass this data to a javascript .js file whose purpose is to use this data and visualize using d3.js This is what I have tried as an example, but no luck views.py def view_function(request): data = 'test_data' return render(request, 'test.html', context = {'data':data}) test.html <head> </head> <body> <script src="{% static 'test.js' %}">myFunction({{data}})</script> </body> test.js function myFunction(view_data) { console.log(view_data); }