Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show two tables inline in django admin?
I have created two models in models.py, Product and ProductImage. Product is needed to show a certain product. ProductImage is needed to show multiple images of one Product. Here is the code in models.py : class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) def __str__(self): return self.product.name @property def imageURL(self): try: url = self.image.url except: url = '' return url And here is the code in admin.py : from django.contrib import admin from .models import * # Register your models here. class ProductImageAdmin(admin.TabularInline): model = ProductImage extra = 2 # how many rows to show class ProductAdmin(admin.ModelAdmin): inlines = (ProductImageAdmin,) admin.site.register(ProductAdmin, ProductImageAdmin) I keep getting this error: TypeError: 'MediaDefiningClass' object is not iterable I searched this error but I still did not manage to fix this. I also looked in the documentation (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models) What is the cause of this error? Thank you! -
JWT Logout "detail": "Authentication credentials were not provided."
I am trying to create a Logout endpoint for a jwt token in djangorestframework. When I access this endpoint via postman, I get "detail": "Authentication credentials were not provided." What am I missing here? Am I supposed to create a serializer that has a field for the refresh token and add it to the view? Am I parsing the data corretly in postman? views.py from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.tokens import RefreshToken class LogoutView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: refresh_token = request.data["refresh_token"] token = RefreshToken(refresh_token) token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) urls.py from accounts.views.user_api_views import ( LogoutView, LogoutAllView, ) urlpatterns = [ path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.jwt")), path("auth/token/", ObtainCustomizedTokenView.as_view(), name="token_obtain_pair"), path( "auth/token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh", ), path("logout/", LogoutView.as_view(), name="logout"), path("logout_all/", LogoutAllView.as_view(), name="logout_all"), ] settings.py INSTALLED_APPS = [ ... # local apps # 3rd party "storages", "rest_framework", "rest_framework_gis", "rest_framework.authtoken", "djoser", "django_celery_beat", "raven.contrib.django.raven_compat", "rest_framework_simplejwt.token_blacklist", ] ...... SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(weeks=521), # 10 years "REFRESH_TOKEN_LIFETIME": timedelta(weeks=521), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": None, "AUTH_HEADER_TYPES": ("JWT",), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", } ...... REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", ], "DEFAULT_PERMISSIONS_CLASSES": ("rest_framework.permissions.IsAuthenticated"), } Image from Postman -
Django python variable not printing in html
this is my code in my views.py: import requests import os import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=4&interval=daily', ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() btcprices = [] btcprices.append(int(json_data5['prices'][0][1])) print(btcprices) context = { "btcprices": btcprices, } return render(request, "index.html", context) when i do {{ btcprices }} in my html file nothing apperas on the web page when i "python manage.py runserver" it works with other variables that i removed from the code but i'm struggling with this one. Any idea why ? by the way the print(btcprices) gives me : [59014, 57922, 58243, 58376] it's type is a list of integers -
How to find dictionary by date in dictionary of dictionaries
I have a dictionary of dictionaries, each is a boxscore of a game in a season. If I wanted to pull one specific game by date, how would I pull that one dictionary out? Something like... for game in schedule: boxscore = game.boxscore if date = '2021-03-21' Thanks! def management(request): """ View to return site management page """ schedule = Schedule('CHI') for game in schedule: boxscore = game.boxscore date = game.date date_time_date = datetime.datetime.strptime(date, '%a, %b %d, %Y') game_date = date_time_date.strftime('%Y-%m-%d') context = { 'game_date': game_date, 'boxscore': boxscore, } return render(request, 'management/management.html', context) -
Unable to get logged in username in django
I am trying to get User as foreignkey in a model but getting error. When I try: qr.claimed = True user = get_object_or_404(User,id=request.user.id) qr.branch = user qr.save(); OUTPUT: AttributeError: 'str' object has no attribute 'user' When I try to POST: qr.claimed = True get_user = request.POST.get('branch') user = User.objects.get(id=get_user) qr.branch = user qr.save(); OUTPUT: AttributeError: 'str' object has no attribute 'POST' When I define user in another python file and try to fetch from there: qr.claimed = True get_user = pythonfile.user user = User.objects.get(id=get_user) qr.branch = user qr.save(); OUTPUT: TypeError: Field 'id' expected a number but got <function user at 0x0E777E38>. request.user -> AttributeError: 'str' object has no attribute 'user' request.POST -> AttributeError: 'str' object has no attribute 'POST' Any error with request or missing any package to install/import? -
Celery task with Scikit-Learn doesn't use more than a single core
I am trying to create a an API endpoint that will start a classification task asynchronously in a Django backend and I want to be able to retrieve the result later on. This is what I have done so far: celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") app = Celery("backend") app.config_from_object("django.conf:settings", namespace = "CELERY") app.autodiscover_tasks() tasks.py from celery import shared_task @shared_task def Pipeline(taskId): # ...read file, preprocess, train_test_split clf = GridSearchCV( SVC(), paramGrid, cv=5, n_jobs = -1 ) clf.fit(XTrain, yTrain) # ...compute the metrics Django view for executing the task: views.py class TaskExecuteView(APIView): def get(self, request, taskId, *args, **kwargs): try: task = TaskModel.objects.get(taskId = taskId) except TaskModel.DoesNotExist: raise Http404 else: Pipeline.delay(taskId) # ... Database updates The problem is the started task only uses one core of the CPU, hence taking a very long time to complete. I also see this error: Warning: Loky-backed parallel loops cannot be called in a multiprocessing, setting n_jobs=1. Is there a way to solve this? I am aware of a similar question on SO made in 2018 that is kind of similar to this, but that post has no definite answer, so I am looking for a solution with no luck so far. … -
Cannot understand error when url is changed in django. It throws '404'
When I first created the urls with 'pk' they worked fine. But when I use 'slug' for lookup, when I change the url it throws 404. url patterns that work Now when I change the 'product-detail' url, the feature url throws error which is irrelevant. And it says that this particular view is causing it. But the view has no relation with 'featured-product-list' url. url pattern that cause error enter image description here On diagnosing it I find that it is trying to pass 'featured' as a slug, which is out of my logic. Please help me to find what is causing this issue. here is the detailed error here is the view -
add tomporary user using forms for appointement application with django
I'm stuck in the attempt to create an appointment application with Django to register (as a patient) and non registered user (doctor makes appointment for non register patient) for the 2ns case (for the non register user) my idea is to create a new user with a type = temporary, but I could not figure out how to add him and specify his type as a temporary using a user form and a profile form to add some information and the appointment form this is my models.py class TypeOfUser(models.TextChoices): PATIENT = 'patient', 'Patient' DOCTOR = 'doctor', 'Doctor' RECEPTION = 'reception', 'Reception' TEMPORARY = 'temporary', 'Temporary' class User(AbstractUser): type_of_user = models.CharField(max_length=200, choices=TypeOfUser.choices, default=TypeOfUser.PATIENT) allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement.choices, default=AllowdToTakeAppointement.YES) def is_doctor(self): return self.type_of_user == TypeOfUser.DOCTOR def is_temporary(self): return self.type_of_user == TypeOfUser.TEMPORARY and this is the forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'})) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class ProfileUpdateForm(forms.ModelForm): gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False, widget=forms.RadioSelect) class Meta: model = Profile fields = ('date_of_birth', 'gender', 'phone_number', 'blood_group', 'address', 'photo') and this is the fucntion for register … -
Type Error /login authenticate() takes from 0 to 1 positional arguments but 2 were given
def loginUser(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('pass1') user = authenticate(username, password) if user is not None: login(request, user) return redirect( '/') else: messages.error(request, "Either your email or password is wrong!") return render(request, 'loginpage.html') return render(request, 'loginpage.html') Whenever I enter the credentials on the login page this error appears, my login function is also named loginUser yet -
how to provide foreign key value input through <input> html django , ValueError?
please this is an urgent task i very appreciate to your recommenditions i'm trying to make an online order system , someone can order several items at the same time , for that reason i have used inlineformset and sometimes using {{form.field_name}} prevent some styles and js events , for that purpose i decided to use input fields manually <input> tags , i didnt faced such challenges in my previous projects , now im confused how to achieve it !? this is my models.py class Item(models.Model): items = models.CharField(max_length=50) #others def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice= models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() i used function based view in view and this is my views.py @login_required def createClientInoiveView(request): item_names = Item.objects.all() if request.method == 'POST': customer = request.POST['customer'] seller = request.user obj = CustomerInvoice.objects.create(seller=seller,customer=customer) # inlineformset fields item = request.POST['items'] quantity = request.POST['quantity'] price = request.POST['price'] cash = request.POST['cash'] discount = request.POST['discount'] items = InvoiceItem.objects.create(item=item,quantity=quantity,price=price,cash=cash,discount=discount) with transaction.atomic(): obj = obj.save(commit=False) if obj.is_valid and item.is_valid(): item.invoice = obj obj.save() item.save() return redirect(reverse_lazy('invoiceapp:detail-invoice',kwargs={'pk':obj.pk})) return render(request,'invoiceapp/create_invoice.html',{'item_names':item_names}) and this is my html form <form method="POST">{% csrf_token %} {{items.management_form}} <div … -
Using JWT authentication with Django/DRF and Storing JWTs in HttpOnly Cookies
I am trying to build a web app using Django and DRF at the back-end and ReactJs at the front end and I want to keep them separate (i.e. avoid Server Side Rendering).For authentication purposes, I want to employ JWT and I am using djangorestframework-jwt for that. I have read it at several places that it is not secure to store JWTs in the local storage so I am trying to use HttpOnly cookies for that. One can achieve that by configuring the django server to send HttpOnly by overriding the following default settings of the drf-jwt package in the settings.py file of your project JWT_AUTH = { 'JWT_AUTH_COOKIE': '<cookie name>', } which is set to none by default. The server sends the httpOnly cookie as anticipated but there are a few issues I am facing: 1.Same Domain Restraint I am aware that httpOnly cookies wont be attached to the request headers unless the request is being made to the server which is hosted on the some domain. In my case I am using localhost:8000 for django and localhost:3000 for my react project so the browser doesnt attach the cookie as the request is made to a different port. I … -
CHARTJS baar chart not showing
i have this js code for a bar chart and i use python data for the yaxis this is my js code : <div class="btcprices-chart"> <canvas id="myChart3"></canvas> <script> var ctx = document.getElementById('myChart3').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'bar', // The data for our dataset data: { labels: ["day1", "day2", "day3", "day4"], datasets: [{ label: 'bitcoin brices per day', backgroundColor: 'rgb(66, 103, 178, 0.6)', borderColor: 'rgb(75, 79, 220))', borderWidth: 2, data: {{ btcprices|safe }} }] }, // Configuration options go here options: { title: { display: true, text: 'bitcoin brices per day' } } }); </script> </div> i have another chart but with nother data values : data=[626830186, 1055315163, 64138356, 314568549] and for this chart btcprices=[59014, 57922, 58243, 58376] in data : {{ btcprices|safe }} it works when i replace it by {{ data[safe }} it works perfectly but if not it shows this : weird bar chart output ps : whn i call the 2 variables data and btcprices in th html just to print them on the web page like : {{data}} and {{btcprices}} only data shows !!!! -
How to select all users I don't follow in Django Models
I'm trying to build web app with Django on my backend and I want to make some type of people recommendations and show only people the current user doesn't follow, however I don't know how to do this. It seems like there are questions on StackOverflow however they are about SQL queries and I still only know the Django Models for the database. I use the standard Django User Model and the following model for the following relationship class Follow(models.Model): # This means following(Person A) follows follower(Person B) following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') def __str__(self): return str(self.following.username) + " follows " + str(self.follower.username) class Meta: unique_together = (('following', 'follower'), ) I use the following query to get all the users the current user follows, but I would like to sort-of invert it. Follow.objects.filter(following=user.id).prefetch_related('following') -
How to reset Django database?
I'd really like to know how to reset Django database. Specifically, I accidentally deleted a table with this command, $ python manage.py dbshell $ DROP TABLE qaapp_question; and everything messed up. I followd a stackoverflow post and just deleted the table, and, haha, completely messed up. syncdb stuff is apparently deprecated so cannot use it. I tried all the ways I googled and found, as followings: $ python manage.py migrate qaapp zero django.db.utils.OperationalError: no such table: qaapp_question Not working. $ manage.py migrate --fake <appname> zero $ rm -rf migrations # I deleted the app migrations folder manually $ manage.py makemigrations <appname> $ manage.py migrate --fake <appname> Not working. $ python manage.py flush Not working. $ python manage.py reset_db Reset successful. Not working. manually trying to delete the sqlite database file -> resource busy or locked Not working. I wanted to restore the deleted table, but I don't care anymore, just kindly tell me how to delete, initialize the database, then be able to rebuild the database with python manage.py makemigrations and python manage.py migrate. Thanks for your help. -
relation "accounts_usergroup" does not exist
class UserGroup(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.CharField(max_length=3500,blank=True) isprivate = models.BooleanField(default=False) Error relation "accounts_usergroup" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_usergroup" I did the following for migrations: python3 manage.py makemigrations <app-name> python3 manage.py migrate Everything else works fine but my new addition of models are not working. I don't want to drop the database as app is in production. I don't know why i am getting this error.Can somebody help please? -
When to use *args , *kwargs in python and django
I would like to clarify the following confusion for python and also for django. I understand that you use args when you are not sure how many non-keyword arguments you have and you use kwargs when you are not sure how many keyword arguments you have. However, I am having some confusion as to when to write args and kwargs and when to use something like a keyword eg slug in my views.py in django and for python functions in general. Take for example: def home_page(request, *args, *kwargs): def login_page(request, username): Why can't I use: def login_page(request, *args, *kwargs): Wouldn't it be better that I use *args, *kwargs instead of username since I wont limit myself to the number of variables I can have in my view? Does it have something to do with the URLs too? I understand that if it is (request, username) in views.py, my urls.py will need to have a /login/<username>, so if it is *args, *kwargs, what should it be? -
Trouble understanding what this noReversematch error means
Hey guys I've ran into NoReverseMatch errors before and generally they're quite easy to fix, normally I haven't done the URLs correctly. I'm a bit taken back with understanding this specific error Im just wondering could anyone shed some light on it for me. Thank you Below is the error shown in powershell. django.urls.exceptions.NoReverseMatch: Reverse for 'prod_detail' with arguments '(<django.db.models.query_utils.DeferredAttribute object at 0x000002885125BF10>, UUID('3676f70a-4089-42ba-8eb9-ed760c9e455e'))' not found. 1 pattern(s) tried: ['(?P<category_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/(?P<product_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$'] [21/Mar/2021 13:47:05] "GET / HTTP/1.1" 500 188352 -
Heroku Application Error on django with react
So Everything is fine during deployment in my django and react as frontend project but still, when I try to open the website I get Application Error and it says to do heroku logs --tail to check logs and when I did some errors were shown. P.S:Everything works perfectly during localhost -
Remove the relation with an object from a ManyToManyField (from admin page and/or from view.py)
I have two models Community and User. In the Community model I am creating a field ManyToManyField called member (based on the User Model) i.e. a community object may have many members and a member object may belong to many communities. The issue I am encountering is that I cannot remove a member from a community neither from within the class-based view.py nor from within the admin page . Creating the ManyToMany relation between Community and User with the field name member. class Community(models.Model): member = models.ManyToManyField(User, related_name='member') Code in class-based view.py for removing a member from a community object (removing only the relation, not the related object itself) class CommunityListView(ListView): model = Community def get(self, request, *args, **kwargs): # The url contains the community id (pk) community_id = kwargs['pk'] c = Community.objects.get(id=community_id) u = User.objects.get(id=self.request.user.id) c.member.remove(u) The code is executed without error but when I visit the admin page the member is still there. I have tried to run c.save() after the command c.member.remove(u) but without success either. As I have understood, Django doc says that the method save() is not needed when you remove a relation from a ManyToManyField. Furthermore, as you can see from the attached image … -
multiple singup using social account authentication in djagno
searching too much about this but not get relative stuff. Goal : signup multiple user using social account authentication(google, facebook, apple) in Django. had tried about Django all-auth couldn't solve the problem. any related source ? -
Config CircleCI for Django and MySQL
I'm using CircleCI to build my DRF API. I have been trying for several hours to configure CircleCI with Django and Mysql. While building the application the container circleci/mysql:8.0.4 failed I'm getting this error: Events status: LLA = Last Locked At LUA = Last Unlocked At WOC = Waiting On Condition DL = Data Locked Next activation : never 2021-03-21T13:04:42.752174Z 0 [Warning] [MY-010315] 'user' entry 'mysql.infoschema@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752193Z 0 [Warning] [MY-010315] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752203Z 0 [Warning] [MY-010315] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752212Z 0 [Warning] [MY-010315] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752228Z 0 [Warning] [MY-010323] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752236Z 0 [Warning] [MY-010323] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752247Z 0 [Warning] [MY-010311] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752349Z 0 [Warning] [MY-010330] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752358Z 0 [Warning] [MY-010330] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. Exited with code 1 CircleCI received exit code 1 My .conf.yml: version: 2 jobs: build: docker: - image: circleci/python:3.6.7 - image: circleci/mysql:8.0.4 command: ["mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_bin"] environment: - MYSQL_ROOT_HOST: '%' - MYSQL_ROOT_PASSWORD: root - MYSQL_USER: root - … -
Django two model inheritance one model?
Given the following code:(don't mind the Fields there're just for illustration) Models class UserModel(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) Fields class CommonInfo(models.Model): delete = models.BooleanField(default=False) Fields class MyModel(CommonInfo, UserModel): my_name = models.CharField(max_length=50, blank=False, null=False) Fields Serializer class MySerializer(views.APIView): class Meta: model = MyModel fields = '__all__' Views class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer This upside model, Serializer & Views use. I use in Django REST Framework. but when I call MyModel they give me an error. This error following: init() takes 1 positional argument but 2 were given -
Show an animation on the website while the ML model is being trained. (Django)
So I am building a website in Django, and within that website, there is an option to train a Machine Learning model which only available to the admin(superuser). However, the model does take some time to train. So is it possible to show some animation to the user, while the model is being trained. And once the model has been trained, the animation will stop and the user will be redirected to another page. I did a bit of exploration but wasn't able to find anything useful. Thanks in Advance Cheers -
How can I trigger the removal button when I create a new one by a clone method in Jquery?
the mission is when I click on the plus button to add a new search input it has to add a new field with a plus button and removal button (it calls 'times-btn') everything works fine but when I click on the removal button the first one has created is removed only but when I click on any button else it doesn't work. so, How can I trigger the removal button that? search.html <!-- Search formsets --> <div class="search-field"> <h2 class="show"></h2> <form method="get" id="main_search"> <div id="first_search_group" class="form-group row search_repeated search_group"> <div class="col-lg-2 d-inline p-2 word_repeated"> <label style="font-size: large; padding-top: 5px">Sentence or Word</label> </div> <!-- Filter --> <div class="col-lg-2 d-inline p-2"> <select name="formsets_option" id="formsets_option" class="form-control"> {% if formsets_option == 'contains' %} <option id="contains" value="contains" selected>contains</option> {% else %} <option id="contains" value="contains">contains</option> {% endif %} {% if formsets_option == 'start_with' %} <option id="start_with" value="start_with" selected>start with</option> {% else %} <option id="start_with" value="start_with">start with</option> {% endif %} {% if formsets_option == 'is' %} <option id="is" value="is" selected>is</option> {% else %} <option id="is" value="is">is</option> {% endif %} {% if formsets_option == 'end_with' %} <option id="end_with" value="end_with" selected>end with</option> {% else %} <option id="end_with" value="end_with">end with</option> {% endif %} </select> </div> <div class="col-lg-4 d-inline p-2"> … -
How to get booleanfield values that are True
I am building a BlogApp and I am trying to get all the users that's profile's BooleanField are True. What i am trying to do:- I made a feature of Users that are banned and I made a BooleanField for each user, AND i am trying to get all the Users that's profile's BooleanValue is True. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) block_users = models.BooleanField(choices=BLOCK_CHOISES,default=False) The Problem def block_users(request): profile = request.user.profile blocked = Profile.objects.filter(block_users=profile.block_users) context = {'blocked':blocked} return render(request, 'blocked.html', context) When i runthis code, This only shows me user that's value is False. BUT i want users that's Value is True. I have no idea how to get it. Thanks in Advance. Any help would be Appreciated.