Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-allauth cant select providers using administration page
I'm trying to add google authentication, I added 'allauth.socialaccount.providers.google' into installed apps and created SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } }, } but administration page doesnt show me this provider no option to select google Having followed all the required steps in the docs, obtained client id and secret key e and I also have refreshed, cleared cache, run makemigrations and migrate many times but the field won't show 'google' as the option. Could you show me the way to solve this? Thank you! -
save an image to media in post method django
I want to store an image in the media folder and the URL in the image field of the model. in this code the image is directly get saved to the model class CustomUser(AbstractUser): email = models.CharField(max_length=50,unique=True, null=True) username = models.CharField(max_length=50) userimage = models.ImageField(upload_to='profile/', null=True) phone = models.CharField(max_length=50) password = models.CharField(max_length=500) account_id = models.UUIDField(default=uuid.uuid4, editable=False) business = models.ForeignKey('company.Company', on_delete=models.CASCADE, null=True) and the view.py @api_view(['POST']) def CreateAcc(request): if request.method == 'POST': data = request.data password = make_password(data["password"]) mail = data['mail'] name = data['name'] phone = data['phone'] image = data['image'] CustomUser.objects.create(email=mail, username=name,phone=phone, password=password,userimage=image ) return Response(True) How to save the image the the media file ? -
Can't pass instance while creating an DB entry in django
I have two models, DocumentData & RecurringInvoice, which have a one to one relationship with each other. When I create an entry in the RecurringInvoice table, I want to pass in the DocumentData instance, instead of the id. But I get an error saying: {'document_data': [ErrorDetail(string='Incorrect type. Expected pk value, received DocumentData.', code='incorrect_type')]} It works if I pass the id of the instance though. From what I know, we can pass in either the instance or the id to link the entries. So why does it fail when I pass the instance? Relevant controller code: try: # get the document data instance doc_data = DocumentData.objects.get(id=docDataID) except DocumentData.DoesNotExist: return Response({ "message": "Document data does not exist" }, status=status.HTTP_400_BAD_REQUEST) invoice_serializer = RecurringInvoiceSerializer( data={ "document_data": doc_data, "send_date": request.data["send_date"], "recipients": request.data["recipients"], "invoice_name": request.data["invoice_name"] } ) if not invoice_serializer.is_valid(): print(invoice_serializer.errors, invoice_serializer._errors) return Response({"message": "Failed to save invoice data"}, status=status.HTTP_400_BAD_REQUEST) invoice_serializer.save() RecurringInvoice model: class RecurringInvoice(models.Model): document_data = models.OneToOneField( DocumentData, on_delete=models.CASCADE, null=True, blank=True) send_date = models.IntegerField( default=1, validators=[MinValueValidator(1), MaxValueValidator(28)] ) invoice_name = models.CharField(max_length=255) recipients = ArrayField(models.CharField(max_length=100)) is_paused = models.BooleanField(default=False) stop_date = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"ID: {self.id}, Name: {self.invoice_name}, Active Till: {self.stop_date}" class Meta: verbose_name = "Recurring Invoice" … -
LDAP Authentication with Django Rest Framework
I am new to Django and i am using Django Rest Framework for Backend. I followed this tutorial to add Ldap authenrication to my Django Rest Framework project. AUTH_LDAP_SERVER_URI = "ip" AUTH_LDAP_BIND_DN = "dn" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,tempelate" but when i try to login i get the error { "non_field_errors": [ "Unable to log in with provided credentials." ] } Where did i go wrong. The IP points to the correct address of Active Directory, the bind DN and Passwords are the ones i used in my Moodle Application and they work.I believe AUTH_LDAP_USER_DN_TEMPLATE corresponds to context. AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"] Here is the Authentication Backends. -
html dropdown subject list filter
me working on python django school LMS project and facing issue in html dropdown filter. there are 3 fields. teacher name, subject list, and checkbox of classes. If I select class 1 one then that time subject dropdown should be show only related subject but in subject list its showing all subject from database. i will attach a code and required output for reference. </head> <body> <script> function showSuccessPopup() { alert("Successfully Submitted"); } </script> <h2 style="text-align: center;">Assign Subjects and Classes to Teachers</h2><br> <div class="container"> <div class="card"> <form method="post" onsubmit="showSuccessPopup()"> {% csrf_token %} <div class="form-group"> <label for="teacher">Teacher:</label> <select name="teacher" id="teacher" class="form-control"> <option>----Select Teacher----</option> {% for teacher in teachers %} <option value="{{ teacher.id }}">{{ teacher.first_name }} {{ teacher.last_name }}</option> {% endfor %} </select> </div><br> <div class="form-group"> <label for="subject">Subject:</label> <select name="subject" id="subject" class="form-control"> <option>----Select Subject-----</option> {% for subject in subjects %} <option value="{{ subject.id }}">{{ subject.name }}</option> {% endfor %} </select> </div><br> <div class="form-group"> <label for="classes">Classes:</label> {% for cls in classes %} <div class="form-check"> <input type="checkbox" name="classes" value="{{ cls.id }}" class="form-check-input"> <label class="form-check-label">{{ cls.classes }}</label> </div> {% endfor %} </div> <button type="submit" class="btn btn-primary">Assign</button> </form> </div> </div> </body>[dropdown subject](https://i.sstatic.net/Tgkf4GJj.jpg) expected output in subject dropdown -
Django - Request Header Fields Too Large
We use an OAuth2-Proxy for our apps. Therefore the request header includes all groups of a user and the header get large. This is no problem for our fastAPI based apps but not for Django based apps. We always get 431 (Request Header Fields Too Large). Any ideas how to increase the max header value in Django? Request Header Fields Too Large Error parsing headers: 'limit request headers fields size' -
Django File Upload Not Working: Files Not Appearing in Media Directory or Database
I am developing a Django application where users can upload files associated with specific topics and submissions. Despite setting up everything according to the Django documentation, the files do not appear in the specified media directory or in the database after upload. I am using Django 5.0.4 and Python 3.10. Models.py: class File(models.Model): topic = models.ForeignKey(Topic, related_name='files', on_delete=models.CASCADE, null=True) submission = models.ForeignKey(Submission, related_name='files', on_delete=models.CASCADE, null=True) filename = models.FileField(upload_to='submissions/', null=True) upload_date = models.DateTimeField(auto_now_add=True) is_accepted = models.BooleanField(default=False) def __str__(self): return f"File: {self.filename.name} for Topic: {self.topic.name}" Forms.py: class UploadFileForm(ModelForm): class Meta: model = File fields = ('filename',) Views.py: def upload_file(request, subm_id, topic_id): submission = get_object_or_404(Submission, pk=subm_id) topic = get_object_or_404(Topic, pk=topic_id) form = UploadFileForm() context = {'submission':submission, 'topic':topic, 'form': form} if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_instance = form.save(commit=False) file_instance.topic = topic file_instance.submission = submission file_instance.save() messages.success(request, 'File succesfully uploaded') return redirect('upload_file', subm_id=submission.id, topic_id=topic.id) else: print(request.FILES) messages.error(request, 'No file was uploaded') form = UploadFileForm() return render(request, 'users/upload_file.html', context=context) Settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' Template: <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label class="form-label" for="{{ form.filename.id_for_label}} " >Загрузите файл</label > {{ form|crispy }} </div> <input class="btn btn-secondary" type="submit" value="Submit" /> </form> What could be causing … -
Wanted to build a cloud service where a static file is accessible on every dynamically generated URL
I aim to access specific static files and HTML pages stored in either an S3 bucket or an Azure blob container using various URLs. The concept involves our server generating dynamic URLs in a specific format and then responding with a redirect to the client. Ultimately, I wanted to show the client the same content on the dynamic URL they are redirected to. I anticipate that an HTML page named "x" will be accessible via hundreds of URLs, such as https://base_url/x/1, https://base_url/x/2, https://base_url/x/3, and so forth, up to https://base_url/x/100. -
Cryptography Fernet Invalid Token
I am trying in Python Django to create a system for encrypting and decrypting messages. Does anyone know why I get an error every time I try to read a message: "The encrypted message is invalid and cannot be decrypted". Below is my code: `class MessageSerializer(serializers.ModelSerializer): created_by = BasicUserSerializer(read_only=True) class Meta: model = Message fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) load_dotenv() self.ENCRYPTION_KEY = "key_generated_by_fernet.generate_key()" self.fernet = Fernet(self.ENCRYPTION_KEY) def to_representation(self, instance): representation = super().to_representation(instance) representation['text'] = self.decrypt(instance.text) return representation def encrypt(self, message): encoded_message = message.encode() encrypted_message = self.fernet.encrypt(encoded_message) return encrypted_message def decrypt(self, encrypted_message): try: decrypted_message = self.fernet.decrypt(encrypted_message) decoded_message = decrypted_message.decode() return decoded_message except InvalidToken: raise ValueError("The encrypted message is invalid and cannot be decrypted.")` Has anyone ever had a similar problem and knows how to solve it? -
Trouble in setting up virtual environment for django in device
After running installation command , the output are as follows. please help me in setting up virtual env for django \Django>pip install virtualenv Requirement already satisfied: virtualenv in c:\python311\lib\site-packages (20.26.1) Requirement already satisfied: distlib<1,>=0.3.7 in c:\python311\lib\site-packages (from virtualenv) (0.3.8) Requirement already satisfied: filelock<4,>=3.12.2 in c:\python311\lib\site-packages (from virtualenv) (3.12.4) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\python311\lib\site-packages (from virtualenv) (4.2.1) D:\Django>virtualenv env 'virtualenv' is not recognized as an internal or external command, operable program or batch file. Please provide me with commands to write first django program in virtual environment. I have been trying the same from 2 days but unable to do so. please help me . And provide commands to run my first program in djano in VScode -
Django Test - How to work out why not redirecting
I have the following Django Test for a CreateView: def test_post_non_chargeable(self): self.client.force_login(self.user) form = EditStudyForm(data=self.non_chargeable_payload) self.assertTrue(form.is_valid()) response = self.client.post(self.url, self.non_chargeable_payload) self.assertRedirects(response, reverse("researcher_ui:console_study", kwargs={"pk": self.study.pk})) The first test, that the form is valid works. The second test doesn't work. The response is not redirecting but getting a 200 response. How do I work out why it isn't redirecting when the form is valid and it does when I use the application? -
How to fix the ImportError: cannot import name 'formatargspec' from 'inspect' (/usr/lib/python3.12/inspect.py). Did you mean: 'formatargvalues'?
I'm trying to run django app usind docker .. it gives me this error when i try to docker-compose up --build : water_maps | File "<frozen importlib._bootstrap>", line 1387, in _gcd_import water_maps | File "<frozen importlib._bootstrap>", line 1360, in _find_and_load water_maps | File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked water_maps | File "<frozen importlib._bootstrap>", line 935, in _load_unlocked water_maps | File "<frozen importlib._bootstrap_external>", line 995, in exec_module water_maps | File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed water_maps | File "/var/www/html/demo_app/water_maps/__init__.py", line 4, in <module> water_maps | from celery import Celery water_maps | File "/usr/local/lib/python3.12/dist-packages/celery/__init__.py", line 17, in <module> water_maps | from . import local # noqa water_maps | ^^^^^^^^^^^^^^^^^^^ water_maps | File "/usr/local/lib/python3.12/dist-packages/celery/local.py", line 17, in <module> water_maps | from .five import PY3, bytes_if_py2, items, string, string_t water_maps | File "/usr/local/lib/python3.12/dist-packages/celery/five.py", line 7, in <module> water_maps | import vine.five water_maps | File "/usr/local/lib/python3.12/dist-packages/vine/__init__.py", line 8, in <module> water_maps | from .abstract import Thenable water_maps | File "/usr/local/lib/python3.12/dist-packages/vine/abstract.py", line 6, in <module> water_maps | from .five import with_metaclass, Callable water_maps | File "/usr/local/lib/python3.12/dist-packages/vine/five.py", line 364, in <module> water_maps | from inspect import formatargspec, getargspec as _getargspec # noqa water_maps | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ water_maps | ImportError: cannot import name 'formatargspec' from 'inspect' (/usr/lib/python3.12/inspect.py). … -
Django serializer is not validating or saving data
I am trying to save data in the database, it works for most of my models but for few models I am not sure why but django is not serializing data. I hope someone can point out where I might be doing wrong. Here is my code Django Models class UserModel(AbstractUser): uuid = models.UUIDField(default=uuid.uuid4, editable=False) class UserWorkPresenceModel(models.Model): user = models.ForeignKey("UserModel", on_delete=models.CASCADE, related_name="workpresence") is_active = models.BooleanField(default=False) check_in = models.DateTimeField(blank=False) check_out = models.DateTimeField(blank=True, null=True) work_break = [] class UserWorkBreakModel(models.Model): work_presence = models.ForeignKey("UserWorkPresenceModel", on_delete=models.CASCADE, related_name="work_break") start_break = models.DateTimeField(blank=True) end_break = models.DateTimeField(blank=True, null=True) is_current_break = models.BooleanField(default=False) Serializer: class UserTakeBreakSerializer(serializers.Serializer): class Meta: model = UserWorkBreakModel # fields = ("start_break", "end_break") fields = '__all__' API View class UserStartWorkBreakView(APIView): def post(self, request, id): try: user = UserModel.objects.get(uuid=id) except: return Response({'message': 'User not found'}, status=HTTP_400_BAD_REQUEST) try: work_presence = UserWorkPresenceModel.objects.get(user=user, is_active=True) except UserWorkPresenceModel.DoesNotExist: return Response({'message': 'User work presence not found'}, status=HTTP_400_BAD_REQUEST) currently_onbreak = UserWorkBreakModel.objects.filter(work_presence=work_presence, is_current_break=True) if currently_onbreak.exists(): return Response({'message': 'User already working'}, status=HTTP_400_BAD_REQUEST) serializer = UserTakeBreakSerializer(data=request.data) print(serializer) if serializer.is_valid(): print(f'validated_data: {serializer.validated_data}') user.workpresence_status = UserWorkPresenceStatus.ON_BREAK serializer.validated_data['is_current_break'] = True serializer.save(work_presence=work_presence) user.save() print(f'serializer.data: {serializer.data}') return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) I'm not getting any error just empty dictionary, here is result of my print commands: UserTakeBreakSerializer(data={'start_break': '2024-05-10 15:05:52.829867'}): validated_data: {} serializer.data: {} … -
django-ckeditor: html template doesn't render my ckeditor content properly although I am using {{ content | safe }}
I am using the django-ckeditor plugin to implement a ckeditor field in my django website. I have an updateView where you can edit the "notes" attribute of a model called Server. The ckeditor widget is working perfectly here in my server_update_form.html: <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0"> <form class="w-full" action="" method="post"> {% csrf_token %} {{ form.media }} <table> <div class="relative z-0 w-full mb-5 group"> <form class="max-w-sm mx-auto"> <label for="notes" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{{ form.notes.label_tag }}</label> {{ form.notes }} </form> </div> </table> <button type="submit" style="display:block" class="w-1/10 text-white bg-orange-600 hover:bg-orange-700 focus:ring-4 focus:outline-none focus:ring-orange-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center"> Submit </button> </form> </div> This is how it looks like I also have a DetailView where I would like to display the content inside server.notes without being able to edit it. My server_detail.html looks like this: {% if server %} <h1 class="mb-8 text-3xl font-bold">Server: {{ server.displayname }}</h1> </div> <div class="flex flex-col pt-3"> <dt class="mb-1 text-gray-500 md:text-sm dark:text-gray-40">Notes</dt> <dd class="text-md mb-5 p-2 border rounded-md"> <form>{{ server.notes |safe }} </dd> </div> </dl> But html doesn't render the notes properly: DetailView page model.py: class Server(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this server", editable=False) ip_address = models.CharField(max_length=30, help_text="Enter servers … -
Celery Command Not Found When Running from Docker Entrypoint Script
I am deploying a Django application using Docker onto ECS and encountering an issue where Celery commands specified in my entrypoint.sh script are not being recognized, resulting in errors. My Docker setup involves using Celery for asynchronous task processing, with separate containers for Celery workers and beat scheduled tasks. I get the following error messages when I create the ECS which includes the celery worker and beat as containers within the same task definition. Error Messages: /app/entrypoint.sh: line 28: exec: celery -A healthcare_project worker -l info: not found /app/entrypoint.sh: line 28: exec: celery -A healthcare_project beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler: not found Entrypoint Script (entrypoint.sh): #!/bin/bash # Exit script in case of error set -e # Apply database migrations echo "Applying database migrations..." python manage.py migrate --noinput # Collect static files echo "Collecting static files..." python manage.py collectstatic --noinput --clear # Debugging: List installed packages and show PATH echo "Installed Python packages:" pip freeze echo "Current PATH in Docker: $PATH" # Check if celery command is passed if [[ "$1" == "celery" ]]; then # Shift command line arguments left shift 1 # Execute the celery command with the passed arguments exec /usr/local/bin/celery -A healthcare_project "$@" else # Start command … -
Two instances of django project (same project) - sharing static?
I'd like to setup two (or more) instances of django project, with separate databases (so far it is easy). But, I think static files (that are massive - images, css, html ,js etc) - can be only in one place. No need to copy it multiple times, as they are not changing. Is it possible to setup it that way? Like some hardcoded path to static folder, outside of "project-instance" path? -
Django bulk upload takes 30 seconds to process 100 records
I have working on a travel insurance project, by which on my requirements is to allow agents to bulk upload travellers with pre-bought policies and packages. I have somehow managed to create this process, but unfortunately 100 rows of excel sheet takes 30 seconds to process. Its very bad in user experiences, most of the agents will be uploading 1000 travellers per month atleast. Please help on pointing out the issue and how this can be optimised further ? This is flow: Admin -> Creates Benefits ( For ex: Medical Expense, theft etc) Admin -> Create Policy -> Attach Package (one policy can many package) -> Choose Benefits and its limits -> Done (Note: Each benefit will have allocated amount stored in PackageBenefit table while creating Policy) Agents -> Upload Traveller via Excel Excel -> User -> Traveller -> PolicyHolder (traveller who bought policy) ->PolicyUsage (this is where i store Package details, Benefits and its allocated amount) These are the models User Traveller (1-1 with user) Policy Package (Foreign with Policy) Benefits PackageBenefit (Foreign with Policy, Package, this holds max_allocated money for the benefit in package) PolicyHolder (Stores all information when traveller buys/attaches to a policy, foreign with traveller, policy, … -
How do I manage the queue of hundreds of GET to be made in a given time with Django?
Good morning, I need to create a Django service that checks the status of hundreds of servers, the GET is routed to the healthcheck/ endpoint of hundreds of microservices, the user can enter the microservice to check and can enter the seconds before making another check: model class Target(models.Model): # ip address service_name = models.CharField( _("Service address"), max_lenght=90, blank=False, null=False ) # seconds (cron) check_every_seconds = models.IntegerField(_("Check every x seconds"), default=3600) is_active = models.BooleanField(_("Is Active")) What is the best approach to managing the queue? What is best for me to use? Celery? Thanks. -
"User matching query does not exist" When tried to follow a user
I am building a small social media website using Django, When I Click on follow button, I get this error saying: "User matching query does not exist." And showing the error here in the profile view function"user_object = User.objects.get(username=pk) this is the follow function in view.py file, def Follow(request): if request.method == "POST": follower_username = request.POST['follower'] user_username = request.POST['user'] # Get User model instances based on usernames follower_user = User.objects.get(username=follower_username) user_user = User.objects.get(username=user_username) if FollowersCount.objects.filter(follower=follower_user,user=user_user).first(): delete_follower = FollowersCount.objects.get(follower=follower_user,user=user_user) delete_follower.delete() else: add_follower = FollowersCount.objects.create(follower=follower_user,user=user_user) add_follower.save() return redirect('profile',username=follower_user) I tried to give try and except to the user_object, but it didn't work this is the profile view function, def Profile_view(request,pk): user_object = User.objects.get(username=pk) user_profile = Profile.objects.get(user=user_object) user_post = Post_Upload.objects.filter(user=user_object) following_count = FollowersCount.objects.filter(follower=user_object).count() followers_count = FollowersCount.objects.filter(user=user_object).count() post_count = user_post.count() context = { "user_profile":user_profile, "user_post":user_post, "post_count":post_count, "following_count":following_count, "followers_count":followers_count, } return render(request, 'profile.html',context) -
Gunicorn Running Django Project: nohup Instance Works Fine, systemd Service Instance Returns 400 Error
Problem Description: I'm encountering an issue with my Gunicorn setup while running a Django project. Specifically, I have two instances of Gunicorn running the same Django project: one using nohup and the other implemented as a systemd service. Surprisingly, the instance running with nohup works perfectly fine, while the one set up as a systemd service consistently returns a 400 error. Background Information: I'm running a Django project with Gunicorn as the WSGI server. Each instance of Gunicorn is configured identically. Both instances are using the same Django project and Gunicorn configuration. Steps Taken: nohup Instance: I'm starting the nohup instance using the following command: nohup /home/user/project_backend/venv/bin/gunicorn --workers 5 --bind 0.0.0.0:8000 backend.wsgi:application & It works perfectly fine! Run Gunicorn as a systemd service, create or open the config file:sudo nano /etc/systemd/system/gunicorn.service Following is gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=user WorkingDirectory=/home/user/project_backend ExecStart=/home/user/project_backend/venv/bin/gunicorn --workers 5 --bind 0.0.0.0:8000 ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed TimeoutStopSec=5 [Install] WantedBy=multi-user.target and thenrun sudo systemctl daemon-reload to apply the config change and sudo systemctl start gunicorn Attempted to send the same HTTP request to both instances: Request sent to nohup instance: success Request sent to systemd service instance: failure (returned 400 error) Has anyone encountered a … -
Django Infinite Scroll repeats the whole page, how do I solve this so it just repeats the content?
Making a django app, that lists off articles. Rather than pagenate manually with a page 2 button, I'd rather try and get infinite scroll working. Been trying some HTMX, Django native, and JS solutions but I'm not that experienced and I've struggled to get anything working. I found an HTMX solution that I got working, however because my view renders the whole page, rather than get the article segment, the infinite scroll just loads the entire webpage at the bottom again, header, navigation and all. I've tried to tweak some things, experiment with a view within a view but couldn't quite get it working. Below is my code. My view: @csrf_protect def Home(request,filtr): # Create a Session ID if one isn't already available for JS if not request.session.exists(request.session.session_key): request.session.create() session = request.session.session_key # ----- ----- f = filtr # filter for page view type p = 6 # page limit page = request.GET.get("page") # ----- ----- # Editors Pick curated = ContentQuery(3) # Filter View if f == 1: # Newest items = ContentQuery(f) elif f == 2: #Random items = ContentQuery(f) else: # Trending items = ContentQuery(f) paginator = Paginator(items,p) page_obj = paginator.get_page(page) try: content = paginator.page(page) except PageNotAnInteger: … -
Fetch all data with single query in Django
How to fetch all child related objects in a single query in Django? For example we have 3 models: class Parent(models.Model): ... class Child(models.Model): parent = models.ForeignKey(Parent) class SubChild(models.Model): parent = models.ForeignKey(Child) I want to fetch all the data in a single query like this: select * from parent p join child c on c.parent_id = p.id join subchild sc on sc.parent_id = c.id How I could perform this using Django ORM? What if I will have multiple child models? In SQL I just add more joins, but how I could do it in Django? Now I have few seconds delay when load everything recursively with multiple queries. The prefetch_related method does not help, I mean qs = Parent.objects.all().prefetch_related('child').prefetch_related('child__subchild') for parent in qs: # here I need to access parent.childs.all() and child.subchild.all() without new queries -
Django REST API Form Showing "Content" Only
In my REST API screen I'm seeing this view: Instead of the "Content" field I used to see a form where I could input data. Now my only option is to manually write in JSON. I'm not entirely sure when/how this change happened so I'm at a bit of a loss for where to look to change it back. I've tried changing the media type on this page but that has no effect. Does anyone know how this field is generated and how I can switch it back to the form data instead? Thanks, Mitchell -
How to Display a Modal on Click Event of a Polygon in a Django Class-Based View Using Folium Map?
I'm using Folium in a Django CBV to display a map with polygons. How can I trigger a modal to appear with more region details when a user clicks on a polygon? ` def get(self, request, *args, **kwargs): context = {} # Retrieve form and queryset data context['RegionalMalnutritionForm'] = RegionalMalnutritionForm() context['regional_levels'] = RegionalLevel.objects.all() context['national_levels'] = NationalLevel.objects.filter(age_category=1, year_record=1) #for Default map when open the pages - Regional is the default for malutrition module min_id = YearCategoryMalnutrition.objects.all().order_by('id').first().id age_category_min_id = AgeCategory.objects.all().order_by('id').first().id coodinate_locations = RegionalLevel.objects.filter(year_record=min_id,age_category=age_category_min_id) geo_data = {"type": "FeatureCollection", "features": []} for location in coodinate_locations: json_string = location.regional_level_coordinate.region_coordinate polygons_type = location.regional_level_coordinate.geo_type malnutrition_category = location.malnutrition_category percentage = location.percentage age_category = location.age_category color = location.color.hex_color region_name = location.region_name geo_data['features'].append(self.create_geojson_feature(json.loads(json_string,), polygons_type, percentage,age_category,malnutrition_category,color,region_name)) folium_map = self.create_map() # Add the feature to the map with the popup folium.GeoJson( geo_data, highlight_function=highlight_function, style_function=style_function, tooltip=folium.features.GeoJsonTooltip( fields=['Data'], aliases=[''], localize=True, style="background-color: rgba(0, 0, 0, 0.5); color: white; font-size: 16px; padding:8px;", ), ).add_to(folium_map) # Convert map to HTML representation context['folium_map'] = folium_map._repr_html_()` I tried adding an onclick event to the polygons in my Folium map within a Django class-based view, expecting a modal to be triggered on click. The modal should display detailed information about the clicked region. However, this doesn't work as expected and … -
Django Admin Import Error: NOT NULL Constraint Failed for ForeignKey Field in CSV Import
I'm experiencing a persistent issue with importing CSV data into my Django project using the django-import-export library in the admin panel. When trying to import records for a Copy model which has ForeignKey relations, I keep encountering a NOT NULL constraint failed error for the book_id field. AGAIN THIS ONLY OCCURS IN THE ADMIN PANEL, I have tested in shell and it works. I am sure there is no issue with the CSV and likely not even the resources/models files. It seems something is going wrong with the admin logic before the actual import. Error looks like this but for every single row. It occurs when hitting "submit". I never even get to "Confirm Import" button Line number: 1 - NOT NULL constraint failed: catalog_copy.book_id Line number: 2 - NOT NULL constraint failed: catalog_copy.book_id Line number: 3 - NOT NULL constraint failed: catalog_copy.book_id Line number: 4 - NOT NULL constraint failed: catalog_copy.book_id Line number: 5 - NOT NULL constraint failed: catalog_copy.book_id Line number: 6 - NOT NULL constraint failed: catalog_copy.book_id Line number: 7 - NOT NULL constraint failed: catalog_copy.book_id Line number: 8 - NOT NULL constraint failed: catalog_copy.book_id Line number: 9 - NOT NULL constraint failed: catalog_copy.book_id Line number: 10 …