Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py runserver takes forever
I recently transfered my django project from a windows computer to a mac. The project is made up of 5 apps. Some are standalone while some has import from other apps. When I run python manage.py runserver the app never comes out of performing systems checks. I have noticed that this problem is majorly due to two apps out of the 5. This is becuase when I comment the url path from the projects main urls model the manage.py runs file. But once I uncomment it, the problems starts again. I have checked my paths and I belive the are accurate. Is there a what I can make the runserver command show me some output. Thank you for your help. -
Pre-Commit throwing Errors on Missing whitespace after ":"
I used the same pre-commit configuration on my windows pc, but since i switched to a macos, whenever i run a pre-commit on my python-django project, i get unexpected errors like missing whitespace after colon, even when the said colon iS at the end of a class definition or function definition or colons present in a url string, i know from the docs that a space is not needed after this cases, i believe this has something to do with the os switch or some misconfiguration with pre-commit on my new pc, Python VERSION: 3.12 pre-commit configuration exclude: "^docs/|/migrations/" default_stages: [commit] repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer # - id: check-yaml - repo: https://github.com/asottile/pyupgrade rev: v3.3.1 hooks: - id: pyupgrade args: [--py310-plus] - repo: https://github.com/psf/black rev: 22.12.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 rev: 6.0.0 hooks: - id: flake8 args: ["--config=setup.cfg"] additional_dependencies: [flake8-isort] # sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date ci: autoupdate_schedule: weekly skip: [] submodules: false Sample Error Message config/settings/production.py:109:21: E231 missing whitespace after ':' Acutal line pointed at in the code STATIC_URL = f"https://{aws_s3_domain}/{AWS_STORAGE_BUCKET_NAME}/payment/static/" Can anyone … -
For loop for users in Django
GoodEvening I have written a web app that list shooters scores. I have all of that working. I added a new app that will list the shooter average scores. But I can't figure out how to loop though the current users. I have use the built in User model and built another model call Scores for the individual scores. Sorry to have to ask for help. But i work on this for hours. Here is the model Scores from django.conf import settings from django.db import models from django.db.models import Avg rifle_type_choices = {("B", "B"), ("S", "S")} optic_type_choices = {("O", "O"), ("S", "S")} range_distance_choices = {("50", "50"), ("100", "100")} class Scores(models.Model): date = models.DateField() match_score = models.IntegerField() xcount = models.IntegerField() rilfe_type = models.CharField(max_length=1, choices = rifle_type_choices, default = "B") optic_type = models.CharField(max_length=1, choices = optic_type_choices, default = "O") range_distance = models.CharField(max_length=3,choices = range_distance_choices, default = "100" ) username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return f' {self.username} {self.date}' Here is the view for the Average app # average/views.py from django.http import HttpResponse from django.template import loader from scores.models import Scores from django.db.models import Avg def index(request): template = loader.get_template("average.html"); context = { 'avg50': Scores.objects.filter(range_distance="50").aggregate(Avg("match_score")), 'avg100': Scores.objects.filter(range_distance="100").aggregate(Avg("match_score")), 'scores_list': Scores.objects.values('username') } return HttpResponse(template.render(context, request)) Here … -
Filtering select field options in Django Rest Framework
How can brand and type fields filter options based from the existing asset category chosen, and unit model filtering options based from the selected brand? This is my JS: $(document).ready(function() { const assetId = $('#asset_id').val(); axios({ method: 'get', url: `/api/assets/assets/${assetId}`, }).then(function(res) { let data = res.data; $('#id_name').val(data.name); $('#id_property_number').val(data.property_number); $('#id_serial_number').val(data.serial_number); $('#id_date_acquired').val(data.date_acquired); getAllBrand(data.brand) getAllUnitModel(data.unit_model) getAllStatus(data.status) getAllType(data.type) getAllUser(data.user) getAllDepartment(data.department) getAllArea(data.area) axios.get(`/api/assets/asset_details/`,{ params:{ asset: data.id } }).then(function(res) { const dataObj = res.data; const $formWrapper = $('#form_field_wrapper').empty(); dataObj.forEach(obj => { const assetObj = obj.asset_field; const fieldId = `id_${assetObj.field_name}`; const feedbackId = `feedback_${assetObj.field_name}`; const requiredInfo = obj.asset_form.is_required ? '<span class="text-danger">*</span>' : ''; const requiredClass = obj.asset_form.is_required ? 'form-required' : ''; switch(assetObj.field_type) { case 'radio': break; case 'checkbox': break; case 'text': var fieldData = new Object(); fieldData.assetFormId = obj.asset_form.id; // form id fieldData.assetFieldId = assetObj.id; // asset field id fieldData.assetDetailId = obj.id; // asset field id $formWrapper.append(` <div class="col-6 m-0"> <div class="form-floating mb-3"> <input type="text" class="form-control asset-form-field ${requiredClass}" id="${fieldId}" placeholder="${assetObj.field_label}" value="${obj.value}"> <label for="${fieldId}">${assetObj.field_label} ${requiredInfo}</label> <div class="invalid-feedback" id="${feedbackId}"></div> </div> </div> `); $(`#${fieldId}`).data(fieldData); break; case 'select': let fieldOptions = JSON.parse(assetObj.field_option); var fieldData = new Object(); fieldData.assetFormId = obj.asset_form.id; // form id fieldData.assetFieldId = assetObj.id; // asset field id fieldData.assetDetailId = obj.id; // asset field id $formWrapper.append(` <div class="col-6 m-0"> … -
How to resolve: Django make migrate not running in AWS ECS from Dockerfile
I have a Django project that runs in a Docker container. Locally when I have updated the project to include changes to the model, I have run python manage.py makemigrations and python manage.py migrate within the docker container. In particular, I would enter the container from the terminal and run python manage.py makemigrations and python manage.py migrate to execute the changes. This worked locally. However, now that I have pushed my code to production (AWS ECS) for some reason manage.py is not running to update the existing database. There is no evidence that manage.py is running at all, even though it is in my entrypoint.sh script. Are there any additional configs that I need to set up either in the Dajngo project or in AWS ECS to be able to run migrations in the AWS ECS environment? The project is otherwise running fine, so the docker container is up, just python manage.py migrate is never run. I have included the Dockerfile below for reference: FROM python:3.11-slim-bookworm ENV uid=1000 ENV gid=1000 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV TZ=UTC ENV USER=app_user UID=$uid GID=$gid RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update \ && apt-get install -y … -
AWS Beanstalk container with Django app can't connect to RDS DB but it accessible from EC2 server and anothe container
My MySQL DB and EC2 instances where Elastic Beanstalk is running are in different VPCs. So I connect to DB via public IP and allow inbound connection in DB SG for my EC2 instance. But I still receive the error Access denied from DB. I tried to connect directly from that instance and even connect from another container(my Django app is crashing) and it works well. The strange things - everything works fine for one env, and doesn't work for another -
Custom authenticate function not working as expected
I have made my own backend for authenticating users with either an email or username. Now I have created a new class view in my app and im trying to authenticate a user. here is a fragment of my class view def post(self, request): dataRecieved = request.data user = authenticate(request, login = dataRecieved["login"], password = dataRecieved["password"]) return Response(user.username) try: login(request, user) return Response(status=200) except Exception: return Response("di[a") the authenticate here is from django.contrib.auth and inside it calls my authenticate function from my custom backend. I haven't changed anything here try: user = backend.authenticate(request, **credentials) except PermissionDenied: # This backend says to st.... Now here is my backend authenticator function def authenticate(self, login=None, password=None, **kwargs): if login is None or password is None: return None try: users = UserModel.objects.filter(username=login) | UserModel.objects.filter(email=login) except UserModel.DoesNotExist: return None else: for user in users: if user.check_password(password) and self.user_can_authenticate(user): return user and when i try to return the user all i get is a NoneType, what should I do? I have tried returning strings within both authenticate functions but it always comes out as a NoneType, im 100% its something wrong with my authenticate function but i have no clue what's wrong. -
i am trying to fetch data from my mongodb Database with django but keep getting : the JSON object must be str, bytes or bytearray, not OrderedDict
so i have an employes collection with a bunch of data that is in this format : { "_id": { "$oid": "511d0a9f181b16509ae5f7dd" }, "nom": "Leberre", "prenom": "Stephanie", "anciennete": 1, "adresse": { "numero": 79, "codepostal": 9500, "ville": "Toulouse", "rue": "Jean Moulin" }, "tel": 559608352, "prime": 1500 }, here is the models.py : from django.db import models class Employee(models.Model): nom = models.CharField(max_length=100) prenom = models.CharField(max_length=100) anciennete = models.IntegerField() adresse = models.JSONField() tel = models.CharField(max_length=20, blank=True, null=True) prime = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.nom}, {self.prenom}" serializers.py : from rest_framework import serializers from .models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' and finally views.py : from rest_framework.response import Response from rest_framework import generics from .models import Employee from .serializers import EmployeeSerializer class EmployeeListView(generics.ListAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer def list(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(serializer.data) i keep getting :"the JSON object must be str, bytes or bytearray, not OrderedDict ". i dont need a very specific solution, just any solution works even if it involves modifying all the files mentioned above -
Is there a solution to combine a multi tenancy django project and google authentication
I am facing a problem in my django project, i need to set up two type of users, 1- guest users ( log in with google authetication ) 2- partner users ( log in with their own e-mail but as multi tenant) if i run the project with only one them it works fine, but not together, settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SITE_ID=2 SHARED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'tailwind', 'theme', 'sweetify', 'taggit', 'django_tenants', 'api', 'tenantapp', ] TENANT_APPS = [ # your tenant-specific apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'tailwind', 'theme', 'sweetify', #'django_browser_reload', 'taggit', 'django_tenants', 'agency', ] INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE" : [ "profile", "email" ], "AUTH_PARAMS" : { "access_type":"online" } } } # possible options: 'sweetalert', 'sweetalert2' - default is 'sweetalert2' SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2' TAILWIND_APP_NAME = 'theme' INTERNAL_IPS = [ "127.0.0.1", ] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #"django_browser_reload.middleware.BrowserReloadMiddleware", … -
Error when im trying to install psycopg2 :(
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 Failed to build psycopg2 ERROR: Could not build wheels for psycopg2, which is required to install pyproject.toml-based projects Python 3.12 requirements.txt: asgiref==3.2.10 Django==3.1 pytils==0.4.1 pytz==2022.7.1 sqlparse==0.4.3 I have read all the other articles on this topic. Installed vs build tools c++ -
How to implement Django's ConditionalGetMiddleware to compare `If-Modified-Since` in the req. headers with `Last-Modified` in the res. headers?
I'm trying to implement conditional caching using django.middleware.http.CondtionalGetMiddleware. I'm able to correctly return 304/200 if I provide an If-None-Match with ETag value in the request headers. However, I'm unable to do so when I provide If-Modified-Since in the request headers. I believe it is because my response does not contain a header called Last-Modified, which ConditionalGetMiddleware seems to be requiring, as follows: class ConditionalGetMiddleware(MiddlewareMixin): """ Handle conditional GET operations. If the response has an ETag or Last-Modified header and the request has If-None-Match or If-Modified-Since, replace the response with HttpNotModified. Add an ETag header if needed. """ def process_response(self, request, response): # It's too late to prevent an unsafe request with a 412 response, and # for a HEAD request, the response body is always empty so computing # an accurate ETag isn't possible. if request.method != "GET": return response if self.needs_etag(response) and not response.has_header("ETag"): set_response_etag(response) etag = response.get("ETag") last_modified = response.get("Last-Modified") last_modified = last_modified and parse_http_date_safe(last_modified) if etag or last_modified: return get_conditional_response( request, etag=etag, last_modified=last_modified, response=response, ) return response def needs_etag(self, response): """Return True if an ETag header should be added to response.""" ... Ideally, I would like Last-Modified to have a value similar to ConcernedModel.objects.latest("updated_at"). One way that … -
Django Custom User model AbstractBaseUser and Proxy models. Password is not hashed or set properly
When user is registered with a form or in admin the password is not hashed, as with the superuser. Any help appreciated. I cannot seem to figure this out. Oh, I am not able to login either. Exept from superuser. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'theapp', 'rest_framework', 'userapp', ] . . . AUTH_USER_MODEL = "userapp.UserAccount" model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email or len(email) <= 0: raise ValueError("Email field is required !") if not password: raise ValueError("Password is must !") user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): class Types(models.TextChoices): STUDENT = "STUDENT", "student" TEACHER = "TEACHER", "teacher" type = models.CharField( max_length=8, choices=Types.choices, default=Types.TEACHER) email = models.EmailField(max_length=200, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) phone_no = models.CharField(max_length=10) # special permission which define that # the new user is teacher or student is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = "email" # defining the manager for the UserAccount model objects = UserAccountManager() def … -
testing Profile creation after user registration with uninttest
i use signals for create profile after user register, Manually the test and def test__create_profile is correct, but def test_profile_created_automate is false. this is my test: class Testprofile(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user(email='hosein@gmail.com', username='hosein', password='admin') def test__create_profile(self): response = self.client.post(reverse('users-front:create_profile'), data={ "user": 1, 'age': 10, "first_name": "string", "last_name": "string", "phon_number": "9182133038", "birthday": "2023-11-21", "bio": "string", "address": "string", "gender": "M" }) self.assertEquals(response.status_code, 201) def test_profile_created_automate(self): user = User.objects.get(username='hosein') self.assertTrue(Profile.objects.filter(user=user).exists()) -
Error when try to add data to db in djnago app
i have djnago application (emergency notification system) and i see error when i try to add data to this is my views py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .models import Contact #################################################### class Main(TemplateView): template_name = 'emnosys/main.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context ################################################### def Registration(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] myuser = User.objects.create_user(username, email, password1) myuser.save() return redirect('signin') return render(request, "emnosys/registration.html") ############################################### def Signin(request): if request.method == 'POST': username = request.POST['username'] password1 = request.POST['pass1'] user = authenticate(username=username, password=password1) if user is not None: login(request, user) return render(request, "emnosys/main.html") else: return redirect('signin') return render(request, "emnosys/signin.html") ################################################ def Signout(request): logout(request) return redirect('home') ###################################################### class PersonalPage(TemplateView): template_name = 'emnosys/personalpage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context #################################################### def add_contact(request): if request.method == 'POST': username = request.POST.get('about--username') message = request.POST.get('about--message') email = request.POST.get('about--email') Contact.objects.create(username=username, message=message, email=email) return render(request, 'emnosys/addcontacts.html') this is my models py from django.db import … -
How to resolve error running pipdeptree with Python 3.11
I'm following the instructions here for upgrading Django: Django Upgrade Video And I get a big error when trying to run the first command for deriving dependencies: pipdeptree -f --warn silence | grep -E '^[a-zA-Z0-9\-]+' The following is the error stack trace Traceback (most recent call last): File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/bin/pipdeptree", line 8, in <module> sys.exit(main()) ^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/__main__.py", line 44, in main render(options, tree) File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/__init__.py", line 27, in render render_text( File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 34, in render_text _render_text_with_unicode(tree, nodes, max_depth, frozen) File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 107, in _render_text_with_unicode lines = chain.from_iterable([aux(p) for p in nodes]) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 107, in <listcomp> lines = chain.from_iterable([aux(p) for p in nodes]) ^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 59, in aux node_str = node.render(parent, frozen=frozen) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 53, in render return render(frozen=frozen) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 114, in render_as_root return self.as_frozen_repr(self._obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 79, in as_frozen_repr fr = FrozenRequirement.from_dist(our_dist) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/operations/freeze.py", line 244, in from_dist req, editable, comments = get_requirement_info(dist) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/operations/freeze.py", line 174, in get_requirement_info if not dist_is_editable(dist): ^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/utils/misc.py", line 384, in dist_is_editable egg_link = os.path.join(path_item, dist.project_name + ".egg-link") ^^^^^^^^^^^^^^^^^ AttributeError: 'Distribution' object has no attribute 'project_name' I'm new to Django and Python. I do not know how … -
Adding filter to inline raw_id_field in django admin
I have a data model as below: class School(models.Model): name = models.CharField() class Candidate(models.Model): name = models.CharField() school = models.ForeignKey(School) class Skill(models.Model): name = models.CharField() school = models.ForeignKey(School) class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate) skill = models.ForeignKey(Skill, related_name='candidate_skills') And in the admin I have: class CandidateSkillInline(admin.TabularInline): model = CandidateSkill form = CandidateSkillInlineForm fields = ('skill', ) raw_id_fields = ('skill',) class CandidateAdmin(admin.ModelAdmin): model = Candidate fields = ('name', 'school') inlines = [CandidateSkillInline] What I am trying to achieve is when I click the skill raw_id_field from the CandidateAdmin I want to list only the skills that belong to the school of the candidate. I had tried this solution https://stackoverflow.com/a/66429352/16891729 but in case of inlines I am getting the instance as None. So I can't access the candidate's school from the instances. This solution is working if we are filtering based on static value. How can I achieve this? -
Override Save to create multiple objects for range()
I want to override Django form save method to be able to create multiple objects at once. I have an AvailableHours model : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True) free_hours_to = models.IntegerField(null=True, blank=True,) status = models.BooleanField(null=True,default=True,) and I have a ModelForm for this class : class TimeGenerator(forms.ModelForm): class Meta: model = AvailableHours fields = ['free_date','free_hours_from','free_hours_to','status'] def save(self, commit=True): m = super(TimeGenerator, self).save(commit=False) self.free_hours_from = self.cleaned_data['free_hours_from'] self.free_hours_to = self.cleaned_data['free_hours_from'] +1 m.save() for hour in range(self.cleaned_data['free_hours_from'],self.cleaned_data['free_hours_to']+1): self.free_hours_from = self.cleaned_data['free_hours_from']+hour self.free_hours_to = self.cleaned_data['free_hours_from']+hour+1 print(hour) m.save() I want to create multiple AvailableHours object like this: if the form is set free_hours_from = 13 and free_hours_to=16 so the save method creates 13-14 , 14-15, 15-16 I wrote a code above in forms and overrided save() but its not working. anyone has a solution ? -
Django app making methods available to other apps written by third parties. How to define what is an 'external' api and what isn't?
We are creating a large Django program in which we expect other teams to write apps that will plug into and run within our Django program. We want our main app to provide some helper methods, type definitions etc that are freely available for other aps to utilize. So far that's easy, they just import our module and run whatever method they want. However we don't want all our methods to be treated as a public api available to other apps. Methods other apps use must be maintained for backwards compatibility, better documented etc after all. We want some methods to be used only internal to our app and would prefer end users not call them; or at the very least that they know we made no guarantee of not changing those methods in future releases. Now we could go around appending a _ in front of every method we don't want other apps using, but they aren't really private methods in my mind, since they are publicly available to other modules within our app. In addition well we already have allot of the app written and I don't want to go back and retroactively refactor half of our methods. … -
Websocket how to receive two request chatgpt at the sametime
I have a websocket (in Django) to receive request from client (reactjs). The request calls chatgpt api to stream its response to client. class GPTAPIConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def receive(self, text_data): data = json.loads(text_data) print('Start', data['requestID']) asyncio.create_task(self.streamToClient(data['requestID'])) async def streamToClient(self, requestID): completion = openai.ChatCompletion.create(...) content = '' for chunk in completion: if chunk['choices'][0].get('delta', {}).get('function_call'): chunkContent = chunk['choices'][0]['delta']['function_call']['arguments'] if chunkContent is not None: content += chunkContent await self.send(text_data=json.dumps({'text': content})) print('End', requestID) From client, I sent two messages with requestID 1 and 2. In server, the request 1 took about 10 seconds to finish so the log is: Start 1 End 1 Start 2 End 2 What I want is: Start 1 Start 2 End 1 or End 2 (depends which one ends first) Please help me! Thank you! -
Buy and sell products?
This app allows for bidding but I want someone who isn't logged in to not be able to bid and tell them they need to be logged in to be able to bid. Even though I wrote the code in the function and the person who entered the site can make an offer, but it gives this error. And how can I close the auction and introduce someone as a buyer? Are the codes I wrote suitable for this? error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/? next=/build/1/ Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] product_detail/<int:product_id>/ [name='product_detail'] watchlist/<str:username>/ [name='watchlist'] add/<int:productid>/ [name='add'] remove/<int:pid>/ [name='remove'] category/<str:name>/ [name='category'] category_2 [name='category_2'] create/ [name='create'] build/<int:product_id>/ [name='build'] accept/<int:product_id><int:bid_id>/ [name='accept'] ^media/(?P<path>.*)$ The current path, accounts/login/, didn’t match any of these. models.py: class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) seller = models.ForeignKey(User, on_delete=models.CASCADE) winner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='winner') … -
Django-haystack with AWS Opensearch
I am trying to implement a project which I have running locally but want to implement on AWS. I am running locally in a Docker container and I am running an instance of ElasticSearch for the project. In production I want to run AWS OpenSearch. When I run manage.py update_index using the docker container elastic search everything works. When I try and implement on AWS with OpenSearch I get the following. GET https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/_mapping [status:401 request:0.151s] Undecodable raw error response from server: Expecting value: line 1 column 1 (char 0) PUT https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local [status:401 request:0.087s] Undecodable raw error response from server: Expecting value: line 1 column 1 (char 0) POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.061s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.060s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.058s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.058s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.058s] --- Logging error --- Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/haystack/management/commands/update_index.py", line 119, in do_update backend.update(index, current_qs, commit=commit) File "/usr/local/lib/python3.11/site-packages/haystack/backends/elasticsearch_backend.py", line 239, in update bulk( File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 257, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 188, in streaming_bulk for data, (ok, info) in zip( File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 99, in _process_bulk_chunk raise e File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 95, in _process_bulk_chunk resp = client.bulk('\n'.join(bulk_actions) + '\n', **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/elasticsearch/client/utils.py", … -
Django optional, non-capturing string in URLs
I am trying to add prefix parameter to our api url's for our application implemented in Python Django. It is currently like this urlpatterns= [ path("api/", include( [ path("books/", include(books.urls)), path("events/", include(events.urls)), path("meetings/<str:group_id>/", handle_meetings) ]) ) ] Now what I want to do is make this api a non-capturing and optional parameter. By non-capturing I mean I want the parameter to be in the URL but not go to the views and handlers. I don't want to add it as a parameter to my views and handlers because I won't use it for now. And I want it to be optional. I will now show what I want to achieve in examples /api/books - should work /api_v1/books - should work /books - should work This being non-capturing is not the most meaningful function because the user can basically enter anything. But it is just a temporary solution and this is how we decided to go. Is this even possible? If this is not possible, I am okay with giving up on making it non-capturing as well. I still couldn't fix it. So in that case you can think of it as this. path("books/", include(books.urls)), path("events/", include(events.urls)), path("meetings/<str:group_id>/", handle_meetings) I have … -
Django query with Q filter _lte on DateField (tz=True) doesn't work
I got an Invoice model as models.DateTimeField() with a few records containing several dates: With an HTML form, I want to filter by dates <input name="start" class="form-control me-3" type="date" value="{{ min_date|date:'Y-n-d' }}" /> I got the same field for end date and when I print them in my view, they seem to be in the correct format 2023-11-12 -> 2023-11-17. In my view, I check if the two fields contain values and if yes, I filter my Invoice queryset: I tried lotsa combinations for queryset filtering and every time, the __lte clause seems not to work correctly and results don't include my end date. __lt is applied instead of __lte. Among those combinations I tried : if request.method == 'GET': # limit records number if no filter invoices = Invoice.objects.all()[:100] else: start = request.POST.get('startDate') end = request.POST.get('endDate') invoices = Invoice.objects.all() if start: invoices = invoices.filter(created_at__gte=start) if end: invoices = invoices.filter(created_at__lt=end) also tried : [...] else: start = request.POST.get('start') end = request.POST.get('end') if start and end: invoices = invoices.filter( Q(created_at__gte=start) & Q(created_at__lte=end)) if end and not start: invoices = invoices.filter(Q(created_at__lte=end)) if not end and start: invoices = invoices.filter(Q(created_at__gte=start)) First, I thought it was due to the warning about ("DateTimeField %s received … -
python-docx-template and {%tr for a loop and if condition error
I'm using the python package python-docx-template in a django project. I'm trying to build a table with a condition to display some rows. I'm trying to nest a '{%tr' of an if statement in a 'for' loop one : This lead to an error : emplateSyntaxError at /reports/employee/73/2/ Encountered unknown tag 'tr'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. 1/ If I remove the 'tr' of the 'if' statement, all works great, but it print empty rows (those of the 'if' and 'endif'). 2/ If I remove the 'tr' of the 'for' loop (so keep the one of the 'if'), I've got the error : Encountered unknown tag 'tr'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. I can not modify datas send to render the template. How can I conditionally print those rows? -
during client authentication in Keycloak. null value returned by getAuthenticationSession()
I attempted to obtain a token from the Keycloak server using the password grant. However, after changing the user password and making some modifications to the authentication process, I encountered the following error: I made an attempt to resolve the issue by restarting the Keycloak server, as well as restarting and modifying the grant, but unfortunately, the problem persists 2023-11-21 16:43:52,510 WARN [org.keycloak.events] (executor-thread-37) type=LOGIN_ERROR, realmId=7ffc23bd-250e-429e-8026-14cff8c6bdef, clientId=Print_login_protect, userId=null, ipAddress=172.20.67.92, error=invalid_user_credentials, auth_method=openid-connect, auth_type=code, response_type=code, redirect_uri=http://localhost:9000/home, code_id=40bf3e47-17b9-44f4-837b-508490fd71c9, response_mode=query 2023-11-21 16:45:41,979 ERROR [org.keycloak.services] (executor-thread-36) KC-SERVICES0015: Unexpected error when authenticating client: java.lang.NullPointerException: Cannot invoke "org.keycloak.sessions.AuthenticationSessionModel.getExecutionStatus()" because the return value of "org.keycloak.authentication.AuthenticationProcessor.getAuthenticationSession()" is null at org.keycloak.authentication.DefaultAuthenticationFlow.isProcessed(DefaultAuthenticationFlow.java:68) at org.keycloak.authentication.DefaultAuthenticationFlow.isProcessed(DefaultAuthenticationFlow.java:63) at org.keycloak.authentication.DefaultAuthenticationFlow.processSingleFlowExecutionModel(DefaultAuthenticationFlow.java:373) at org.keycloak.authentication.DefaultAuthenticationFlow.processFlow(DefaultAuthenticationFlow.java:249) at org.keycloak.authentication.AuthenticationProcessor.authenticateClient(AuthenticationProcessor.java:897) at org.keycloak.protocol.oidc.utils.AuthorizeClientUtil.authorizeClient(AuthorizeClientUtil.java:50) at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.checkClient(TokenEndpoint.java:269) at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.processGrantRequestInternal(TokenEndpoint.java:217) at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.processGrantRequest(TokenEndpoint.java:190) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:154) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:118) at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:560) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:452) at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:413) at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:321) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:415) at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:378) at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:174) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:142) at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:168) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:131) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:33) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:429) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:240) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:154) at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:321) at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:157)