Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery KeyError: 'myproject.tasks.async_task'
When i'm trying to run celery background task then it giving me error: KeyError: 'myproject.tasks.async_task' I'm using python version: 3.8.10, django verion: 4.1.2 , celery version: 5.2.7 and rabbitmq version: 3.8.2 here below screenshot is my project structure: here below is my code for background task: settings.py: CELERY_BROKER_URL = 'amqp://localhost:5672' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' myproject/init.py: from __future__ import absolute_import, unicode_literals from myproject.celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import import os, sys from celery import Celery import django from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py: from __future__ import absolute_import from celery import shared_task from time import sleep import os @shared_task def sleepy(duration): sleep(duration) return None @shared_task def async_task(save_path, name_of_file): sleep(30) completeName = os.path.join(save_path, name_of_file+".html") file1 = open(completeName, "w") toFile = 'test data' file1.write(toFile) file1.close() return 'task complete' views.py def add_product(request): if request.method == 'POST': id_col_data = request.POST.getlist('services') target_col = request.POST.get('target_col') file_name = request.POST.get('file_name') amz_columns_dict = {'id_col': id_col_data, 'target_col': target_col, 'wt_col': None} import os.path save_path = '/home/satyajit/Desktop/' if os.path.exists(save_path): try: from myproject.tasks import async_task name_of_file = file_name status = async_task.delay(save_path, name_of_file) #celery task print('status---->', status) except Exception as e: print('task … -
How to find the index of a queryset after the database is sorted in Django
I am making a leaderboard for my quiz. I made this model: class LeaderBoard(models.Model): name = models.CharField(max_length=200) score = models.DecimalField(max_digits=4, decimal_places=2) This is my code for getting a queryset leaderboad_place = leaderboard.order_by("score").get(name=request.user.username) After I sort my code, I need the index at which my score stands out. I want the index, I mean the location of the queryset after the database is sorted, my code is not working. Please someone help. -
KeyError when I read environment variables while doing makemigrations in django
Context of the problem - I want to migrate from the SQLite database to Postgres. When I makemigrations with Postgres settings which are passed to the settings file with environment variables, I get KeyError; however, another variable from the same file does not cause any problems. My secrets file: SECRET_KEY='secret key value' DB_HOST='db host value' DB_NAME='db name value' DB_USER='db user value' DB_PASS='db pass value' DB_PORT='db port value' My dev.py settings: from app.settings.base import * import os from dotenv import load_dotenv import pprint load_dotenv(os.environ.get('ENV_CONFIG', '')) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS += [ ] MIDDLEWARE += [ ] env_var = os.environ print("User's Environment variable:") pprint.pprint(dict(env_var), width=1) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_HOST'], 'PORT': os.environ['DB_PORT'], } } As you see, I import all the content from my base settings file - app.settings.base, where I use my secret key (in the same way as I read my environment variables for database): SECRET_KEY = os.environ.get('SECRET_KEY', '') I use SQLite in my base.py settings and want to use Postgres in my dev.py. However, when I try to ./manage.py makemigrations --settings=app.settings.dev, I get the error: … -
Trouble Creating a webpage
I'm having trouble creating a view. Down below you can find my view. I keep getting template error. I'm not sure where I went wrong.. class PrivacyView(CreateView): model = Post template_name = 'privacy_policy.html' fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('post_list') def post_list(request, tag_slug=None): posts = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) query = request.GET.get("q") if query: posts = Post.published.filter(Q(title__icontains=query) | Q(tags__name__icontains=query)).distinct() paginator = Paginator(posts, 10) # 10 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'post_list.html', {'posts': posts, page: 'pages', 'tag': tag}) Not sure where I'm going wrong here. If you can provide any help, please do. -
Low Speed Connection for VS Code servers to download extensions
Two days ago, i'd installed Ubuntu and deleted windows, than i install VS Code from Snap Store, now i have a problem with VS Code servers to download extensions. I'm from Iran and we have low speed connection, because of it, I get error for low connection. Is there a way to install extensions for VS Code? any help will gratitude. I get the XHR timeout: undefinedms How can i install VS Code extensions due to low connection speed? -
Django Query "caches" until restarting Server
Django "caches" my query. I realized it after updating my Database. When i run the Function with the Query, it takes some old Data before the Update. When i restart the Server, it works fine again. Do anyone know, how i can solve this issue? I use Raw Queries with the connection-function. (connection.cursor(sql)). In the End of each Query, i close the cursor with cursor.close(). I debugged the Code and found out, that after Updating my Database it takes the old Data until i restart my Server. -
Bootstrap modal, django for loop and model | same value displaying error Fixed
Would you like the modal to display corresponding loop values or messages? When I tried to print the order message in modals, it showed the same message for every order, which led me to realize that every time we call the same modal ID, it shows the same message for every order, -
Django Advanced Filtering for a Queryset that can have many related foreign keys
I am trying to sort a query in django on a model that can have multiple foreign keys. I only want the filtering to apply to one of those keys and I am having a hard time getting it to work. models.py class Post(models.Model): content = models.TextField(max_length=1000) reaction_counts = GenericRelation(ReactionCount, related_query_name='post_reaction_counts') class ReactionType(models.TextChoices): LIKE = 'like', ('Like') DISLIKE = 'dislike', ('Dislike') STAR = 'star', ('Star') LOVE = 'love', ('Love') LAUGH = 'laugh', ('Laugh') class ReactionCount(models.Model): count = models.PositiveIntegerField(default=0) type = models.CharField( max_length=7, choices=ReactionType.choices, ) post = models.ForeignKey(Post, related_name="reaction_count", on_delete=models.CASCADE) In this above example the keyed element (Foreign Key Relation) is ReactionCount for Post. I want to sort the posts by the posts with the most likes, dislikes, stars, loves, laughs, etc. I am trying to do this by doing Post.objects.all().order_by('-reaction_count__type', '-reaction_count__count') This however does not work as there are multiple ReactionCount objects for each post causing the ordering to not work. What I need is for a way to specify that I want the ordering of count to only apply only to Posts with a ReactionCount foreign key of a specific type. Is there a way this can be done by changing how the ordering is done on object Posts? … -
Login Button not redirecting back to home page
I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked. urls.py from django.urls import path from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView urlpatterns = [ path('login/', authView.as_view(),name='login'), path('', pplList.as_view(), name='pplLst'), path('people/<int:pk>', pplDetail.as_view(), name='pplDet'), path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'), path('people-create/', pplCreate.as_view(), name='pplCre'), path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'), ] views.py from distutils.log import Log import imp from .models import People from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView # Create your views here. class authView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('pplLst') class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' class pplCreate(CreateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplUpdate(UpdateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplDelete(DeleteView): model = People context_object_name = 'cnd' success_url = reverse_lazy('pplLst') login.html <h1>Login</h1> <from method="POST"> {%csrf_token … -
Django api update/create request from test case never fired the related methods in serializer
How i can send the UPDATE or CREATE request from my test case? When i run my test case the create/update methods never fired in serializer.. What i misunderstand in Django philosophy? Can someone suggest what i have to do? For example: #View class filesPairView (viewsets.ModelViewSet): serializer_class = filesPairViewSerializer def create(self, request): ... return Response(status=status.HTTP_201_CREATED) #Serializer class filesPairViewSerializer(serializers.ModelSerializer): class Meta: ... def create(self, validated_data): print ("filesPairViewSerializer CREATE") def update(self, validated_data): print ("filesPairViewSerializer UPDATE") #Test case class filesPairViewTestCase(APITestCase): def test_barmi(self): print("test_barmi") url = ('http://127.0.0.1:8000/api/filesPairView/') data ={ #some valid data } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) #urls router.register(r'filesPairView', views.filesPairView ) -
【Django】How to show the results of the columns calculated of child-tables
The purpose is to get averages of the columns of child-tables. My models are "One to Many" relations. (Here, One:Professor, Many:Evaluation) Based on each one-table (Model:Professor), I want to gain each averages of values of columns (Model:Evaluation, column:satisfaction). When showing each averages based on professors, results should be shown based on search engine written in views.py. The problem of following codes is that results cannot be shown in professors/professor_list.html. models.py class Professor(models.Model): college = models.CharField(max_length=50, choices=COLLEGE_CHOICES) name = models.CharField(max_length=50) def __str__(self): return self.name class Evaluation(models.Model): name = models.ForeignKey(Professor, on_delete=models.CASCADE, related_name='evaluation_names', null=True) college = models.ForeignKey(Professor, on_delete=models.CASCADE, related_name='evaluation_colleges', null=True) satisfaction = models.IntegerField(choices=SATISFACTION_CHOICES) def __str__(self): return self.comment views.py from .models import Professor, Evaluation from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q, Avg class ProfessorList(generic.ListView): model = Professor template_name = "professors/professor_list.html" def get_queryset(self): q_word = self.request.GET.get('query') selected_name = self.request.GET.get('name') selected_college = self.request.GET.get('college') if q_word: if selected_name and selected_college: professor_list = Professor.objects.filter( Q(name__icontains=q_word) | Q(college__icontains=q_word) ) s_list = Evaluation.objects.filter( Q(name__icontains=q_word) | Q(college__icontains=q_word) ).annotate(avg_satisfactions=Avg('satisfaction')) elif selected_college: professor_list = Professor.objects.filter( Q(college__icontains=q_word) ) s_list = Evaluation.objects.filter( Q(college__icontains=q_word) ).annotate(avg_satisfactions=Avg('satisfaction')) else: professor_list = Professor.objects.filter( Q(name__icontains=q_word) ) s_list = Evaluation.objects.filter( Q(college__icontains=q_word) ).annotate(avg_satisfactions=Avg('satisfaction')) else: professor_list = Professor.objects.all() s_list = Evaluation.objects.annotate(avg_satisfactions=Avg('satisfaction')) return professor_list, s_list professors/professor_list.html <form action="" method="get" class="#"> … -
Filter model method - Django
I want to filter the Preschooler with their BMI tag but BMI tags are from model method. How do I filter Preschoolers with their BMI tag? models.py from pygrowup import Calculator, helpers class Preschooler(Model): birthday = models.DateField(null=True, blank=True) height = models.FloatField(null=True, validators=[MinValueValidator(45.0), MaxValueValidator(120.0)]) weight = models.FloatField(null=True, validators=[MinValueValidator(1.0), MaxValueValidator(28.0)]) gender = models.CharField(max_length=100, choices=GENDER, null=True) def bmi_tag(self): calculator = Calculator(adjust_height_data=False, adjust_weight_scores=False, include_cdc=False, logger_name='pygrowup', log_level='INFO') try: age_months = int((date.today().year - self.birthday.year) * 12) whfa_value = float(calculator.wfl(self.weight, age_months, helpers.get_good_sex(str(self.gender)), self.height)) if whfa_value > 2.0: return 'ABOVE NORMAL' elif whfa_value >= -2.0 and whfa_value <= 2.0: return 'NORMAL' elif whfa_value >= -3.0 and whfa_value < -2.0: return 'BELOW NORMAL' else: return 'SEVERE' except: pass I would like to filter a preschooler like this: preschooler_normal = Preschooler.objects.filter(bmi_tag='NORMAL') But I am aware that we cannot query against model methods. How can I achieve this? Thanks! -
Login page is not working. Why am I getting redirected to my homepage
Whenever I do /login I get redirected to my homepage which is named pplLst. I think it is something wrong with how I am redirecting but I watching this tutorial (https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s) which I used in my code urls.py from django.urls import path from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView urlpatterns = [ path('login/', authView.as_view(),name='login'), path('', pplList.as_view(), name='pplLst'), path('people/<int:pk>', pplDetail.as_view(), name='pplDet'), path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'), path('people-create/', pplCreate.as_view(), name='pplCre'), path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'), ] views.py from distutils.log import Log import imp from .models import People from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView # Create your views here. class authView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('pplLst') class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' class pplCreate(CreateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplUpdate(UpdateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplDelete(DeleteView): model = People context_object_name = 'cnd' success_url = reverse_lazy('pplLst') -
username=self.kwargs.get('username') returning Not Found: /
Hi I am trying to set the show the items the is only related to a specific user who is currently logged in. I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getting an error of Not Found: / I am not sure why? Here is the models.py: class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) Here is the urls.py: urlpatterns = [ path('', home.as_view(), name='home'), I have tried to have a queryset with the filter to the logged in user but returned back the same error. Here is my views that I have tried class home(LoginRequiredMixin, ListView): model = Item template_name = 'app_name/base.html' context_object_name = 'items' # queryset = Item.objects.filter(user=User) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) print(user) # return Item.objects.filter(user=user) In the home.html I added: {% block head_title %} {{ view.kwargs.username }} | {% endblock %} My question: How can I show the list of items that is only related to the logged in user? what am I doing wrong in here? -
Query in Django to sort in one table based on result of another table
I have two models listing model is: class listing(models.Model): productTitle= models.CharField(max_length=60) description = models.TextField() category = models.ForeignKey(category,on_delete=models.CASCADE,null=True) productPrice = models.FloatField(default=0.0) def __str__(self): return self.productTitle my watchlist model is: item = models.ForeignKey(listing, on_delete= models.CASCADE) watchlist = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item In my index.html I want to show the list item if watchlist attribute is False. Now, my views.py for index.html is as follows: def index(request): if request.user != "AnonymousUser": items= listing.objects.exclude(id=watchlist.objects.filter(user=request.user)) else: items = watchlist.objects.all() context = {'items':items} return render(request, "auctions/index.html", context) I couldn't filter the items on listing models based on the result of watchlist model i.e if watchlist=True then I do not want to render items on index.html. Because, I want to render watchlist items in separate pages. How to query in django if there are two models used? -
I have used the international phone numbers(intlTelInput) in my django app but it seems the form isn't saving the number
So i have basically used the intl-tel-input plugin in my registration form. My webapp is in django. But whenever i submit the form, i get an error which is like the phone_number field is required, even though i have filled in the number. Seems like the form isn't saving the phone number data. How can i solve this? form temlplate looks like this: {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/register.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script> </head> <body> </body> </html> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> </body> </html> </head> <body> <div class="container"> <div class="title">REGISTER </div> <div class="content"> <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="user-details"> <div class="input-box"> {{form.name|as_crispy_field}} </div> <div class="input-box"> {{form.email|as_crispy_field}} </div> <div class="input-box"> <span class="details">Phone number</span> <input id="phone" type="tel" name="phone" /> </div> <div class="input-box"> {{form.address|as_crispy_field}} </div> <div class="input-box"> {{form.nin|as_crispy_field}} </div> <div class="input-box"> {{form.LC1_letter|as_crispy_field}} </div> <div class="input-box"> {{form.National_Id|as_crispy_field}} </div> <div class="input-box"> {{form.password1|as_crispy_field}} </div> <div class="input-box"> {{form.password2|as_crispy_field}} </div> </div> <div class="form-check d-flex justify-content-center mb-5"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3c" /> <label class="form-check-label" for="form2Example3"> First agree with all statements in <a href="#!">Terms of service</a> to continue </label> </div> <div class="button"> <input type="submit" value="Register" href="#"> <input type="submit" value="Login" style="margin-left: … -
Django drf group by a model date field
I have an attendance model with the below structure class Attendance(models.Model): class PRESENCE(models.TextChoices): P = "P", "Present" A = "A", "Absent" L = "L", "On leave" user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_attendance", blank=False, null=True) leave_reason = models.CharField(max_length=355, blank=True, null=True) date = models.DateField(blank=False, null=True, auto_now=False, auto_now_add=False, editable=True) presence = models.CharField( choices=PRESENCE.choices, max_length=255, blank=False, null=True) attendance_taker = models.ForeignKey( User, on_delete=models.CASCADE, related_name="attendance_taker", blank=False, null=True) def __str__(self): return f'{self.user}' class Meta: verbose_name = _("Attendance") verbose_name_plural = _("Attendance") constraints = [ UniqueConstraint( fields=('user', 'date'), name='unique_attendance_once_per_date') ] I would like to create a table with the list of dates but simply using a generic view wouldn't cut it since different users will have similar dates, I need a way to merge the same dates into one and group the attendance instances that have similar dates. -
Insert i18n language into the request
I'm using the i18next lib, together with react in my front, and i intend to pass the information of my current language to my api through every request. I have a axios client wrapped in a constant that i use in my whole application, like this: ` const client = axios.create({ baseURL: CONSTANTS.API.BASE, headers: { "Content-Type": "application/json", }, timeout: TIME_OUT, }); ` I'd like to know if there some easy way to do this, and then get the language information in the back. By the way, i'm using Django REST Framework in my api. I tried to simply declare a variable into the headers in the client, just for test, but i couldn't get the value in the request in the api -
How to override `Model.__init__` and respect `.using(db)` in Django?
I have the following code: print(f"current database: {self.db}\ninfusate from database: {infusate._state.db}\ntracer from database: {tracer._state.db}") FCirc.objects.using(self.db).get_or_create( serum_sample=sample, tracer=tracer, element=label.element, ) That is producing the following output and exception: current database: validation infusate from database: validation tracer from database: validation Validating FCirc updater: {'update_function': 'is_last_serum_peak_group', 'update_field': 'is_last', 'parent_field': 'serum_sample', 'child_fields': [], 'update_label': 'fcirc_calcs', 'generation': 2} Traceback (most recent call last): File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 581, in get_or_create return self.get(**kwargs), False File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( DataRepo.models.fcirc.FCirc.DoesNotExist: FCirc matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/views/loading/validation.py", line 91, in validate_load_files call_command( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/management/commands/load_animals_and_samples.py", line 134, in handle loader.load_sample_table( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/utils/sample_table_loader.py", line 426, in load_sample_table FCirc.objects.using(self.db).get_or_create( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 588, in get_or_create return self.create(**params), True File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 451, in create obj = self.model(**kwargs) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/models/maintained_model.py", line 430, in __init__ super().__init__(*args, **kwargs) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 229, in __set__ raise ValueError('Cannot assign "%r": the current database router prevents relation between database "%s" and "%s".' % (value, instance._state.db, value._state.db)) ValueError: Cannot assign "<Tracer: … -
execute django raw querie using ilike sentence
I got a query that compared with ORM is much more simpler using direct sql, Trying to execute it directly is in the part related to the ilike clause, I tried different ways but all fails (added a shorter query just to exemplify the problem) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike '%%%s%%'", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike %%%s%%", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike %s", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike '%%%s%%'", ["jan"]) the error: LINE 1: SELECT cc.name FROM customer cc WHERE name ilike '%'jan'%' LINE 1: SELECT cc.name FROM customer cc WHERE name ilike %'jan'% LINE 1: SELECT cc.name FROM customer cc WHERE name ilike 'jan' LINE 1: SELECT cc.name FROM customer cc WHERE name ilike '%'jan'%' -
djangosaml2idp Issue with Importing Expired Certificates
was interrupted by the expiration of the service provider. Is there any way to fix this part? I couldn't touch it because I didn't know at all. -
Django: could not convert string to float: ''
I am trying to write a function to display all items in cart, but it keeps showing this error could not convert string to float: " and i cannot tell where the problem is coming from? i have tried chaging the float(...) method to int(...). what the possible error? def cart_view(request): cart_total_amount = 0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_amount += int(item['qty']) * float(item['price']) return render(request, "core/cart.html", {'cart_data':request.session['cart_data_obj'], 'totalcartitems': len(request.session['cart_data_obj']), 'cart_total_amount':cart_total_amount}) else: return render(request, 'core/cart.html', {'cart_data':'','totalcartitems':0,'cart_total_amount':cart_total_amount}) -
Unable to connect Oracle 19 database into Django container with Oracle database running into another container
I am pretty new on Docker and Iam trying to run a Django application with Oracle 19 database with Docker thanks to a docker-compose.dev.yml file. The problem is that my database container works but not my Django application which fails to connect to database. Here's the file : version: "3.9" services: oracle-database: image: icsvaccart/oracle19c:latest volumes: - ./data/db:/opt/oracle/oradata ports: - "1521:1521" - "5500:5500" django-back-end: build: . volumes: - .:/app ports: - "8000:8000" env_file: - pythonPOC/.env depends_on: - oracle-database Then I ran the command docker compose -f docker-compose.dev.yml up --build and after a couple of minutes, the process ends with the following complete logs : (venv) PS D:\Vianney\Documents\Projets\pythonPOC> docker compose -d -f docker-compose.dev.yml up --build Building 439.7s (11/11) FINISHED [internal] load build definition from Dockerfile 0.0s transferring dockerfile: 32B 0.0s [internal] load .dockerignore 0.0s transferring context: 34B 0.0s [internal] load metadata for docker.io/library/python:3 1.5s [auth] library/python:pull token for registry-1.docker.io 0.0s [1/5] FROM docker.io/library/python:3@sha256:fc809ada71c087cec7e2d2244bcb9fba137638978a669f2aaf6267db43e89fdf 0.0s [internal] load build context 0.1s transferring context: 16.98kB 0.1s CACHED [2/5] WORKDIR /app 0.0s CACHED [3/5] COPY requirements.txt /app 0.0s CACHED [4/5] RUN pip install -r requirements.txt 0.0s [5/5] COPY . . 417.3s exporting to image 17.7s exporting layers 17.7s writing image sha256:f7909ee3f0cf378b86a4c6d64bc7c37ad69b1014cfea06b345cb9345e6310365 0.0s naming to docker.io/library/pythonpoc-django-back-end 0.0s … -
How to serve response in django then down the server
I need a advice I want create a path in django for example /stop-server When somebody send a request to /stop-server server return a response and then become killed What's your proposal?......... -
Tests for Django Channels/WebSockets
what is the good & easy way to test consumers.py in Django Channels (websocket endpoints). I've seen https://channels.readthedocs.io/en/stable/topics/testing.html but to me that's kinda too complicated a bit and not sure if that's I want. For example I haven't find info about how to pass user to scope for proper consumer testing or how to make my custom middleware for authentication. Maybe there's someone "advanced" at django channels and you've tested consumers. If yes, please share the way you did it, because I really can't google how to test this stuff. I have already reached this stage: class TestConsumer(TestCase): async def test_consumer(self): communicator = WebsocketCommunicator(UserLocationConsumer.as_asgi(), path='/ws/user-track-location')) connected, subprotocol = await communicator.connect() self.assertTrue(connected, 'Could not connect') await communicator.send_json_to(content='test') result = await communicator.receive_json_from() print(result) await communicator.disconnect() That allows me to enter my consumer BUT inside consumer there is no scope, because no authorization where passed, so I can't fully cover my consumer's functionality with tests: ERROR: test_consumer (gps.tests.test_consumers.TestConsumer) self.user_id = self.scope['user'].id KeyError: 'user'