Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello sir, I am learning Django. The server was working fine till now but when I created the index.html file in the template, I am facing problem
My django server is not working properly. When I load my website it shows nothing. How can I fix this problem, I checked all my setting and views.py, and urls.py all are ok but when I save all these my server loads but when I go to the website and paste the url.. it shows nothing. I try all the things to fix this error but nothing happens. -
Forbidden (403) CSRF verification failed. Request aborted. while logging in in Label Studio
Once labelstudio is updated to version and run from commandline: LABEL_STUDIO_DISABLE_SIGNUP_WITHOUT_LINK=true CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1 HOST='https://...' nohup label-studio -b --data-dir /label-studio/data/ -db /label-studio/db.sqlite --log-level INFO --internal-host localhost -p 8080 --host https://... --agree-fix-sqlite > label-studio.out 2> label-studio.err & On login attempt it results in an issue: Forbidden (403) CSRF verification failed. Request aborted. The setup is Python 3.11.11 with the following relevant modules: label-studio==1.15.0 label-studio-converter==0.0.59 label-studio-sdk==1.0.8 label-studio-tools==0.0.4 -
What is pytests equivalent to setUpTestData in Django?
I have seen TestCase.setUpTestData which improves test speed quite a bit in my case. I typically prefer pytest fixtures instead of the TestCase classes. However,when I make a session-scope fixture which does data preparation needed for all tests with the fixture, I get RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I followed https://stackoverflow.com/a/72261942/29412366, but that had no effect. How can I store and re-use a DB state within a Django application when testing using pytest? I use an in-memory sqlite3 DB. I tried https://stackoverflow.com/a/72261942/29412366 : @pytest.mark.django_db @pytest.fixture(scope='session') def thing(django_db_setup, django_db_blocker): del django_db_setup # Cannot be used with usefixtures(..) it won't work with django_db_blocker.unblock(): print('sleeping') Thing.objects.create(thing='hello') and expected the test to run successfully + save time. Instead, I got the RuntimeError mentioned above. (function-scoped fixtures work fine, but then I don't save any test execution time) -
Django NFC Writing Issue on Production - HID Omnikey 5422 - "Service not available" Error
I am developing a Django web application to write to an NFC card using the HID Omnikey 5422 reader. Everything works fine on localhost, but when I deploy it to the production server, I get the following error: Console Error: jquery.min.js:2 POST https://demo.infoidz.com/portal/write-to-nfc/ 500 (Internal Server Error) Django Server Error: Error writing link to NFC card: Failed to establish context: Service not available. (0x8010001D) -
Advice on Choosing a Full Stack Development Stack for a STEM Student
I am a new STEM student with experience in machine learning projects. My academic curriculum now requires me to learn a full stack development stack. I would appreciate your advice on which stack to choose. I have prior knowledge of Python and a basic understanding of HTML, CSS, and JavaScript. Could you please recommend the most widely used stacks in the current industry? Thank you! -
Images not displaying after deploying Django app to Render, but they work locally
I’ve deployed my Django application on Render, and while everything works perfectly locally (including images), the images are not displaying after deployment. The other static files, like CSS and JavaScript, are loading fine, so I believe the issue might be specific to serving media files. Here’s what I’ve checked so far: MEDIA_URL and MEDIA_ROOT: I’ve configured the MEDIA_URL and MEDIA_ROOT in my settings.py as follows: python Copy Edit MEDIA_URL = '/media/' MEDIA_ROOT = '/mnt/data/media' # Path to Render persistent disk Persistent Disk: I’m using Render's persistent disk and confirmed that the images are correctly uploaded to the server. File Permissions: I’ve checked the file permissions, and they seem to be correct. However, despite all this, the images are not showing up on the live site. Can anyone help me figure out why the images aren’t displaying on Render? Do I need to adjust the configuration for serving media files, or is there something I missed in the deployment process? Thanks in advance! I’ve deployed my Django application on Render, and while everything works perfectly locally (including images), the images are not displaying after deployment. The other static files, like CSS and JavaScript, are loading fine, so I believe the issue … -
Is there any way to handle this error I'm facing with my Django project?
Refused to execute script from 'http://127.0.0.1:8000/static/js/register.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I keep getting this error even thought I have the register.js file at the right place. I expected my javascript codes to function but it doesn't. -
Django imported database -- am I doing it wrong? Is Django not fit to purpose here?
So perhaps I'm missing something conceptually, or simply doing it wrong. Or, worst case scenario, "that's not what Django is for" :-/ I have set up my Django instance to fully take advantage of an external database which contains, amongst other things, all of my iTunes (no, not Music) data, with an extensive changelog. That's tangential to my question but I wanted to throw it out to show that I'm not a complete beginner (I even have it set so Django doesn't mess w/the external read-only database, which is a bit of a feat). What I'm trying to do is import this into Django models in my actual Django database, to take advantage of the Django admin, preparatory to creating a web app around all of this. I've set up the Django models, and created some (SQLAlchemy) routines to ETL my data into three tables (Songs, Artists, Albums). I have a lot of data (783122 songs from 59445 albums by 97562 artists), but that shouldn't overload a robust framework like Django, I wouldn't think. So the data's imported & I've set up a basic admin which should simply show the songs inline when I go to the admin page for … -
how to get django-response on django-request
How to send a django.http.HttpRequest object and receive a django.http.HttpResponse object inside a view? In other words, whats the analogue of python-requests-: response = requests.request(**data) using django.http.HttpRequest and django.http.HttpResponse accordingly -
Error: "405 Client Error: Method Not Allowed" while connecting to IPFS using ipfshttpclient in Django project
I’m working on a Django project where I’m using IPFS to store and retrieve files. However, I’m encountering an issue when trying to use the ipfshttpclient (or ipfsapi) library to connect to the IPFS daemon. When I run the migrate command in my Django project, I get the following error: 405 Client Error: Method Not Allowed for url: http://localhost:5001/api/v0/version?stream-channels=true (env) root@LAPTOP-SEOPFS2E:~/project/EMS/env/project/clgproject# python manage.py migrate /root/project/EMS/env/project/clgproject/EMS/views.py:12: FutureWarning: The `ipfsapi` library is deprecated and will stop receiving updates on the 31.12.2019! If you are on Python 3.5+ please enable and fix all Python deprecation warnings (CPython flag `-Wd`) and switch to the new `ipfshttpclient` library name. Python 2.7 and 3.4 will not be supported by the new library, so please upgrade. import os, requests, ipfsapi , ipfshttpclient #added by DD 'ipfshttpclient' Traceback (most recent call last): File "/root/project/EMS/env/lib/python3.8/site-packages/ipfshttpclient/http.py", line 266, in _do_raise_for_status response.raise_for_status() File "/root/project/EMS/env/lib/python3.8/site-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 405 Client Error: Method Not Allowed for url: http://localhost:5001/api/v0/version?stream-channels=true The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/root/project/EMS/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/project/EMS/env/lib/python3.8/site-packages/django/core/management/__init__.py", line … -
Saving data to the database in django
I am working on a website to recommend stocks on the stock market, based on historically reliable trading strategies. When running the server, I can't see any of the data which is supposed to be shown on the website. Looking into the db, it appears that most of the data is not being saved to the db. There is also another problem, which may be related: When running the code, I am getting the company name for the last stock which is being looped through, but for the others there it just says 'None'. I would be grateful if anyone can help me with this. Here is the code to loop through each stock: def compile_queue(self): from stock.models import Stock list_of_stocks = Stock.objects.prefetch_related("stock_data", "strategies", "recommendations").values('ticker')[0:101] for i in list_of_stocks.values(): try: #Update db with new data ticker = i.ticker stock_object = Stock_Class(ticker) self.list_of_operations.append(lambda i=i: stock_object.update_data(i)) # Get strategy objects moving_average_strategy = Moving_Average_Strategy(ticker) rsi_strategy = RSI_Strategy(ticker) bollinger_band_strategy = Bollinger_Bands_Strategy(ticker) # Add strategies to the queue self.list_of_operations.append(lambda:moving_average_strategy.apply_strategy()) self.list_of_operations.append(lambda:rsi_strategy.apply_strategy()) self.list_of_operations.append(lambda:bollinger_band_strategy.apply_strategy()) self.list_of_operations.append(lambda:stock_object.set_recommendations(i)) except Exception as e: print(f"(Trading_System.py) The required actions for {i} could not be run due to Error: {e}") Here is part of the code which gets the data for a given stock and … -
How to limit admin django session and renew time after user action
I am improving my django admin session security and I wanted to do 2 things: Limit my admin session time Renew my session time after every user action What is the best way to do? -
How can i use exiftool in django?
I bought my first VPS server and I have ubuntu system on it. I installed exiftool via ‘sudo apt install exiftool’ and when I say the command which exiftool everything is fine I get the response /usr/bin/exiftool. After that I try to make a function to change the tags of the photo in django, but django I think doesn't see exiftool and nothing is added. Anyone know what I can do? I've been trying to fix this for about 5 hours :D import subprocess def set_jpeg_metadata_exiftool(): exiftool_path = "exiftool" title = "Title" subject = "Subject" author = "Me" comment = "Comment" rating_val = 5 copyright_val = "Company name" keywords = 'test' cmd = [ exiftool_path, f'-Title={title}', f'-Subject={subject}', f'-Author={author}', f'-Comment={comment}', f'-Rating={rating_val}', f'-Copyright={copyright_val}', f'-Keywords={keywords}', '-overwrite_original', file_path ] subprocess.run(cmd, check=True, encoding='utf-8') -
Django with React using Vite and Inertia
Inspired by https://github.com/mujahidfa/inertia-django-vite-vue-minimalI created https://github.com/anjanesh/inertia-django-vite-react-minimalto use React (19.0.0) in Django (5.1.5) via Inertia (2.0) but : When I run npm run dev and python manage.py runserver and goto localhost:8000, I get in the browser : Uncaught (in promise) Error: @vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201 at Index.tsx:1:26 Works in production though - npm run build and python manage.py collectstatic -
Django 5.1 + Postgresql (debian server)
Trying to connect to posgresql base as Django wrote in its docs: https://docs.djangoproject.com/en/5.1/ref/databases/#postgresql-notes DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "my_service", "passfile": ".my_pgpass", }, } } I've created 2 files in my home directory .pg_service.conf [my_service] host=/var/run/postgresql user=dbms dbname=dbms_db port=5432 .pgpass /var/run/postgresql:5432:dbms_db:dbms:my_password Such command as test of .pgpass: psql -h localhost -U dbms dbms_db is working. But the connect doesn't work: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "my_service", "passfile": ".pgpass", }, } } with such error Traceback (most recent call last): File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 332, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/psycopg/connection.py", line 119, in connect raise last_ex.with_traceback(None) psycopg.OperationalError: connection failed: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "dbms" ... File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/psycopg/connection.py", line 119, in connect raise last_ex.with_traceback(None) django.db.utils.OperationalError: connection failed: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "dbms" whats wrong with my code? Trying to use export vars in debian - but … -
only works on first try with listening to keystrokes on input form field using jquery listener
Here is the basic situation: I want to be able to listen to user input on a text input box, the code will use ajax to check the entry after a pause of 5 seconds, against the cached answer. The check works just fine on the first try (after 5 seconds). But if the user blurs out to another field, then tries a second time to enter the correct answer, editing the same field, nothing happens, the ajax request is not performed. The listener seems to have disappeared or stopped working. Here's the code on the template side: let ajax_call = function (endpoint, request_parameters) { $.getJSON(endpoint, request_parameters) .done(response => { ...... }) //response handling }; answerInputs.on('keydown', function(){ answer = $(this); setTimeout(function(){ var answer_seq = answer.data("sequence"); answers[answer_seq] = answer.val(); var request_parameters = {'answers': JSON.stringify(answers), 'idList': JSON.stringify(idList)} // if scheduled_function is NOT undefined, cancel the execution of the function if (typeof(scheduled_function)!='undefined') { clearTimeout(scheduled_function); } // setTimeout returns the ID of the function to be executed scheduled_function = setTimeout(ajax_call, delay_by_in_ms, endpoint, request_parameters); }, 5000); }); -
The dynamically rendered inputs are not being pulled through to the post request?
Code is used to render the input fields based on the different expense types to the edit form // Clear previous fields dynamicFieldsContainer.innerHTML = ''; // Inject fields dynamically for (const [key, value] of Object.entries(data.fields)) { // Skip fields that are null or undefined if (value === null || value === undefined) continue; const field = ` <div class="mb-3"> <label for="${key}" class="form-label">${key.replace('_', ' ').toUpperCase()}</label> <input type="text" class="form-control" id="${key}" name="${key}" value="${value}" required> </div>`; dynamicFieldsContainer.insertAdjacentHTML('beforeend', field); } These are the hidden fields that are already present on the form and are populated by the JS script these, are the only fields present in the POST request // Set hidden ID field document.getElementById('expense-id').value = data.id; // Set hidden expense-type field document.getElementById('expense-type').value = data.type; The current html structure which shows the form and the post action as well as the hidden and dynamically render html tags <form id="editExpenseForm" name="editExpenseForm" method="post" action="{% url 'edit_expense' %}"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="editExpenseModalLabel">Edit Expense</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <input type="hidden" name="expense-id" id="expense-id"> <input type="hidden" name="expense-type" id="expense-type"> <div id="dynamic-fields"> <!-- Fields will be injected dynamically --> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary">Save Changes</button> </div> </form> -
Getting errors when running automated test for my DRF APi
I’m performing some automated tests on my register/login APIViews (API endpoints) with DRF for my Django project. The trouble I’m running into, I’m not able to successfully run the tests with python manage.py test. I’m sure I set up everything for my APIViews/tests correctly, however I’m getting a traceback error suggesting something might be wrong with my response = self.client.post(url, data, format='json') in my UserRegisterTests from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from ..models import User class UserRegisterTests(APITestCase): def test_register_user(self): url = reverse('register') data = {'email': 'myemail@mail.com', 'password': 'mypassword123'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), 1) self.assertEqual(User.objects.post().email, 'myemail@mail.com') self.assertTrue(User.objects.check_password('mypassword1123')) And there might be something wrong with the if serializer.is_valid(): in my register APIView (views) # API endpoint for registration @authentication_classes([JWTAuthentication]) class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response({ 'message': 'successfully registered', }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This may be of some help, here is my RegisterSerializer class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'password', 'password2'] def validate(self, valid): if valid['password'] != valid['password2']: raise serializers.ValidationError({"password": "Passwords do not match."}) return valid def create(self, validated_data): user = User.objects.register_user( email=validated_data['email'], pasword=validated_data['password'] … -
Why the get request won't get data from connected models?
My GET request to list all the posts and comments and replies, doesn't get all the connected models. models.py from django.db import models from django.contrib.auth import get_user_model from django.conf import settings User = get_user_model() class Post(models.Model): id = models.AutoField(primary_key=True) text = models.TextField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author}: {self.text}' class Images(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='images/') post_id = models.ForeignKey(Post, on_delete=models.CASCADE) class Comment(models.Model): id = models.AutoField(primary_key=True) text = models.CharField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class CommentSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) replies = ReplySerializer(many=True, read_only=True) class Meta: model = Comment fields = "__all__" class ImageSerializer(serializers.ModelSerializer): class Meta: model = Images fields = ('image',) class PostSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True, read_only=True) author = UserSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True) class Meta: model = Post fields = "__all__" views.py class PostsViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer urls.py router = DefaultRouter() router.register('posts', PostsViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So I created superuser and added some posts and images via admin panel. And after all that, I'm getting the following: @baseUrl = http://localhost:8000/ GET {{baseUrl}}/posts/ Content-Type: application/json HTTP/1.1 … -
During testing, Manager isn't available
I've swapped the User model with my own custom User model. It uses the standard UserManager. I also have a CustomUserChangeForm which is used in my UserAdmin. I've set AUTH_USER_MODEL = "accounts.User" in settings. This all works fine when using the site/admin site normally through the browser. Tests on my views that use the custom User model also work fine. Only when I try to run a test directly on the CustomUserChangeForm I get the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'. What's going wrong here? The test: from .forms import CustomUserChangeForm from .models import User def test_admin_user_change_form(self): self.register_user() self.register_user("email2@site.com", "username2") user = User.objects.get(username="username") # Test valid change form = CustomUserChangeForm({ "username": "username3", "email": "email3@site.com" }, user) self.assertTrue(form.is_valid()) # Test case insensitive username change form = CustomUserChangeForm({ "username": "Username2" }, user) self.assertFalse(form.is_valid()) # Test case insensitive email change form = CustomUserChangeForm({ "email": "Email2@site.com" }, user) self.assertFalse(form.is_valid()) The form: class CustomUserChangeForm(UserChangeForm): def clean_username(self): username = self.cleaned_data.get("username") if username and self._meta.model.objects.exclude(id=self.instance.id).filter(username__iexact=username).exists(): self._update_errors(ValidationError({ "username": self.instance.unique_error_message(self._meta.model, ["username"]) })) else: return username def clean_email(self): return self.cleaned_data.get("email").lower() The answers at this question and this question do not seem to apply/work. -
Django migration from 3.1 to 3.2 error while copying models instances
I'm trying to upgrade Django from 3.1 to 3.2, and one of the error that I encountered was endpoints that I have that duplicate resources and their related models. In this example: @action( detail=True, methods=['POST'], name='Duplicate one resource', url_name='duplicate', url_path='duplicate', ) @transaction.atomic def duplicate(self, request, pk=None): foo = self.get_object() # gets foo foo_bars = foo.foo_bars.all() # gets a queryset of FooBar new_name = self.append_copy_suffix(foo.name) new_foo = foo.copy_instance(name=new_name) # code below print(foo, new_foo) FooBar.objects.bulk_create( [FooBar(foo=new_foo, bar=foo_bar.bar, stuff=foo_bar.stuff) for foo_bar in foo_bars] ) return Response(self.get_serializer(new_foo).data, status=status.HTTP_201_CREATED) def copy_instance(self, **kwargs): """ Method to copy a model instance More info here: https://docs.djangoproject.com/en/3.1/topics/db/queries/#copying-model-instances :param kwargs: additional parameters to update :return: the duplicated resource """ new_resource = self new_resource.pk = None for k, v in kwargs.items(): setattr(new_resource, k, v) new_resource._state.adding = True new_resource.save() return new_resource This works pretty well in Django 3.1, but in Django 3.2, the related resources are not created for some reason. Things that I noticed in debug and printing the values: When I print the foo and new_foo, they are the same one (new_foo). foo_bars is empty. Maybe because the foo and new_foo are the same one before the bulk_create and the foo_bars is just a queryset that was yet to be … -
ModuleNotFoundError: No module named 'django_invoice'
I get this error every time I try to do migrations or even run my py manage.py runserver. I installed the 'django_invoice' module, inserted it in INSTALLED_APP but still I get the same error over and over again. I installed the requested module hoping that the problem would be fixed but unfortunately it wasn't. -
Can I define an Alias to a foreign field in Django?
I'm looking to define an alias to a foreign key related set so that it can then be used in a generic filtering function. To explain with a little more detail here is a simplified example of my use case demonstrating what I'm trying to achieve: models.py from django.db import models class Family(models.Model): family_name = models.CharField(max_length=100) pets: models.Manager['Pet'] = ... members: models.Manager['Person'] = ... def __str__(self): return f'{self.id} - {self.family_name}' class Pet(models.Model): class PetType(models.TextChoices): CAT = 'cat' DOG = 'dog' LIZARD = 'lizard' name = models.CharField(max_length=100) type = models.CharField(max_length=100, choices=PetType) family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='pets') def __str__(self): return f'{self.id} - {self.name} {self.family.family_name} [{self.type}]' class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='members') @property def pets(self) -> models.Manager[Pet]: return self.family.pets def __str__(self): return f'{self.id} - {self.name} {self.family.family_name}' If I have a Person entity, I can use it's pets property to get the pets from the family, what I'm looking for is a way to add an alias/annotation/whatever to a queryset of Person so that I can define: def has_a_cat(query_set): return query_set.filter(pets__type='cat') and then be able to use that for both Family and Person query sets. I know I can filter a Person queryset by the pet type … -
Django-filter with django-table
I've been stuck on this problem for a couple of weeks and can't seem to resolve it through self research. Scenario for testing: I have a 4 learners who are registered against different groups. Using tables2 I've created class GroupListView(SingleTableView), selecting the group takes me to class GroupDetailView(SingleTableView, FilterView). This should show a qs of LearnerInstances associated with that learner. However, when applying the f.qs to the learner queryset it shows all 4 learners on the detail page. views.py class GroupDetailView(SingleTableView, FilterView): table_class = LearnerGroupTable model = LearnerInstance template_name = "learner/group_detail.html" filterset_class = LearnerAimFilter # get all learners within the selected group def get_queryset(self): qs = super().get_queryset() qs = qs.filter( learner__group__slug=self.kwargs["slug"], ) return qs # a queryset of learners within the group from model learnerinstance def get_context_data(self, **kwargs): context = super(GroupDetailView, self).get_context_data(**kwargs) learners = self.get_queryset() context["learners_qs"] = learners f = LearnerAimFilter(self.request.GET, queryset=learners) learners = f.qs context["filter"] = f context["table"] = LearnerGroupTable(learners) context["learners"] = learners context["group"] = Group.objects.filter(slug=self.kwargs["slug"]).values() context["group_name"] = Group.objects.filter(slug=self.kwargs["slug"]).values( "short_name" ) return context If I # out the learners = f.qs the detail view shows the correct learner instances but does not filter. As soon as I undo the # it then shows all four learners but the filter … -
How to display users who are only included in the Group in django admin panel
I have an Author simple models in my Django project as below: class Author(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, default=None) def __str__(self): return self.user.username note: CustomUser is django's default User model which I added with a phone number In the Group models (in Django admin panel), I have created 'Author' group, to separate or differentiate ordinary users or authors. I want when I enter a new author name in the Author model, the only names that appear are those that belong to the 'Author' group.