Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass Array using AJAX in Django
I have an array called metrics and im trying to pass it to backend with AJAX but Im only getting the last values of the array 7,8,9 . I want to pick up the whole array .Any idea how? Any help is appreciated. html var metrics = [ [1,2,3], [4,5,6], [7,8,9], ]; $.ajax({ type : 'GET' , url : "...", data : {"metrics[]": metrics }, }) views.py def Sensor_Metrics(request): if request.is_ajax and request.method == "GET" : metrics = request.GET.get("metrics[]") print(metrics) return JsonResponse({"error": ""}, status=400) -
Opayo (Sagepay): how to implement withdrawal function for users?
We built online-store using Python/Django (DRF), Opayo for checkout and set up virtual wallets for our customers. We also want to implement a withdrawal function so that our customers be able to send their funds from virtual account to real bank account or PayPal wallet. Unfortunately, I don't see relevant guide/info in Opayo docs. Could you give some advice on where to search or at least tell me if it's possible? -
Django celery apply_async running multiple times
Using Django 2.2 and Celery 4.4.7. Using AWS ECS to deploy the application and celery and using SQS as message broker. In the ECS task definition, using the following command to start the celery task ["celery","worker","-A","qcg","-l","info","--concurrency","4"] There are 8 tasks running for the celery service and 4 tasks for the application When using apply_async to delay a task send_webhook_task.apply_async( kwargs={ 'tracking_id': tracking_data.id, 'hook_url': hook.url }, countdown=60 ) The above task is executed after 60 seconds, but it executes for 3-4 times and the same data is sent multiple times. Same when using delay() is executed only once send_webhook_task.delay( tracking_id=tracking_data.id, hook_url=hook.url ) Why apply_sync is executing multiple times with the above setup? -
How can i get id/pk from a url
I am a Django newbie trying to create a flight booking view that will take logged in user id and the pk/id of the selected flight so i can combine the data and populate a ticket for the corresponding user and the selected flight. I don’t have any idea how to make this work, i have tried searching for answers and no luck. Any kind of help would be appreciated. -
Django unicorn name 'Kwargs' is not defined
recently i start learning django unicorn all was going good i start creating a cart with unicorn by i ended with error enter image description here name kwargs is not defined my cartview.py class CartviewView(UnicornView): user_product: QuerySetType[UserItem] = None user_pk: int def __init__(self, *args, **kwargs): super().__init__(**kwargs) #calling super is required self.user_pk = Kwargs.get('User') self.user_product = UserItem.objects.filter(user=self.user_pk) My index.html {% extends 'baseapp/base.html'%} {% load unicorn %} {% block content %} {% unicorn 'cartview' user=request.user.pk product=product %} {% endblock %} and my cartview.hmtl <div> <div class="section"> {% for product in product %} <div class="columns"> <div class="column is-6"> <div class="box is-flex "> <div class="field"> <label class="label">{{product.name}}</label> <div class="control"> <span class="title is-4">{{product.price}}</span> </div> </div> </div> </div> </div> <div class="columns"> <div class="column is-6"> <h1 class="title is-3 is-text-centered">Cart</h1> {% if user_product%} {% for product in user_product%} {{product}} {% endfor %} {% else %} <P>Ther is no product added yet</P> {% endif %} </div> </div> </div> </div> -
Django error message doesn't declare an explicit app label
I am getting this error message while trying to add a model form to my django site. It was all working fine before I added the form code and now I cannot access the site. Any help on how to fix it appreciated. I need the form to save to the database. Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 448, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in … -
Django test api while api is running in dev environment
I have a Django project in Dev Env. I can run the api with 'python manage.py runserver' I can run the tests with 'python manage.py rest api.tests' But only one at a time. When I run tests the api is not running. How can I run tests when api is running? -
how to integrate advanced reports with Django App (python)?
I'm currently developing a Django App (python) and i need to use reports with advanced sql queries (sql with group by, order by, case .. when .. then) . -
How do I write test cases with local permission_classes set in viewsets in DRF?
everytime I run the Test an assertionError is thrown 403!=200, which is natural, because somehow its is failing to log in with a user or super_user. what I need to know is how do authenticate here to run the test with no failure. ##views.py class EmployeeDetailsViewSet(viewsets.ModelViewSet): permission_classes= [IsAuthenticated] queryset= EmployeeDetail.objects.all().order_by('employeeCode') serializer_class= EmployeeDetailsSerializer class SalaryDetailsViewSet(viewsets.ModelViewSet): permission_classes = [IsAdminUser] queryset= SalaryDetail.objects.all().order_by('salaryCode') serializer_class= SalaryDetailsSerializer ##settings.py REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'] } ##test.py def testSalaryDetails(self): client = APIClient() client.login(username='admin', password='qwefghbnm') response = client.get('/salaryDetails/') self.assertEqual(response.status_code, 200) self.client.logout() -
docker exec command with subprocess in Python program
I want to create a docker container through the subprocess function in the python program, and enter the container to execute the corresponding script to obtain the returned results. But I use. Subprocess.Popen function executes docker exec MySQL /bin/bash /home/test sh 'select * from userinfo;' Error 2002 (HY000): can't connect to local MySQL server through socket 'var / run / mysqld / mysqld sock'(2)。 Using the same command, I can run correctly at the terminal without reporting errors and get the desired results. Why? -
How can I use a string in django as html? which includes djangos inline html
For example: str = "<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}" I know that the |safe filter exists, but that doesn´t work for inline html, only for html. Same here for the autoescape off. I would be happy if somebody could help me :D -
i have removed a tables column named stock.but when i am appliying migration it causes error?how can i rectify
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration figgyapp.0001_initial dependencies reference nonexistent parent node ('figgyapp', '0003_remove_product_s tock') -
How to show sorted list in form in django
This works but dont know how to show in my page sorted(glob.glob(''+dvcs.hostname+''), key=os.path.getmtime) I dont know what should I do. Here is my code class Recentbackups(View): @staticmethod def get(request, pk): dvcs = Device.objects.filter(pk=pk) form = DeviceForm() context = {'dvcs': dvcs, 'form': form} return render(request, 'Recentbackups.html', context) -
Run Django Celery Periodically
I have the task file tasks.py @shared_task def add(x, y): print(x + y) return x + y and celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # setting the Django settings module. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onboarding.settings') app = Celery('onboarding',broker='pyamqp://guest@localhost//') app.config_from_object('django.conf:settings', namespace='CELERY') # Looks up for task modules in Django applications and loads them app.autodiscover_tasks() app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-1-seconds': { 'task': 'tasks.add', 'schedule': 30, 'args': (16, 16), }, } when i run celery -A onboarding beat and celery -A onboarding worker Seems it is adding tasks but it is not executing the tasks required. What can be the problem -
routes to manage groups and permissions with rest api endpoints in django
What is the best way to manage groups and permissions with django-rest-framework API endpoints? I want to have all functionalities that admin panel has to manage groups and permissions, in some API routes. Thanks in advance -
Django Datefield attributes
i have Datefield in my model where it should save when created and updated what should be the attributes inside? models.py class Mymodel(models.Model): edited = models.DateField(*what should be the attributes here*) -
search with 2 field in generic api view
Do you know how can I search with 2 fields with 'and' conditions? I mean in the below code I need to search'search_fields' with symbol name and time_frame,(both conditions together not only one of them) class RegisterSymbolViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = SymbolValidationSerializer filter_backends = [filters.SearchFilter] search_fields = ['^symbol','^time_frame'] queryset = RegisterSymbol.objects.all() -
the server responded with a status of 503 (Service Unavailable)
I've built a django application for about 5 months ago, it works fine till yesterday, but now it sometimes shows this error message: The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. server: ubuntu version: 18 LTS server provider linode Thank you for any help -
Can't login into admin URL on production with Django 4
Can't seem to login into Django admin URL on my production but it works fine on my local. For context, currently my site does not have SSL. Debug is set to False as well. This was working prior to Django 4 upgrade (was previously on Django 3.08) mysite.com/admin keeps redirecting to mysite.com/admin/login/?next=/admin/ with a 500 error. -
Django ModelMultipleChoiceField
I'm newbie in Django and making my first real application. I need some advice in building page with three dependent model multiple choices fields or another similar interface. The goal is to build a page where user can choice target folders from three-level folders structure and save user selection in DB for further use. I want to crate three list contains L1, L2 and L3 dirs names each, where user selects any available dirs. If user changes selection on L1 dirs list it need to automatically update L2 dirs list, the same rule in L2 dirs list for L3 dirs list. Due to security restrictions I can't access filesystem with dirs from Django server. But it can be accessed from user PC. I guessed to manually load dirs structure, because it is rarely changes. The question is how to embed those lists at page and make them dependent. I guess it must be three model multiple choices fields with some JavaScript event to update them. But I need example how to build it. May be there is another better way than use ModelMultipleChoiceField... Example of dirs - tree structure: |-L1_Dir#1 -|-L2_Dir#A-|-L3_Dir#P | | |-L3_Dir#Q | | | |-L2_Dir#B-|-L3_Dir#R | |-L3_Dir#S … -
Getting Django query list based on another table
I have models as below: Group Model class Group(model.Model): name = models.CharField(max_length=100, null=True, blank=True) GroupMember Model class GroupMember(model.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_member_group') member = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_member_user') Course Model class Course(model.Model): name = models.CharField(max_length=100) GroupCourse Model class GroupCourse(model.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='course_group') course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='group_course') CourseStaff Model class CourseStaff(model.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='course_staff_course') staff = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_staff_user') What I want is to get All the GroupMembers that does not exists in CourseStaff model for a specific course. For example: I have total 5 members in Group A Member 1 Member 2 Member 3 Member 4 Member 5 I have total 2 course in Group A Course 1 Course 2 Course 1 has two members: Member 1 Member 2 Course 2 has two members: Member 2 Member 3 What I want is to get Member 3-5 from GroupMember when querying for Course 1 Also get Member 1,4, 5 from GroupMember when querying for Course 2 How can I do that? Thanks -
Django: Query Group by Month with filling empty months
Trying to group by sales by month like below which works perfect monthbased = any_queryset.annotate(sales_month=TruncMonth('BidDate') ).values('sales_month' ).annotate(sum=Sum(F('Quantity')*F('SellPrice')) ) My question is about the months with no sales. I am using this result in a bar chart and if any month does not have sales then those months will not appear in the chart I want to show empty months with zero values. I did it like this # convert queryset to list of dicts monthbased_list = [{'sales_month': x['sales_month'], 'sum': x['sum']} for x in monthbased] # fill empty year and months for i in range(datetime.now().year-2, datetime.now().year+1): for j in range(1,13): if not any(d['sales_month'].month == j and d['sales_month'].year == i for d in monthbased_list): monthbased_list.append({'sales_month': datetime(i,j,1), 'sum': 0}) Is there a better way to do it? -
Cannot import is_safe_url from django.utils.http , alternatives?
I am trying to update my code to the latest Django version, The method is_safe_url() seems to be removed from new version of Django (4.0). I have been looking for an alternative for the past few hours with no luck. Does anyone know of any alternatives for the method in Django 4.0? -
Interface for DjangoFilterConnectionField
I have two classes class RegisteredUser(graphene.ObjectType): class Meta: interfaces = (BaseClient, ) name = graphene.String() group = graphene.String() policy = graphene.Int() event = graphene_django.filter.DjangoFilterConnectionField(AuthEvent, max_limit=15) Then I also have another class for users that have not signed up class NonRegisteredUser(graphene.ObjectType): class Meta: interfaces = (BaseClient, ) name = graphene.String() source = graphene.Int() event = graphene_django.filter.DjangoFilterConnectionField(NonRegisteredEvent, max_limit=15) And finally we have BaseClient class which is the common interface for both of the above classes class BaseClient(graphene.Interface): name = graphene.String() events = graphene_django.filter.DjangoFilterConnectionField('NotSureWhatToAdd', max_limit=15) @classmethod def resolve_type(cls, instance, info): if instance.type == 'RegisteredUser': return RegisteredUser return NonRegisteredUser Now everything works fine if I query "name" field but not sure how do I make 'events' field work since both have different DjangoFilterConnectionField. -
Cosine similarity query in elasticsearch
I have documents saved inside an index x which is inside another index y ie Maker/Ford and Maker/BMW, here documents are saved inside Ford which is inside Maker. Similarly for BMW. I need to find cosine similarity. I tried scripts, { "query": { "script_score": { "query": { "match_all": {} }, "script": { "source": "Ford['_vector'].size() == 0 ? 0 :cosineSimilarity(params.queryVector,'_vector')+1", "params": { "query_vector": [ 0,1,12,4 ] } } } } } { "script_score": { "query": {"match_all": {}}, "script": { "source": "cosineSimilarity(params.query_vector, '_vector') + 1.0", "params": {"query_vector": query_vector} } } } None of them really worked. What would be the solution?