Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can I run django Manage.py using Python3 manage.py run server
I tried running Python3 manage.py run server to run my django application but couldn't due to error. Error:Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. Note:python is running my pc and I have environment variable set too -
Django form submission Redirecting to wrong url
I am trying to take help from this tutorial and my own thing. It's supposed to be a marketplace. I have an app called Creator (vendors) I am trying to let the users add new products by themselves using views.add_product, add_product.html, and forms.py when I try to submit the add_product form, it gives this error Error Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/creator/ (I am not trying to redirect it to this page but rather 'url 'creator_overview'' Project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('creator/', include('creator.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) creator/urls.py urlpatterns = [ path('sell_on_cosloo', sell_great_things, name='creator_signup'), path('creator_overview',creator_overview , name='creator_overview'), path('add_product',add_product , name='add_product'), ... ] creator/views.py @login_required def add_product(request): if request.method == 'GET': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.vendor = request.user.vendor product.slug = slugify(product.title) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request, 'creator/add_product.html', {'form': form}) creator/forms.py <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-dark is-uppercase">Submit</button> </div> </div> </form> add_product.html {% extends 'core/base.html' %} {% block title %}Add product | {% endblock %} {% block content %} <h1 class="title">Add product</h1> <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div … -
Factory_boy not creating RelatedFactory in Trait
I've got a Purchase model and a PurchaseInfo model. PurchaseInfo has a foreign key to Purchase. I'm trying to modify an existing Factory for Purchase that will create PurchaseInfo at the same time using RelatedFactory since it's a reverse foreign key relationship. The only thing is that I wanted to use a Taint so that I could control the value of fields within PurchaseInfo. Normally when I create a Purchase like p = PurchaseFactory() the PurchaseInfo is created with null fields inside of it. If I create a Purchase like p = PurchaseFactory(info=True), so I can get the field modifications via the Taint, the PurchaseInfo is not created at all. I have a feeling that putting the RelatedFactory in a Taint is not the way to go. What is the correct way to do this? Models: class Purchase(Model): ... class PurchaseInfo(Model): purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE, unique=True, db_index=True) lock = DateTimeField(null=True) lock_by = ForeignKey(... class PurchaseInfoFactory(DjangoModelFactory): class Meta: model = PurchaseOrderInternalField lock = None lock_by = None class PurchaseFactory(DjangoModelFactory): class Meta: model = Purchase info = RelatedFactory(PurchaseInfoFactory, factory_related_name='purchase') class Params: info = Trait(internalfield=RelatedFactory(PurchaseInfoFactory, factory_related_name='purchase', lock=timezone.now() - relativedelta(months=1), lock_by=SubFactory(UserFactory, user_id=1))) -
How can I get information about the logged-in user in a Django application?
How can I get information about the logged-in user in a Django application? What I want to do is get the user information from Logged-in user and put additional information and store in a database(models.py). -
docker compose failing on gitlab-ci build stage
I am trying to build gitlab-ci but one of the stages is failing the build. I get stuck on build stage. it does not recognise python and i am trying to install it so i can build the image and get it tested with robot framework gitlab-ci.yaml image: python:latest services: - name: docker:dind entrypoint: ["env", "-u", "DOCKER_HOST"] command: ["dockerd-entrypoint.sh"] stages: - compile - build - test - deploy variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 DOCKER_TLS_CERTDIR: "" MOUNT_POINT: /builds/$CI_PROJECT_PATH/mnt REPOSITORY_URL: $AWS_ACCOUNT_ID.dkr.ecr.eu-west-2.amazonaws.com/apps_web TASK_DEFINITION_NAME: apps_8000 CLUSTER_NAME: QA-2 SERVICE_NAME: apps_demo ARTIFACT_REPORT_PATH: "app/reports/" before_script: - docker info - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE:web - apk add --no-cache openssh-client bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY unittests: stage: test before_script: - python -m venv env - source env/bin/activate - python -m pip install --upgrade pip - pip install -r app/app-requirements.txt variables: DOCKER_IMAGE_TAG: ${CI_REGISTRY_IMAGE}:${CI_COMMIT_TAG} image: ${DOCKER_IMAGE_TAG} script: - source env/bin/activate - python app/manage.py jenkins --enable-coverage artifacts: reports: junit: app/reports/junit.xml paths: - $ARTIFACT_REPORT_PATH expire_in: 30 days when: on_success only: refs: - merge_requests variables: - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "qa" migrations: stage: compile before_script: - python -m venv env - source env/bin/activate - pip install -r app/app-requirements.txt script: - python app/manage.py makemigrations artifacts: … -
how to know which url is hit in django graphql?
I am working on a django project, where graphql is used, I am not able to trace which function hit and from where error is coming, Please help -
Django rest: accessing all related objects using ForeignKey
I'm stuck and I don't know what's wrong... to me it's identical to the "Nested relationships" example in the DRF API guide but something is not right... MODEL class PlayerSquadra(models.Model): player = models.ForeignKey( 'app_player.Player', on_delete=models.CASCADE, verbose_name=_('giocatore'), related_name='player_squadraplayer', ) squadra = models.ForeignKey( 'app_stagione.Squadra', on_delete=models.CASCADE, verbose_name=_('squadra'), related_name='squadra_squadraplayer' ) def __str__(self): return '%s' % (self.player) URL router.register(r'squadraJSON/(?P<squadra>.*)', views.SquadraViewSet) VIEW class SquadraViewSet(viewsets.ReadOnlyModelViewSet): queryset = Squadra.objects.all() serializer_class = SquadraSerializer def get_queryset(self): laSquadra = self.kwargs['squadra'] queryset = Squadra.objects.filter(id=int(laSquadra)) return queryset SERIALIZER class PlayerSquadraSerializer(serializers.ModelSerializer): class Meta: model = PlayerSquadra fields = '__all__' class SquadraSerializer(serializers.ModelSerializer): playersquadra = PlayerSquadraSerializer(many=True, read_only=True) class Meta: model = Squadra fields = ['nomeSquadra','id','playersquadra'] What I get when I call http://192.168.0.102:8000/squadraJSON/26/ is: GET /squadraJSON/26/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "nomeSquadra": "prova2", "id": 26 } ] And no errors... While I expect something like this: GET /squadraJSON/26/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "nomeSquadra": "prova2", "id": 26 "playersquadra": [ {'id': 1, 'firstName': 'Michael', 'lastName': 'Jordan',...}, {'id': 2, 'firstName': 'Larry', 'lastName': 'Bird',...}, ... ], } ] Could you give me some hint why I'm not getting all the players belonging to Squadra with id=26? Thanks for helping -
Page not found (404) like button
from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default='awesome') author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) -
Django tests pass individually but fail when running together
I have a number of tests that all pass if I just run the file individually in Pycharm. But if run them as using the DiscoverRunner some of them fail. I know it must have something to do with the tests setup, so I am looking for input on how to debug this. Things I already tried based on other stackoverflow answers: Make sure all the testscases are django.test.TestCase. Most test load data from fixtures in the class definition. Make sure to call the super method where I define the tearDown method. I had two tests files that used mail.outbox when run together. But if I put them together in a package inside the test folder they suddenly passed. Any idea what could be causing this? Any tips on how to debug this? -
Uncaught ReferenceError jquery and Django (model.Form)
I am having an Exception thrown after calling a jquery function inside the Widgets area of the forms as below : class TipsterEmployeeAdminForm(forms.ModelForm): class Media: js = ('admin/js/tipster-employee.js',) class Meta: model = TipsterEmployee fields = ( 'first_name', 'last_name', 'slug', 'email', 'international_prefix', 'phone_number', 'tipster_partner', ) widgets = { 'tipster_partner': SelectExtra( attrs={'onchange': 'updateEmployeeUrl("{base_url}")'.format( base_url=get_base_url())}), } The exception thrown is : Uncaught ReferenceError: updateEmployeeUrl is not defined This happens around here : widgets = { 'tipster_partner': SelectExtra( attrs={'onchange': 'updateEmployeeUrl("{base_url}")'.format( base_url=get_base_url())}), } Also in the base.html template , the jquery link is there : -
I can't filter fields in model (Django)
I have models (removed all unnecessary): class Contract(models.Model): contract_number = models.IntegerField(primary_key=True) student = models.ForeignKey('Student', on_delete=models.CASCADE) lessons = models.ManyToManyField('Lesson') class Student(models.Model): name = models.CharField(max_length=150) age = models.IntegerField() class Lesson(models.Model): lesson_time = models.TimeField(verbose_name='Время урока') lesson_date = models.DateField(verbose_name="Дата урока") is_done = models.BooleanField(verbose_name="Проведен") In my html I use special link: <a href="{%url 'stud_detail' id=student.id%}"> which leads to url in urls.py: path('student/<int:id>', views.one_student, name='stud_detail') And there is my view (again removed all other models): def one_student(request, id): student = Student.objects.get(id=id) contracts = Contract.objects.filter(student=id) lessons = Lesson.objects.filter(id__in=contract) print(lessons) content = dict(student=student, contracts=contracts, lessons=lessons) return render(request, 'studbase/student_detail.html', content) Now I have 10 lessons in the contract, but based on filtration results I have only one. print(lessons) returns only 1 lesson instead of 10 lessons. What did I do wrong? -
Doesn`t work method create for serializers.ModelSerializer
I study Django Rest Framework. First I created CustomUser Model based on AbstractUser. After I created serializer RegistrationSerializer based on ModelSerializer. In RegistrationSerializer I wrote my own create() for password2 validation using official specification. Extra field for password2 works well. But my RegistrationSerializer "doesn't use" my create(). Looks like it doesnt know about method and I cant understand why. On my POST request without password2 I recieve password2 is required. On my POST request with password2 I recieve CustomUser() got an unexpected keyword argument 'password2'. accounts/models.py class CustomUser(AbstractUser): image = models.ImageField(verbose_name="Аватар", upload_to="covers/", null=True) And accounts / api / serialers.py from rest_framework import serializers from accounts.models import CustomUser class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = CustomUser fields = ['email', 'username', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def create(self): account = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account -
Django, importing models class into new file. Import error attempted relative import with no known parent
I am working on learning Django by making a simple analysis dashboard. I did the startproject command and the startapp command like the tutorial ran through. I added a new file called connectionOracle.py in the app folder. My folder structure is (top folder is was created via venv) AnalysisSite |AnalysisSite |coreAnalysis ||models.py ||connectionOracle.py I have a class called WorkOrder in the models.py file. I am trying to import it into the connectionOracle.py file by doing the following from .models import WorkOrder I then go to the Command Line (on windows) and navigate tot he coreAnalysis folder and run the following python connectionOracle.py I get an error that says. ImportError: attempted relative import with no known parent package I did some reading online, and I tried doing an absolute path with AnalysisSite.AnalysisSite.coreAnalysis.models that didnt work. I also tried moving the connection file to different directories and that didnt work either. I also tried going into the command line and typing set DJANGO_SETTINGS_MODULE = AnalysisSite.settings I also put a _init_.py in each folder. (Django automatically put it into the project directory and app directory). I am not sure what I am doing wrong -
Find the shortest path in a web application
I want to create a web application. I want to create a site that can recommend tourist places to tourists. I would like to recommend the shortest route between several tourist places to the tourist. I use Python, Django and OSM. please guide me. -
How to Reset a Password through mobile number in Django?? Please suggest some tips
This is my models.py. I want to reset the password of the user by mobile number. Can't find answer yet. Can someone help to suggest any methods? Thanks in advance. from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User,null=True, on_delete=models.CASCADE) mobile = models.CharField(max_length=15, blank=True, null=True) def __str__(self): return self.user.username -
Django forms gives 'str' object has no attribute '_meta'
I am making a custom User model that looks like this accounts/models.py class MyUser(AbstractUser): role_tuple = ( ('admin', 'admin'), ('user', 'user'), ('activist', 'activist'), ) role = models.CharField(null = True, default='user', max_length = 200, choices = role_tuple) user_proof_image = models.ImageField(null=True, upload_to='user_proof_images') Added it to settings.py AUTH_USER_MODEL = 'accounts.MyUser' I now want to create a form using the custom user model so I used from django.contrib.auth.forms import UserCreationForm from CPW.settings import AUTH_USER_MODEL class CreateUserForm(UserCreationForm): class Meta: model = AUTH_USER_MODEL fields = ['username', 'email', 'password1', 'password2', 'role'] But it tells me from .forms import CreateUserForm File "C:\Users\xyz\OneDrive\Desktop\Django\CPW\user_auth\forms.py", line 4, in <module> class CreateUserForm(UserCreationForm): File "C:\Users\xyz\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 258, in __new__ apply_limit_choices_to=False, File "C:\Users\xyz\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 142, in fields_for_model opts = model._meta AttributeError: 'str' object has no attribute '_meta' I have never tried forms of custom users. Help? -
pass django template file content to javascript
I want to pass a template file content to my javascript file for later use to create DOM elements there. What I have tried is to pass it to js as a variable with an include tag like this: <script>const list_item = {% include 'myapp/list_item.html' %}</script> But this end up getting: Uncaught SyntaxError: Unexpected token '<' Is there a way I can pass template file content to js file? Thanks in advance -
Django-How to update or edit formset factory form in my invoice
I am working in Django having invoice form saved successfully but can't update the invoice form. I have a main invoice form and another LineItemSet formset form with calculation. I tried to edit it but the formset form cannot update the existing one and saved it as a new entry. Here is my model form: class Customer(models.Model): name = models.CharField(max_length=100) GST_no = models.CharField(max_length=50, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) customer_email = models.EmailField(null=True, blank=False) billing_address = models.TextField(null=True, blank=False) date_created = models.DateField(auto_now_add=True, auto_now=False, blank=True, null=True) def __str__(self): return self.name class Supplier(models.Model): name = models.CharField(max_length=100) GST_no = models.CharField(max_length=50, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) supplier_email = models.EmailField(null=True, blank=False) bill_address = models.TextField(null=True, blank=False) date_created = models.DateField(auto_now_add=True, auto_now=False, blank=True, null=True) def __str__(self): return self.name class PriceTag(models.Model): name = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.name) class Products(models.Model): item = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=100, blank=True, null=True) pricetag = models.ManyToManyField(PriceTag) quantity = models.IntegerField() price = models.IntegerField(default='0') reorder_level = models.IntegerField(default='0', blank=True, null=True) last_updated = models.DateField(auto_now_add=False, auto_now=True) date = models.DateField(auto_now_add=False, auto_now=False, null=True, blank=True) comment = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.item) class Invoice(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) invoice_no = models.IntegerField(blank=False, null=True) due_date = models.DateField(auto_now_add=False, auto_now=False, null=True, blank=True) last_updated = models.DateField(auto_now_add=False, auto_now=True) status = models.BooleanField(default=False) total_amount = models.DecimalField(decimal_places=2, … -
Django sessionid not created for Locust client
I'm running Django 2.2.24 and Locust 2.1.0 for load testing. When I run some Locust test logging in as a the Django admin user, there are no issues - all my GETs work as expected. Now I am actually logging in as a specific user. From a web interface, Django passes a CSRFtoken and a sessionid token with no problem. From the Locust client however, the sessionid does not show up at all. Not only that, but when I look in the django_session table (where the web tokens do exist), there are no tokens for the Locust client. I think this is more related to Django session management than to locust - hence the post in this forum. My locust file looks like this: def on_start(self): ''' The start script for each user - this order is important ''' # Below 3 lines work fine - we get the csrftoken and put it in the header successfully response = self.client.get("/accounts/login") self.csrftoken = response.cookies['csrftoken'] self.headers = {'X-CSRFToken': self.csrftoken} # Now login with username and password as POST r1 = self.login() return r1 def login(self): # admin login and retrieving it's access token udata = {'username': self.username, 'password': self.password} cookies=self.client.cookies.get_dict()) #csrftoken cookie … -
How to show the information in the same page where I am submitting form in django
I am trying to submit a form and get the result in the same page where I have created the form . But , can't get the values in the same page . But , whenever I am trying to take the value in a different page it's working. My views.py file : def home(request): words = request.GET['text'] count = len(words.split()) context = {'count':count} return render(request,'index.html',context) My index.html file: <div class="container"> <h3 style="display:inline-block; text-transform: capitalize; padding-top: 10px; border-bottom: 2px solid #e5e5e5;">Word counting app</h3> <h5 style="padding-top: 40px;text-transform: capitalize;">enter your word below to count</h5> <div class="row"> <div class="col-lg-6"> <form method="" action=""> <textarea name="text" cols="30" rows="7"></textarea> <button type="submit" style="padding: 6px 28px; border: none; background:orange; margin-top: 10px;">Submit</button> </form> <p>{{count}</p> </div> </div> </div> -
Exception thread in Accessing sqlite3 in django
I am playing in Django, in views - print('datatable', Datatable.objects.all()) - shows this error/exception Exception in thread Thread-5: Traceback (most recent call last): File "C:\Users\Karthiyayini Dhillip\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Karthiyayini Dhillip\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Karthiyayini Dhillip\Documents\dj\project1\cv\views.py", line 87, in update print('datatable', Datatable.objects.all()) File "C:\Users\Karthiyayini Dhillip\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 255, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) models.py from django.db import models # Create your models here. class Users(models.Model): email = models.EmailField(max_length = 254) password = models.CharField(max_length=100) def __str__(self): return(self.email) class Datatable(models.Model): classes = models.CharField(max_length = 254) date_d = models.DateField() def __str__(self): return(self.date_d, self.classes) How to solve this, thanks -
Django - Query for posts along with it's number of replies?
So I'm trying to populate a news feed with posts of a certain category. Then I want to be able to display the number of replies on the post. The reason I'm confused on how to do this, is because I filtered through goals by category then I filtered all the posts associated with all those goals and now I have a list of a dictionary containing the post body and goal description and create date, but I'd like to also add in the number of replies and I'm not sure how to do this in an efficient way. Also I realize my way of doing things in the view.py is less than ideal so any suggestions would be great! Model.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) class ReplyPost(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="reply") post_id = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.CharField(max_length=250) View.py @api_view(['GET']) def get_most_recent_posts_by_category(request, category, count): goals_list = list(Goal.objects.filter(category = category).values_list('uuid', flat=True)) data = list(Post.objects.filter(goal_id__in=goals_list).order_by('created').values('body', 'goal_id__description', 'created')) data['goal_description'] = data['goal_id__description'] data['post_body'] = data['body'] del data['goal_description'] del data['body'] return JsonResponse(data, status=status.HTTP_200_OK) -
Access to Django admin site deployed on non-root URL with mod_wsgi
I have a DRF 3.12.4 (with Django 3.2.3) app deployed on apache httpd 2.2.15 with mod_wsgi 4.6.5 running on Python 3.7. I want my app to be served on non-root URL, e.g. prefixed by /alert. With the following settings in wsgi.conf: ... Alias /alert/static/ /var/www/djangoapps/achtung_alert/static/ WSGIDaemonProcess achtung_alert user=infa group=infa threads=25 display-name=%{GROUP} home=/var/www/djangoapps/achtung_alert python-home=/var/www/djangoapps/achtung_alert/venv python-path=/var/www/djangoapps/achtung_alert:/var/www/achtung_alert WSGIScriptAlias /alert /var/www/achtung_alert/wsgi.py process-group=achtung_alert application-group=%{GLOBAL} WSGIProcessGroup achtung_alert <Location /alert > WSGIProcessGroup achtung_alert WSGIPassAuthorization On </Location> ... and project's urls.py: from django.contrib import admin from django.urls import path, include from rest_framework.authtoken import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('achtung_alert.urls')), path('api-auth/', include('rest_framework.urls')), path('api-token-auth/', views.obtain_auth_token), ] and no FORCE_SCRIPT_NAME in settings.py I am able to access all endpoints in my achtung_alert app, api-auth/, api-token-auth/ - all prefixed by /alert. But if I try to access /alert/admin/ I'm getting the following error from Django's debug page: Page not found (404) Request Method: GET Request URL: https://mysite/alert/admin/ Using the URLconf defined in achtung_alert_project.urls, Django tried these URL patterns, in this order: admin/ openapi [name='openapi-schema'] swagger-ui/ [name='swagger-ui'] ^events/$ [name='event-list'] ... The current path, alert/admin/, didn’t match any of these. If I make a typo in URL, then "/alert" prefix will be removed from the current path as expected: Page not found … -
Raise 404 instead of 500 when using an invalid uuid
I have a uuid field in my Document model If I get() my model with a bad uuid, I got a error 500. This line throw an error: x = Document.objects.get(uuid=object_uuid) Instead of a 500 I want a 404 error I wrote this, but I don't want to put my function everywhere it's so redundant (I'm lazy) def is_valid_uuid_or_404(object_uuid): try: return uuid.UUID(object_uuid) except ValueError: raise Http404("Invalid uuid") x = Document.objects.get(uuid=is_valid_uuid_or_404(object_uuid)) #Boring Someone has a good idea to make it better ? -
Django Filter BooleanFilter with 3 options - True, False and Both
I am trying to create a filter for where an attribute is null with Django-Filter for an Appointment model. The relevant docs are: https://django-filter.readthedocs.io/en/stable/guide/tips.html?highlight=isnull#solution-1-using-a-booleanfilter-with-isnull class Appointment(models.Model): ... professional = models.ForeignKey(telemed_models.HealthcareProfessionalProfile, null=True, blank=True, on_delete=models.SET_NULL, related_name='appointments', verbose_name=_('professional')) ... The filter I need is called 'Unassigned' which will filter for those appointments where no professional is set. I am using a checkbox for this: class AppointmentListFilter(django_filters.FilterSet): ... unassigned = django_filters.BooleanFilter(field_name='professional', lookup_expr='isnull', label=_("Unassigned"), widget=forms.widgets.CheckboxInput()) ... On page load (i.e. before clicking 'filter items') all items are shown (obviously) and the checkbox is unchecked. The weird behaviour is as a result of the following: After clicking 'filter items' the checkbox is technically 'working' when it is used - i.e. unchecked is showing appointments where professional is not null. Checked is showing appointments where professional is null. So, there's a clash with the fresh/page load state. Basically that on pageload unchecked means "all items", but after filtering, unchecked means "only those with a value". While the filter is technically doing what it is supposed to do, this is bad UX because it's quite confusing for the user. Does anybody know a good way of handling this? I mean, a boolean feels like the right way to …