Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django BaseDataTableView - filter_queryset method not work
I am using BaseDatatableView and DataTable jquery. I've already written several views for BaseDatatableView and there were no problems until I had to override the 'prepare_results' and 'render_column' methods. I need to present the results of instance methods in a table, so I overwrite the methods of the BaseDatatableView class. This is my code in views.py class MyModelDatatable(BaseDatatableView): model = MyModel columns = ['field1', 'field2', 'id'] columns_searched = [col for col in columns if col != 'id'] def get_initial_queryset(self): return self.model.objects.all() def filter_queryset(self, qs): print('test') # not displayed search_text = self.request.GET.get('search[value]', None) if search_text: search_terms = search_text.split() query = Q() for col in self.columns_searched: or_conditions = Q() for term in search_terms: or_conditions |= Q(**{f'{col}__icontains': term}) query |= or_conditions qs = qs.filter(query) return qs def prepare_results(self, qs): data = [] for item in qs: item_str = str(item) data.append({ 'field1': item_str, 'field2': item.field2, 'id': item.id }) return data def render_column(self, row, column): if column == 'field2': return row.date.strftime('%Y-%m-%d') return super(OrderDatatable, self).render_column(row, column) def get(self, request, *args, **kwargs): return self.get_json_response() def get_json_response(self): draw = int(self.request.GET.get('draw', 1)) total_records = self.get_initial_queryset().count() total_display_records = total_records start = int(self.request.GET.get('start', 0)) length = int(self.request.GET.get('length', 10)) end = start + length data = self.prepare_results(self.get_initial_queryset()[start:end]) response = { 'draw': draw, … -
SSL Certification Requirements Safety Question
I am using Heroku and Redis in a production environment built with Django and have been getting errors with SSL. At first I had this issue: A rediss:// URL must have parameter ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE I then tried adding ?ssl_cert_reqs=CERT_REQUIRED To my CELERY_RESULT_BACKEND Which then returned this error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain I then changed the ?ssl_cert_reqs to equal CERT_NONE and this has solved all issues completely. My question is if this fix is safe from any attacks or if this has completely got rid of the SSL certificates. I have read on a few pages that people have used this to fix their issue but I am working on a production app and do not want to compromise on safety. Any help would be greatly appreciated. Thank you, Liam -
Python issue with redis hostname not resolved in docker
I seem to have issues while trying to setup redis instance via python/django. I have a lot of containers running in docker-compose and while other containers are able to connect properly, when trying with Django I get: Step 11/16 : RUN python3 /home/allianceserver/myauth/manage.py collectstatic ---> Running in 749d9931dadb [30/Oct/2023 08:59:47] INFO [allianceauth.eveonline.providers:181] ESI client will be loaded on-demand [30/Oct/2023 08:59:47] ERROR [allianceauth.authentication.task_statistics.helpers:44] Failed to establish a connection with Redis. This EventSeries object is disabled. Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 264, in connect sock = self.retry.call_with_retry( File "/usr/local/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry return do() File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 265, in <lambda> lambda: self._connect(), lambda error: self.disconnect(error) File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 595, in _connect for res in socket.getaddrinfo( File "/usr/local/lib/python3.9/socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/helpers.py", line 41, in get_redis_client_or_stub if not redis.ping(): File "/usr/local/lib/python3.9/site-packages/redis/commands/core.py", line 1216, in ping return self.execute_command("PING", **kwargs) File "/usr/local/lib/python3.9/site-packages/redis/client.py", line 533, in execute_command conn = self.connection or pool.get_connection(command_name, **options) File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 1086, in get_connection connection.connect() File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 270, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: … -
Django REST framework: get last related object
I am trying to get the last related object in a Django REST framework view. With the current implementation I am getting this error - but I am not sure if this is the correct approach: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. I have this two models (little bit cleaned up): class Device(models.Model): name = models.TextField() def get_last_status(self): return self.status.last() class DeviceStatus(models.Model): class eDeviceStatus(models.TextChoices): OFFLINE = 'F', _('Offline') ONLINE = 'L', _('Online') device = models.ForeignKey(Device, related_name='status', on_delete=models.CASCADE) status = models.CharField(max_length=1, choices=eDeviceStatus.choices, default=eDeviceStatus.OFFLINE) last_update = models.DateTimeField() with this Device view: class DeviceViewSet(ModelViewSet): serializer_class = DeviceSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Device.objects.filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) and this Device serializer: class DeviceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') last_status = serializers.SerializerMethodField() class Meta: model = Device fields = ['url', 'id', 'name', 'last_status'] def get_last_status(self, obj): s = obj.get_last_status() serializer = DeviceStatusSerializer(s) return serializer.data I would like to have in my api the last status (field: last_status) from the DB. But I am failing to have it correctly implemented. How can I have the last_status correctly set? -
Specify lookup_url_kwarg in the nested route using drf-nested-routers
Using drf-nested-routers we have implemented many nested routes that go two levels in depth. Just as in the documented examples: /clients/ /clients/{pk}/ /clients/{client_pk}/maildrops/ /clients/{client_pk}/maildrops/{pk}/ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/ However, I don't like the inconsistency in the 4th line. How can I make the lookup_url_kwarg be maildrop_pk there too? /clients/{client_pk}/maildrops/{maildrop_pk}/ If I set the lookup_url_kwarg in the MailDropViewSet to maildrop_pk, then it appears correctly in this route, but the nested routes for MailRecipient become: /clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/ /clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/{pk}/ I want to have a consistent naming across all nested routes. -
DRF ViewSet always returns HTTP 200
I'm new to DRF. This is my ViewSet: class AccountViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = AccountSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, email=None): queryset = User.objects.all() user = get_object_or_404(queryset, email=email) serializer = AccountSerializer(user) return Response(serializer.data) I have two email addresses in the database. My API client is httpie. When I send a GET request to http://127.0.0.1:8000/api/accounts/ I get back those two emails. So this part works fine. However, when I provide an email address that doesn't exits in the database (as Params or Headers), I again get those two emails instead of 404. I did a little bit of research and change the code like this: class AccountViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = AccountSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, email=None): queryset = User.objects.all() try: user = get_object_or_404(queryset, email=email) except User.DoesNotExist: return Response(status=404) serializer = AccountSerializer(user) return Response(serializer.data) Again, 200 with those two emails. Even when I provide an email that does exists, I get both in response. I can't figure out what I'm missing. -
How to maintain data integrity in django
How can I maintain data integrity in django? I see that there is optimistic locking, or mvcc, but I don't know how to implement it. Also, are these the same thing? I think I can implement pessimistic locking using select_for_update. I heard that F() gets the latest information on the database side and adds values to it to maintain consistency, but is it ok for simultaneous cases? I asked chatgpt and chatgpt said that mvcc and optimistic locking are implemented by default by the database, is this true? -
I want to select a record from table to go another page in django
i have a table in my template have a many records that retrieved from the database, each row have a select option that when a user selects an option and click on the button, it must be take him to another page. my template.html: <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>رقم الكتاب</th> <th>تاريخ</th> <th>تاريخ الاضافة</th> <th>ملاحظات</th> <th>اﻻجراء</th> </tr> </thead> <tbody> {% for doc in docs %} <tr> <td>{{ doc.number }}</td> <td>{{ doc.date|date:"Y-m-d"}}</td> <td>{{doc.created_at|date:"Y-m-d"}}</td> <td>{{ doc.note }}</td> <td>{{ doc.status }}</td> <td> <a href="/edit/{{ doc.id }}"><span class="glyphicon glyphicon-pencil" ><i class="far fa-edit" style="color: #116014;"></i></i></span></a> <a href="/delete/{{ doc.id }}"><i class="far fa-trash-alt" style="color: #bf5a40;"></i></a> <a href="/download/{{ doc.id }}"><i class="far fa-file-pdf" style="color: #204a87;"></i></a> </td> <td> <select id="choices" style="background-color:DodgerBlue; color: white;"> <option value="/deliver/{{ doc.id }}/{{doc.number}}/{{doc.date}}/{{doc.note}}/{{doc.document}}/{{doc.status}}">الموارد البشرية</option> <option value="">المالية</option> </select> <button type="button" id="go-button" class="button"><span>تحويل</span></button> </td> </tr> {% endfor %} </tbody> </table> urls.py: urlpatterns = [ path("", views.index, name="index"), path("show", views.show, name="show"), path("docs", views.documents, name="docs"), path("maward-show", views.show_maward, name="maward-show"), path("deliver/<int:id>/<int:number>/<str:date>/<str:note>/<path:document>/<str:status>", views.deliver, name="deliver"),] **views.py: ** def deliver(request, id, number, date, note, document, status): print(document) var = Maward.objects.create(id=id, number=number, date=date, note=note, document=document, status=status) time.sleep(3) return redirect("/show") i added a javascript code to my template as following: <script> $(document).ready(function() { $('#go-button').click(function() { // Get the selected choice var selectedChoice = … -
Django migrations not working properly in ecs
I have a django application on ecs. I push the code to github along with the migrations files. I have a script that runs the migrate command when I deploy. I can create a superuser but when I try to login to admin panel I get relation user_user does not exist error, but when I connect to the RDS directly form my local system I can login, but not from the domain which is attached to the elb -
Unable to run the django server
i'm trying to laucn the django with the command python manage.py runserver but i got this error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is Fa is False. here is my settings project: DEBUG = True ALLOWED_HOSTS = [] i've tried all the solution proposed by others on the relative question with mine but the difference is that i've not change the settings variable Debug so their solution don't work for me. like to change the value of list settings variable ALLOWEG_HOSTS but it's not working for me. -
Django-Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
There some questions related to this but no answers are helped. I often come accross errors like that but cannot figure out what causes problems. My projects has been running fine but suddenly all of them which using postgresql are stopped, giving following error. Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/psycopg/connection.py", line 728, in connect raise ex.with_traceback(None) psycopg.OperationalError: connection is bad: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 74, in inner with self._recreate_cm(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/transaction.py", line 198, in __enter__ if not connection.get_autocommit(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 464, in get_autocommit self.ensure_connection() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/utils.py", … -
pathlib.py" is overriding the stdlib module "pathlib"
Creating a Django app in a condo virtual environment(djenv) created the html, updated views.py and urls.py when updating settings.py, getting a problem for this line of code from pathlib import Path "C:\test1\djenv\Lib\pathlib.py" is overriding the stdlib module "pathlib" when I renamed pathlib.py, Django doesn't work properly Is there a way override the stdlib pathlib and use the virtual environments pathlib.py or are there any other fixes for this problem -
Django join tables with two or more FK conditions
I want to join models B and C with two conditions, data_a and human in model_B, and data_a and autor in model_C, but how do I do it with Django ORM class user(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_A(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_B(models.Model): data_a = models.ForeignKey(model_A) human = models.ForeignKey(user) data_2 = models.IntegerField() class model_C(models.Model): data_a = models.ForeignKey(model_A) author = models.ForeignKey(user) data_1 = models.CharField(max_length=5) data_2 = models.IntegerField() additional conditions on join in django I've seen this place, but I don't know if it's applicable to my situation -
Django bulk_create() with inexistent ForeignKey
I have 2 models. For simplicity, I deleted all unnecessary fields. class User(models.Model): id = models.CharField(max_length=36, primary_key=True, null=False) age = models.IntegerFiels(default=-1) and class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Through the API, I receive information about devices and create a list with devices. devices = [] for device_data in data: devices.append( Device( user_id=device_data("user_id") ) ) Once I have the list of devices, I add it to the database. Device.objects.bulk_create(devices, ignore_conflicts=True) The problem is that if, when creating a Device, I specified a user_id that is not in the database, I will get a crash because I am trying to link with a non-existent id. Now to get around this I do the following: devices = [] users = [] for device_data in data: users.append( User( id=device_data("user_id", age = -1) ) ) devices.append( Device( user_id=device_data("user_id") ) ) Then, when saving: User.objects.bulk_create(users, ignore_conflicts=True) Device.objects.bulk_create(devices, ignore_conflicts=True) User.objects.filter(age=-1).delete() How can I make sure that when saving, if the specified user_id does not exist, this device is not added? Or add a device, while creating a User with this user_id, but with the rest of the fields by default, and then, at the end, I will delete all users, and with them all devices, where age … -
Django queryset not filtering correctly based on end_date and current_time
I'm encountering an issue with my Django project where I have a model Service with an end_date field. I want to filter services based on whether their end_date is in the future, but I'm facing unexpected behavior. model.py: from django.db import models from apps.user.models import CustomUser from apps.location.models import City from django.utils import timezone class Area(models.Model): name = models.CharField(max_length=70,unique=True) def __str__(self): return self.name class Type_of_housing(models.Model): name = models.CharField(max_length=100,unique=True) areas = models.ManyToManyField(Area,blank=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=100,unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Service(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) type_of_housing = models.ForeignKey(Type_of_housing, on_delete=models.CASCADE) area = models.ForeignKey(Area, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) location_address = models.CharField(max_length=100) city = models.ForeignKey(City,on_delete=models.CASCADE) is_visible = models.BooleanField(default=True) end_date = models.DateTimeField() def __str__(self): return self.title def save(self, *args, **kwargs): if not self.end_date: # Calculate the end date as 14 days from the current date and time self.end_date = timezone.now() + timezone.timedelta(days=14) super().save(*args, **kwargs) class ServiceImage(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) image = models.ImageField(upload_to='service_images/') def __str__(self): return f"Image for Service: {self.service.description}" and view.py: def service_list(request): current_time = timezone.now() print("Current Time:", current_time) services = Service.objects.all() for service … -
How to get python implemented in Django
I have already defined a function and now wanted to use it on my website and have already tried this <img src="{{ get_pop_img(0) }}" class="card-img-top" alt="jpg"> and my function is def get_pop_img(number): response = requests.get('https://api.jikan.moe/v4/top/manga?filter=bypopularity') img = response.json()['data'][number]['images']['jpg']['image_url'] return img but i only getting errors I also importet my python file in the views.py -
Why does the variable not change its value after admin action has been triggered?
I have two admin actions for the Feedback Model in the admin panel, approved and unapproved. The value for approved in the Feedback Model is default to False. When admin use the action to approve, it turns this value to True and unapproved will turn True to False. This works on the admin panel on the deployed site, however when I'm trying to do the test for the admin.py I ran into an error where the test_approve is passing, while the test_unapprove failed. When I try to debug the test_unapprove I set the approved value as True and then check the value of feedback.approve before the response and it came out as True, which is expected. Then I check again after the response and it still came out as True where it should come out as False. Please have a look if you have any clue why this is happening. If you need any more info please let me know! admin.py @admin.register(Feedback) class FeedbackAdmin(admin.ModelAdmin): list_display = ('username', 'body', 'lesson_id', 'created_on', 'approved') list_filter = ('approved', 'created_on') list_display_links = ('username',) search_fields = ['username', 'user_id', 'body'] actions = ['approved_feedback', 'unapproved_feedback'] def approved_feedback(self, request, queryset): queryset.update(approved=True) def unapproved_feedback(self, request, queryset): queryset.update(approved=False) test_admin.py class TestAdmin(TestCase): … -
Django data problem : new salons always with all users
Problem is that I want to create a new salon, so beginning with only the user who created it. But, when I consult my django database (with localhost:8000/admin/), I notice that every user (UserSalon) is present in every 'Salon'... However, when I print all the users of this salon in the terminal, I can see there is only this one. So wtf? I have this in my models.py: class UserSalon(models.Model): # etc. class Salon(models.Model): salon_users = models.ManyToManyField(UserSalon) # etc. and this is a part of code from my view.py: user_salon_id = request.session.get('user_salon_id') if request.method == 'POST': create_salon_form = CreateSalonForm(request.POST) try: user_salon = UserSalon.objects.get(id=user_salon_id) except UserSalon.DoesNotExist: user_salon = None if create_salon_form.is_valid(): created_id_salon = create_salon_form.cleaned_data['id_salon'] created_key_salon = create_salon_form.cleaned_data['key_salon'] new_salon = Salon.objects.create(id_salon=created_id_salon, key_salon=created_key_salon) new_salon.salon_users.clear() new_salon.salon_users.add(user_salon) new_salon.save() -
How to assign the result of a conditional to a variable in a Django template?
There are two django models, "Production" and "Season". Production has a foreign key to Season (i.e. in rails-speak Season has_many Productions, Production belongs_to Season). I have a detail view for Production, and the page sidebar has the list of all productions in the current season. {% for p in season.production_set.all %} <li class="nav-item"> <a class="nav-link d-flex align-items-center gap-2" href="{% url 'production_detail' season.id p.id %}"> {{p.name}} </a> </li> {% endfor %} {% endblock %} But I would like the nav item to be disabled for the current production being viewed. That means adding the 'disabled' class to a element, and setting the "aria-current" attribute as well. I can use if/else takes, but it ends up being quite verbose and also repetitive, given that I need this logic twice in the same html tag <a class="nav-link d-flex align-items-center gap-2 {% if p.id is not production.id %} active {% else %} disabled {% endif %}" aria-current="{% if p.id is production.id %}true{%else%}false{%endif%}" href="{% url 'production_detail' season.id p.id %}"> So I tried to assign a variable like {% with p.id is not production.id as current %} but no syntax I have tried allowed me to assign a boolean expression to a variable. Is there a … -
Cannot turn PIL.Image.Image to tensor using tochvision transforms.ToTensor in Django
I'm doing a AI service using django app served by uWSGI in docker which setup from my senior. And it's always 504 time-out when reach img_tensor = transforms.ToTensor()(img_resized) This is views.py from django.apps import apps from rest_framework import status from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response import os, shutil import gc import uuid from PIL import Image from multiprocessing import Pool import torch from fairseq import utils from torch.utils.data import DataLoader from torchvision import transforms from HTR.serializers import HTRSerializer from HTR.Backend.main import generate_text class HTRViewSet(APIView): permission_classes = [permissions.AllowAny] config = apps.get_app_config('HTR') def post(self, request, format=None): serializer = HTRSerializer(data=request.data) if serializer.is_valid(): # input_text haven't use now image = serializer.validated_data['image'] input_text =serializer.validated_data['text'] unique_id = str(uuid.uuid4()) directory_path = os.path.join(os.getcwd(), 'HTR', 'Backend', 'image', unique_id) doc_list = generate_text(image, directory_path, self.config.TrOCR, self.config.device) gc.collect() doc = '\n'.join(doc_list) corrected = None full_doc = doc.replace('\n', '<br>') return Response({'document': full_doc, 'corrected': corrected}, status=status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) main.py for running AI model from fairseq.data import Dictionary from fairseq import utils from torch.utils.data import DataLoader import torch import os, shutil try: from .bpe import GPT2BPE from .dataset import STRDataset from .Preprocess.main import processing except ImportError: from bpe import GPT2BPE from dataset import STRDataset from Preprocess.main import processing … -
How to Post Video source from react native camera component to Django server
How can i post video source(Which formate) from react native to Django server after processing video then return to react native Component In my Camera Component try { const response = await axios.post('http://localhost:8000/my-post-view/', {videoSource}); setApivideo(response.data); } catch (error) { console.error('Error:', error); } In My Django View def my_post_view(request): if request.method == 'POST': video_uri = request.data.get('videoUri') //Im Processing video Here actually its not reading video_uri - cap = cv2.VideoCapture(video_path) //After processing the video return HttpResponse({'processedData': cap}) I tried above Using Post method but im confused about how to post video source and get Processed video return back to my react native component -
Python import modules in a script is not working
import json import os import django import openai import sys # Ensure the DJANGO_SETTINGS_MODULE is set to your project's settings module. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tastify_backend.settings") django.setup() from recipe.models import Ingredient, IngredientCategory, MeasuringUnit, Recipe print(Ingredient.objects.all().select_related('ingredient_category').filter(ingredient_category=1)) The import of the model does not work, there is the following: Here is the error traceback, so that you can check what I am missing. Traceback (most recent call last): File "/Users/patrickvogele/Desktop/tastify_backend/recipe/scripts/generate_ingredients.py", line 9, in <module> django.setup() File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tastify_backend' Why is that? -
Why does it give an error when trying to do django logging writing its handlers?
settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'database': { 'level': 'DEBUG', 'class': 'megabot.log.DatabaseHandler', }, }, 'loggers': { 'main': { 'handlers': ['database'], 'level': 'DEBUG', 'propogate':True } }, } log.py import logging from .models import Log class DatabaseHandler(logging.Handler): def emit(self, record): log = self.format(record) level = record.levelname message = record.getMessage() Log.objects.create(level=level, message=message) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = DatabaseHandler() formatter = logging.Formatter('%(levelname)s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) models.py class Log(models.Model): level = models.CharField(max_length=50) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I'm trying to set up recording errors directly to my application Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/log.py", line 76, in configure_logging logging_config_func(logging_settings) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/logging/config.py", line 809, in dictConfig dictConfigClass(config).configure() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/logging/config.py", line 571, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'database' -
how to log the user in Directus from a different domain and login form then authenticate him in the Directus admin page
now I have created a Directus application, and am using it as a back-end .. and am letting the user log in from another external domain and form Django app and sending post request to be able to login .. how to stop Derictus from asking him to log in again after i redirect him to the Directus admin panel link after login success ? here are some of the codes I have used for the whole process : docekr-compose.yaml for the Directus part : version: "3" services: db: image: ${DB_IMAGE} container_name: ${DB_CONTAINER_NAME} volumes: - ${DB_VOLUME} ports: - '${DB_PORT}:5432' restart: always environment: - POSTGRES_DB=${DB_DATABASE} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} # - PGDATA=/tmp directus: image: directus/directus:10.7.1 container_name: ${WEB_CONTAINER_NAME} ports: - ${APP_PORT}:8055 restart: always volumes: - ./uploads:/directus/uploads environment: KEY: ${KEY} SECRET: ${SECRET} ADMIN_EMAIL: ${ADMIN_EMAIL} ADMIN_PASSWORD: ${ADMIN_PASSWORD} DB_CLIENT: ${DB_CLIENT} DB_FILENAME: ${DB_FILENAME} DB_HOST: ${DB_HOST} DB_PORT: 5432 DB_DATABASE: ${DB_DATABASE} DB_USER: ${DB_USER} DB_PASSWORD: ${DB_PASSWORD} WEBSOCKETS_ENABLED: true depends_on: - db and my Django logic : def authenticate_user(request): print("function called") if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') # Create a JSON payload data = { "email": email, "password": password } # Send a POST request to the external API url = "http://<my_domain>:<port>/auth/login" headers = {'Content-Type': 'application/json'} … -
Djnago Admin : Country/State/City Dropdown
I'm trying to do a chained dropdown of Country/State/City in Django Admin I know there is lot of post about this, And this is very basic problem. Is there any good solution or builtin solution that Im missing, Can anyone tell, How to solve it or guide in proper direction?