Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fill the db with fake data
def _create_sources(fake, source_number): obj_list = [ Source( name=fake.sentence(nb_words=10, variable_nb_words=True), url=fake.url(), isbn_10=fake.isbn10(), isbn_13=fake.isbn13(), ) for _ in range(source_number) ] counter = 0 for obj in obj_list: Source.objects.bulk_create([obj]) print("{} {}".format(Source._meta.object_name, str(counter))) counter +=1 I fill my database with fake data. It is necessary for both debugging and even for development. By the way, it has nothing to do with tests. Initially I did: Source.objects.bulk_create(ob_list) It worked. But it the computer kept silence for a long time. And I decided to print a notification. My code is clumsy: I bulk_create just one object,having converted it into a list. Could you help me find a more elegant solution? -
Submitting a form in Django
I'm following a tutorial on youtube to create a Netflix clone. When I clicked the create profile button, the form data was cleared, but it didn't redirect me to the ProfileList page. Does it mean that the form is not valid? Thanks for your help. views.py class ProfileCreate(View): def get(self,request,*args, **kwargs): form=ProfileForm() return render(request,'profileCreate.html',{ 'form':form }) def post(self,request,*args, **kwargs): form=ProfileForm(request.POST or None) if form.is_valid(): #print(form.cleaned_data) profile = Profile.objects.create(**form.cleaned_data) if profile: request.user.profiles.add(profile) return redirect('core:profile_list') return render(request,'profileCreate.html',{ 'form':form }) ProfileCreate.html {% extends 'base.html' %} {% load static %} {% block tittle %} Profile create {% endblock tittle %} {% block content %} {% include 'partials/navbar.html' %} <section class='bg-primary_black min-h-screen bg-cover py-20 md:py-32 flex-col flex items-center' style="background-image:url('{static 'home_netflix.jpg'}')"> <div class="flex flex-wrap justify-center w-10/12 md:w-6/12"> <form method="POST" class="w-full md:w-8/12 bg-gray-900 p-5 rounded-lg"> <h1 class="text-4xl text-center text-gray-100 font-medium"> Create A Profile </h1> {% csrf_token %} <div class="my-4"> <Label class='text-lg text-gray-200 font-medium mb-3'> Profile Name </Label> <input required class="p-2 bg-gray-500 rounded-sm text-gray-200 outline-none block w-full" type="text" name="name" id="id_name" placeholder="Profile name"> </div> <div class="my-4"> <Label class='text-lg text-gray-200 font-medium mb-3'> Maturity Level </Label> <select class="p-2 bg-gray-500 rounded-sm text-gray-200 outline-none block w-full" name="age_limit" id="id_age_limit" > <option value="All">All</option> <option value="Kids">Kids</option> </select> </div> <div class="flex justify-center items-center"> <button class="px-4 py-2 rounded-md … -
Django model filter based on boolean field
I have a user model which has fields like these, is_active = models.BooleanField() date_joined = models.DateTimeField(auto_now_add=True) resigned_date = models.DateTimeField(blank=True, null=True) Where resigned_date will be None if is_active field is True. If is_active field is False then the resigned_date field will have the date. I think I can explain it. What I want is to queryset of users based on some DATE and is_active field. More clearly I want to get the list of employee that (is active and joined_date is less that or equal to the current date) and (is not active and resigned_date is greater that the current date) The query I have written so far: users = user_models.User.objects.filter( Q( is_active=True, date_joined__month__lte=month, date_joined__year__lte=year, ) & Q( is_active=False, resigned_date__month__gt=month, resigned_date__year__gt=year, ) ) But this is not working. It is not returning any users. How can I achive this? Thanks -
ModuleNotFoundError: No module named 'django_app' with heroku deployement
Hey mentors and senior devs I am now on this issue 5-7 hours trying to solve it, This issue happens during the deployment of my app on digital oceans apps and these are logs that Heroku sent please help me figure it out 2022-10-03T10:37:01.047248352Z [2022-10-03 10:37:01 +0000] [1] [INFO] Starting gunicorn 20.1.0 2022-10-03T10:37:01.048342704Z [2022-10-03 10:37:01 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) 2022-10-03T10:37:01.048420287Z [2022-10-03 10:37:01 +0000] [1] [INFO] Using worker: sync 2022-10-03T10:37:01.105225067Z [2022-10-03 10:37:01 +0000] [16] [INFO] Booting worker with pid: 16 2022-10-03T10:37:01.121367774Z [2022-10-03 10:37:01 +0000] [16] [ERROR] Exception in worker process 2022-10-03T10:37:01.121405181Z Traceback (most recent call last): 2022-10-03T10:37:01.121410503Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-10-03T10:37:01.121414404Z worker.init_process() 2022-10-03T10:37:01.121419137Z File "/workspace/.heroku/python/lib/python3.10/site-``` packages/gunicorn/workers/base.py", line 134, in init_process 2022-10-03T10:37:01.121423724Z self.load_wsgi() 2022-10-03T10:37:01.121428153Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-10-03T10:37:01.121431187Z self.wsgi = self.app.wsgi() 2022-10-03T10:37:01.121434180Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/app/base.py", line 67, in wsgi 2022-10-03T10:37:01.121438157Z self.callable = self.load() 2022-10-03T10:37:01.121441663Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-10-03T10:37:01.121462270Z return self.load_wsgiapp() 2022-10-03T10:37:01.121465690Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-10-03T10:37:01.121469061Z return util.import_app(self.app_uri) 2022-10-03T10:37:01.121472387Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/util.py", line 359, in import_app 2022-10-03T10:37:01.121475619Z mod = importlib.import_module(module) 2022-10-03T10:37:01.121482753Z File "/workspace/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2022-10-03T10:37:01.121486027Z return _bootstrap._gcd_import(name[level:], package, level) 2022-10-03T10:37:01.121490349Z File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2022-10-03T10:37:01.121493850Z File "<frozen importlib._bootstrap>", … -
Only id is returing in nested serializer django rest framework
I have two models user and notes, my aim is to get a JSON response like this. { "status": 200, "data": [ { "id": 1, "note": "dd", "created_on": "2022-10-03T06:58:33.337137Z", "is_active": true, "created_by":[{ "username":"loream", "email":"username@gmail.com", ........... } ] }, ]} Modals are : class Notes(models.Model): note= models.TextField() created_on=models.DateTimeField(auto_now_add=True) is_active=models.BooleanField(default=True) user=models.ForeignKey(UserModal,on_delete=models.CASCADE,null=True,related_name="created_byy",blank=True) class UserModal(AbstractUser): username = models.CharField(max_length=30,unique=True) password = models.CharField(max_length=30) email = models.EmailField(blank=True) serializers I wrote is class UserSerializer(serializers.ModelSerializer): class Meta: model = UserModal fields = '__all__' class NotesSerializer(serializers.ModelSerializer): created_byy = UserSerializer(many=True,read_only=True) class Meta: model=Notes fields='__all__' But I couldn't get a JSON response as expected I'm getting responses like this { "status": 200, "data": [ { "id": 1, "note": "dd", "created_on": "2022-10-03T06:58:33.337137Z", "is_active": true, "user": 1 }, ] } how can I achieve the expected result? -
Django web Application to put on VPS or Containers
We have a Django web Application in our workplace running in a local server, and we want to go cloud virtualization. what's the best solution for us: google VPS or containers ? -
Cannot connect to external PostgreSQL database from dockerized Django
I am running Django application dockerized and trying to connect to PostgreSQL database that is located at external host with a public IP. When running a container, makemigrations command falls with the following error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "myhost" (89.xx.xx.102) and accepting TCP/IP connections on port 5432? However, it successfully connects when not dockerized. Here the docker-compose.yml: services: backend: build: . ports: - 65534:65534 and corresponding Dockerfile: FROM python:3.10 AS builder ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY requirements.txt /app/ RUN pip install -r /app/requirements.txt RUN pip install gunicorn FROM builder COPY ./ /app/ ENTRYPOINT [ "/app/entrypoint.sh" ] and entrypoint.sh: #!/bin/bash python /app/manage.py collectstatic --no-input --clear python /app/manage.py makemigrations python /app/manage.py migrate --no-input gunicorn --pythonpath /app/ -b 0.0.0.0:65534 app.wsgi:application How to make it possible for the Django application to connect to externally hosted PostgresSQL database? -
Got AttributeError 'User' object has no attribute 'password1'
How to fix the error please help?Got AttributeError 'User' object has no attribute 'password1'. i want to add two password fields. user is created but error occurs AttributeError: Got AttributeError when attempting to get a value for field password1 on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'password1'. views.py class RegisterAPIView(generics.CreateAPIView): serializer_class = UserSerializer queryset = User.objects.all() serializers.py class UserSerializer(serializers.Serializer): username = serializers.CharField( label="Имя пользователя", style={"input_type": "username"} ) email = serializers.CharField( label="почта", style={"input_type": "email"} ) password1 = serializers.CharField( label="Пароль", style={'input_type': 'password'} ) password2 = serializers.CharField( label="Пароль повторно", style={'input_type': 'password'} ) def create(self, validated_data): password1 = validated_data.pop('password1') password2 = validated_data.pop('password2') print(validated_data) if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") validated_data["password"] = password1 print(validated_data) user = User.objects.create(**validated_data) print(user.id) return user -
How to use regex in form.py in django
I am working on Django project. I a fetching the data from POSTgresql in form.py while fetching the data is comming in ('Shirur'), in such format but i want the data as Shirur. Taluka1=forms.ModelChoiceField(queryset=data.objects.values_list("taluka").distinct()) Gut_Number = forms.ModelChoiceField(queryset=data.objects.all().values("gut_number").distinct()) Village_Name_Revenue = forms.ModelChoiceField(queryset=data.objects.all().values("village_name_revenue").distinct()) above is my code ' -
JWT token error "Token has no id" Django Rest Framework
I'm trying to access data(user_id) from the custom simple jwt token. But I'm getting this error. "message": "Token has no id" { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token has no id" } ] } this is my jwt_custom.py def generate_access_token(user): access_token_payload = { 'user_id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, minutes=20), 'iat': datetime.datetime.utcnow(), } access_token = jwt.encode(access_token_payload, settings.SECRET_KEY, algorithm='HS256') return access_token def generate_refresh_token(user): refresh_token_payload = { 'user_id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7), 'iat': datetime.datetime.utcnow() } refresh_token = jwt.encode( refresh_token_payload, settings.SECRET_KEY, algorithm='HS256') return refresh_token this is my views.py here I'm creating a token when the user login. @permission_classes([AllowAny]) class LoginView(APIView): serializer_class = LoginSerializer def post(self, request, **kwargs): serializer = self.serializer_class(data=request.data) ... generate_access_token = jwt_custom.generate_access_token(user) generate_refresh_token = jwt_custom.generate_refresh_token(user) return Response({"response": True, "return_code": "login_success",'refresh': str(generate_access_token), 'access': str(generate_refresh_token), "result": {"user": user_serializer.data}, "message": success["login_success"]}, status=200) ... this is views.py here I'm trying to get data through the token. class UserPosts(APIView): def post(self, request, user_id=None, *args, **kwargs): get_token = request.META.get('Authorization', None) try: payload = jwt.decode(get_token, settings.SECRET_KEY, algorithms=['HS256']).decode('utf-8') except jwt.ExpiredSignatureError: return Response({'expired refresh token, please login again.': "notFound"}) get_user_data = request.data["user_id"] try: User.objects.get(id=user_id) post = Post.objects.filter(user_id=payload.get('user_id')).order_by('-created_on') paginator = CustomPageNumberPagination() page = paginator.paginate_queryset(post, request) ... … -
Django celery cannot import name 'Celery' from 'celery' after restart Docker
I run Django and Celery in Docker. It's working fine, but after I restart Docker, celery can't start because of import name error. Errors below: v_web | Traceback (most recent call last): v_web | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv v_web | self.execute(*args, **cmd_options) v_web | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 393, in execute v_web | self.check() v_web | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 423, in check v_web | databases=databases, v_web | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 76, in run_checks v_web | new_errors = check(app_configs=app_configs, databases=databases) v_web | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 100, in check_url_settings v_web | value = getattr(settings, name) v_web | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ v_web | self._setup(name) v_web | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup v_web | self._wrapped = Settings(settings_module) v_web | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ v_web | mod = importlib.import_module(self.SETTINGS_MODULE) v_web | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module v_web | return _bootstrap._gcd_import(name[level:], package, level) v_web | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import v_web | File "<frozen importlib._bootstrap>", line 983, in _find_and_load v_web | File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked v_web | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed v_web | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import v_web | File "<frozen importlib._bootstrap>", line 983, in _find_and_load v_web … -
docker-compose up --build exit code: 1
after i run this command pip3 freeze > requirements.txt 503.5/503.5 KB 2.2 MB/s eta 0:00:00 #0 99.08 ERROR: Could not find a version that satisfies the requirement pywin32==304 (from versions: none) #0 99.08 ERROR: No matching distribution found for pywin32==304 #0 99.08 WARNING: You are using pip version 22.0.4; however, version 22.2.2 is available. #0 99.08 You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command. failed to solve: executor failed running [/bin/sh -c pip install -r requirements.txt]: exit code: 1 PS C:\Ngulik\docker_django_tb> pip3 freeze > requirements.txt -
pylint-django shows error ModuleNotFoundError: No module named 'myproj'
I have installed pylint and pylint-django. Then followed docs. My django project is structured as follows: /path/to/project/myproj/settings_test.py /path/to/project/manage.py Running the following command: cd /path/to/project/ export DJANGO_SETTINGS_MODULE=myproj.settings_test find . -name "*.py" | xargs pylint --load-plugins pylint_django --django-settings-module=myproj.settings_test I face with this error: errors: Traceback (most recent call last): File "/home/ar2015/.local/bin/pylint", line 8, in <module> sys.exit(run_pylint()) File "/home/ar2015/.local/lib/python3.8/site-packages/pylint/__init__.py", line 35, in run_pylint PylintRun(argv or sys.argv[1:]) File "/home/ar2015/.local/lib/python3.8/site-packages/pylint/lint/run.py", line 207, in __init__ linter.check(args) File "/home/ar2015/.local/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 685, in check with self._astroid_module_checker() as check_astroid_module: File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__ return next(self.gen) File "/home/ar2015/.local/lib/python3.8/site-packages/pylint/lint/pylinter.py", line 982, in _astroid_module_checker checker.open() File "/home/ar2015/.local/lib/python3.8/site-packages/pylint_django/checkers/foreign_key_strings.py", line 92, in open django.setup() File "/home/ar2015/.local/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ar2015/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/ar2015/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/ar2015/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/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 _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'myproj' Note: The following did not help: python3 manage.py makemigrations python3 manage.py migrate pip install django-filter touch __init__.py export DJANGO_SETTINGS_MODULE=myproj . Steps for reproduction: Note this is a MWE and … -
What exactly are path converters in Django
I am new to Django and I can't seem to wrap my head around what exactly a path converter does. As I understand, for each app we require a URLConf file, which will map our URL's to our view functions. In this way, when a URL is requested by a user, the corresponding view function will be executed. According to the documentation: Path converters¶ The following path converters are available by default: str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression. int - Matches zero or any positive integer. Returns an int. slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site. uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a UUID instance. path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than a segment of a URL path as with str. So, does this mean, that the path converter acts … -
Migrations reflect not only database but some business logic. Migrations blow up
Let us suppose that we had a model (example is from the documentation https://docs.djangoproject.com/en/4.1/ref/models/fields/#filefield): def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) Migrations will be something like: ('upload', models.FileField(upload_to=vocabulary_phrases.models.user_directory_path)), But now you decide to change to a class: class UploadTo: def __init__(self, folder, filename_suffix=""): self.folder = folder self.filename_suffix = filename_suffix def _get_filename(self, instance, filename): _, file_extension = os.path.splitext(filename) result = str(instance.a_uuid) if self.filename_suffix: result += "-{}".format(self.filename_suffix) result += file_extension return result def save_path(self, instance, filename): tmp_filename = self._get_filename(instance, filename) result = "{}/{}".format(self.folder.value, tmp_filename) return result class MyModel(models.Model): upload = UploadTo(folder=UPLOAD_TO.VOCABULARY_FILE_FOLDER, filename_suffix="trololo").save_path When you try to makemigrations, this code will blow. It will complain like 0002_migration contains user_directory_path, it is absent. This change in the code not mechanical. I can't imagine that it can be done just by refactor / rename in IDE. Then I can't imagine what the new migration should look like. This means that I will not be able to modify migrations file easily. I will have to deploy another project next to this one and another database. Delete all migrations, makemigrations, copy created migration and substitute all occurrances of user_directory_path with what is in my clipboard. Complicated, … -
Django channels always returns AnonymousUser when using Django Authentication
i am learning about django channels. I am following the channels docs: https://channels.readthedocs.io/en/stable/topics/authentication.html When i try to access the user using self.scope["user"] in consumers.py, i am always getting AnonymousUser object I can see the logged in user in templates. I used the admin user for testing. Note: I am new here. Please let me know if i need to provide some more info. Thank you consumers.py from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer import time import asyncio from pprint import pprint from asgiref.sync import async_to_sync class MyWebsocketConsumer(WebsocketConsumer): def connect(self): print("connected") pprint(self.scope) pprint(self.scope['user'].username) self.room_name = self.scope['url_route']['kwargs']['room'] group_add = async_to_sync(self.channel_layer.group_add) group_add(self.room_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): pprint(self.scope['user'].is_authenticated) print('msg received', text_data) group_send = async_to_sync(self.channel_layer.group_send) message = { 'type': 'chat.message', 'msg': text_data } group_send(self.room_name, message) # self.send(text_data) def chat_message(self, event): msg = event['msg'] self.send(msg) def disconnect(self, close_code): print("disconnected", close_code) routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/wsc/<str:room>', consumers.MyWebsocketConsumer.as_asgi()), # path('ws/awsc/', consumers.MyAsyncWebsocketConsumer.as_asgi()) ] asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter import app.routing from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_consumer.settings') wsgi_app = get_asgi_application() application = ProtocolTypeRouter({ 'http': wsgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( app.routing.websocket_urlpatterns)) ) }) settings.py from pathlib import Path # Build paths inside … -
How do i set network file path in django response?
I have MinIO and Django apps in the docker network. When I want to send a file to a client I need to use this form: response = HttpResponse() response['X-Accel-Redirect'] = file_path if download: response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name) else: response['Content-Disposition'] = 'filename="{}"'.format(file_name) Is it possible to replace file_path with network file path? -
Problem with searchbar in Django and HTML
I have created a searchbar in Django and HTML, however, this gives me problems. If I enter "Apple iPhone 13 Pro" in the searchbar it will not find any results, because the URL is not encode. The URL is: Apple+iPhone+13+Pro, but it should be: Apple+iPhone%C2%A0%. How can I solve? -
Deploy Zappa Django on AWS Lambda with Custom GoDaddy Domain
I created a Django Rest APIS using the Django Rest framework. I used Zappa to deploy my DJANGO API and got a working URL https://autocreatedname.execute-api.region.amazonaws.com/dev Zappa created an s3 bucket and a lambda function After that, I created a Cloudfront distribution with my custom domain name and got d3b779m4oksdfs.cloudfront.net --> this works in isolation on the browser. I created AWS certification and added CNAME and Value to my Godaddy DNS and it's active and validated. Now, I am not sure if I need Amazon route 53/API Gateway to connect these. -
Triggering a trackor without change in value in django?
I have a use case, where I am tracking the changes of a field. My issue is I want to trigger it even if there is no change in that field. E.g., status field changes from Null -> IM -> OK -> OK I have put my logging code based on the change of status field and due to some constraint I had to do the status change from IM to OK. I now want to trigger the tracker for the OK - > OK (the very first occurrence only) This is my post_save signal: @receiver(post_save, sender="iot_app.VehicleNumber") def vehiclenumber_post_save(sender, instance, created, *args, **kwargs): if changed == 'status': if created: continue try: log_ota_events.delay( vehicle_id=instance.id, event=getattr(instance, '_event_type'), source=getattr(instance, '_event_source', None), source_id=getattr(instance, '_event_source_id', None), metadata={ 'immobilize_status': instance.status, 'immobilizer_action': instance.immobilizer_action, 'immobilisation_valid_upto': str(instance.immobilisation_valid_upto), }, comment=getattr(instance, '_event_comment', None), ) except Exception as e: logger.warning(f"Couldn't log the event {e}", exc_info=True)``` -
Django Rest Framework, request POST, update if exists, create if not exists from mass data of POST request
I am building an API for users info data I want to make that when the POST request, execute function "create", "update" if from POST request user exists: update (full_name, function, department, logon, system, lic_type ) if from POST request user doesn't exist: create (user, full_name, function, department, logon, system, lic_type ) models.py from django.db import models class Users(models.Model): user = models.CharField(max_length=50,blank=True, null=True) full_name = models.CharField(max_length=200, blank=True, null=True) function = models.CharField(max_length=300,blank=True, null=True) department = models.CharField(max_length=300,blank=True, null=True) logon = models.DateTimeField(blank=True, null=True) system = models.CharField(max_length=300,blank=True, null=True) lic_type = models.CharField(max_length=300,blank=True, null=True) serizlizers.py from rest_framework import serializers from .models import Users class UsersSerializer(serializers.ModelSerializer): logon = serializers.DateTimeField(input_formats=settings.DATE_INPUT_FORMATS) class Meta: model = Users # fields = '__all__' fields = ['user', 'full_name', 'function', 'department', 'logon', 'system', 'lic_type'] views.py from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from rest_framework import status from .models import Users from .serializers import UsersSerializer from rest_framework.decorators import api_view, authentication_classes from rest_framework.response import Response from django.views.decorators.csrf import csrf_exempt from rest_framework.authentication import BasicAuthentication @csrf_exempt @api_view(['GET', 'POST']) @authentication_classes([BasicAuthentication]) def users_list(request): if request.method == 'GET': users = Users.objects.all() user = request.GET.get('user', None) if user is not None: users = users.filter(user__icontains=user) users_serializer = UsersSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) elif request.method == 'POST': users_data = JSONParser().parse(request) users_serializer = UsersSerializer(data=users_data, … -
Django creation of model with foreign keys
I have a model with two foreign keys. When I use ModelForm to create instances those two foreign keys appear as drop down menus. But I want them to be automatically created from string values. How could i do this? -
Django-tenants "Unable to create the django_migrations table"
An issue occurred where our production database was not getting migrated due to an error during migration. This error involved the usage of the package django-tenants, which is a fork of the django-tenant-schemas package. The error: Traceback (most recent call last): File "/backend/manage.py", line 21, in <module> main() File "/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django_tenants/management/commands/migrate_schemas.py", line 89, in handle executor.run_migrations(tenants=tenants) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 14, in run_migrations Starting new HTTPS connection (1): o1380729.ingest.sentry.io:443 run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants)) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations migration_recorder.ensure_schema() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 70, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (relation "django_migrations" already exists ) What could cause this error? -
jquery each function for auto generated html elements with same class
I have an ajax script that should act on some automatically generated html elements from django, to do this I was told to use the each() function in jquery to act on each element with the same class name. The script sort of works without the each() function, but it only changes the first element rather than each individual element. With the each function in place, no values are changed so I'm not sure what to do. javascript $(document).ready(function() { $('.fix-button').each(function() { $(this).on('submit', function(e){ e.preventDefault(); issue_id = $(this) $.ajax({ type: 'POST', url: '{% url "fix_issue" %}', data: { issueid: issue_id.val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("fixed_bool").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) { } }); }); }); }); my views.py if its necessary def FixView(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('issueid')) issue = get_object_or_404(Issue, id=id) if issue.fixed == False: print(issue) issue.fixed = True result = str(issue.fixed) issue.save() else: issue.fixed = False result = str(issue.fixed) issue.save() return JsonResponse({'result': result, }) -
No module named... in Django proyect
I have a pretty standart Django project and i can't find a way to import /middleware/utils/compare.py from /middleware/utils/request.py This is the proyect tree: |--middleware/ | |--utils/ | | |--compare.py | | |--request.py | |--__init__.py | |--asgi.py | |--settings.py | |--urls.py | |--views.py | |--wsgi.py |--manage.py Where __init__.py, asgi.py, settings.py, urls.py, wsgi.py have no major modifications. (__init__.py is empty) # middleware/views.py from .utils.request import requests # This line works fine # middleware/utils/request.py from compare import compare # ModuleNotFoundError: No module named 'compare' from .compare import compare # Attempted relative import beyond top-level package pylint(relative-beyond-top-level) # ^^^ This line absolutly breaks my code, but it runs from utils.compare import compare # ModuleNotFoundError: No module named 'utils' from .utils.compare import compare # ModuleNotFoundError: No module named 'middleware.utils.utils' Note: compare.py has a function named compare, i also tried renaming it but had the same problems. This might be obvious, but i run the proyect with python manage.py runserver