Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to revealed Views in my page by Django?
I tried to be revealed Views in my web page by Django. but I couldn't. even I tried several solutions that suggested by ChatGPT. theses are my codes models.py class PostView(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) views = models.PositiveIntegerField(default=0) def __str__(self): return f'Views for Post: {self.question}' it's my code for create views for each question 1-1. models.py class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_question') subject = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField() modify_date = models.DateTimeField(null=True, blank=True) voter = models.ManyToManyField(User, related_name='voter_question') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_question') def __str__(self): return self.subject and it's Question model that is established the connection with PostView model. and after I wrote this code. I ran 'makemigrations' and 'migrate' base_views.py def view_question(request, question_id): question = get_object_or_404(Question, pk=question_id) post_views, created = PostView.objects.get_or_create(question=question) post_views.views += 1 post_views.save() context = {'question': question, 'post_views': post_views} return render(request, 'pybo/question_detail.html', context) url.py path('question/list/',base_views.index, name='index'), path('quesiton/list/<str:category_name>/', base_views.index, name='index'), path('question/detail/<int:question_id>/', base_views.detail, name='detail'), path('question/detail/<int:question_id>/', base_views.view_question, name='views_question'), template {% if question_list %} {% for question in question_list %} <tr class="text-center"> <td>{{question_list.paginator.count|sub:question_list.start_index|sub:forloop.counter0|add:1 }}</td> <td> {% if question.voter.all.count > 0 %} <span class="badge badge-warning px-2 py-1"> {{ question.voter.all.count}} </span> {% endif %} </td> <td class="text-left"> <a href="{% url 'pybo:detail' question.id %}"> {{ question.subject }} </a> {% if question.answer_set.count > … -
How to create a tournament bracket in Python (Django)?
How to create a tournament bracket in Django if I do have these models. I want to create a tournament bracket in single elimination format. Let's say we have 5 players in certain Tournament: [p1, p2, p3, p4, p5]. Then I have to add null to players until it reaches the next power of two, in this case, it would be 8. [p1, p2, p3, p4, p5, null, null, null]. Level = 1 Level = 2 Level = 3 p1 - null winner of (p1 - null vs p2 - null) the winner of (p1 - null vs p2 - null) vs winner of (p3 - null vs p4 - p5) p2 - null winner of (p3 - null vs p4 - p5) p3 - null p4 - p5 I also need all of this to be pre-generated, so it means that if one of the pair of the Match is a null, then it needs to qualify to the next round, but if there exists both of the players then the winner of that pair will be chosen manually, only then the winner should go to the parent_match class Tournament(models.Model): name = models.CharField(max_length=100) class Player(models.Model): first_name = models.CharField(max_length=50) last_name … -
Django Model subset of database table
All of my models are not managed as they are based on a legacy database. There is a Partner master table holds amongst other things an ID, Code, Name and a PartnerTypeID which is a ForeignKey relationship with a PartnerType Table. The type of Partner can be a client, bank, etc. and each Type has a unique IDentity column, plus an Alpha Code and Name for list boxes and alike. We then have Views that provide the rest of the system with simplified views of the Partner Data based on the Type. Therefore, we have a Client View, Bank View etc. This was done as most Partner attributes are similar across all of the various Partner types. I can set up admin interface over the Partner table with filters etc to help data entry etc. But I would like to know if it is possible to have a separate Django Model reflecting each partner type. Therefore, have a Client Model that only allows creation and modification of a Client Partner. I have no intention of introducing any extra attributes but simply have the Client Model only deal with Partners with a TypeID = 1, and the Bank Model only deal … -
iam getting an error in postman while performing login through api : { "non_field_errors": [ "Unable to log in with provided credentials." ] }
** here is my models.py** from django.db import models from django.contrib.auth.models import AbstractUser from .manager import CustomUserManager STATE_CHOICES = ( ('Odisha', 'Odisha'), ('Karnataka', 'Karnataka') ) ROLES = ( ('admin', 'admin'), ('customer', 'customer'), ('seller', 'seller'), ) class User_role(models.Model): role = models.CharField(max_length=50, blank=True) class User_Profile(AbstractUser): email = models.EmailField(unique=True) username = models.CharField(max_length=100) password = models.CharField(max_length=50) # role = models.CharField(choices=ROLES, max_length=50) role = models.ForeignKey(User_role, on_delete=models.CASCADE) def __str__(self): return self.email USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class Product(models.Model): title = models.CharField(max_length=100) selling_price = models.FloatField() discount_price = models.FloatField() description = models.TextField() productImg = models.ImageField(upload_to="productImages") class Cart(models.Model): user_profile = models.ForeignKey(User_Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) class Order_Placed(models.Model): user_profile = models.ForeignKey(User_Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) order_date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=50) managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None, role=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, username=username, role=role, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None, role=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) # Assign a default role for superusers if role is None: # role = 'admin' from .models import User_role role = User_role.objects.get(role='admin') return self.create_user(email, username, password, role, **extra_fields) here … -
why i am getting a error like no module found
[enter image description hereenter image description here](https://i.stack.imgur.com/fST8f.png) when i am trying to migrate this file i am getting the module error how must i needd to remove that error from the vs code and run properly,This error is even occuring after i have done pip install. -
Migrations not working on azure and django
i'm facing some problems with Django on my azure resource group. The main page of my landing is working fine, but when i try to log in, it does not work, and i get the error that it has ben caused by the "Accounts application" Error: relation "accounts_user" does not exist LINE 1: ...s_user"."admin", "accounts_user"."timestamp" FROM "accounts_... I've performed the migrations on the SSH, but i think that they are not being properly migrated, since even when i "Create a superuser" the user that i've just created does not work to log in and throw the same error. Although it the variables for the database seem to be sent correctly, as i can see on the local variables on the error: ignored_wrapper_args (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7a01ddf85cc0>, 'cursor': <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7a01d58667a0>}) params ('USER EMAIL',) self <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7a01d58667a0> sql ('SELECT "accounts_user"."id", "accounts_user"."password", ' '"accounts_user"."last_login", "accounts_user"."email", ' '"accounts_user"."full_name", "accounts_user"."active", ' '"accounts_user"."staff", "accounts_user"."admin", ' '"accounts_user"."timestamp" FROM "accounts_user" WHERE ' '"accounts_user"."email" = %s LIMIT 21') And: DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'MY HOST NAME.postgres.database.azure.com', 'NAME': 'MY DATABASE NAME', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': … -
JWT Refresh token is not generating on Login
I am doing a django project, using dj-rest-auth, and jwt token. When registering a user, the program generates a refresh token along with access token, but when logging in, it only generates access token and refresh token is an empty string "". I cannot find a similar problem, nor any solution to this. Here is my settings.py: """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-$!z5s1dryft$&tjajmulo+kb7^vi$mfujnzor$_zi(7qv9jxwj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3rd Party 'rest_framework', 'rest_framework_simplejwt', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'corsheaders', #local 'accounts.apps.AccountsConfig', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = … -
torch cuda memory not realeasing
i want to clean up gpu memory using deallocate_memory function. It works atexit function but when I call deallocate_memory function, the memory is not released. def ready(self): # self.deallocate_gpu_memory() # Register resource cleanup for application exit atexit.register(self.cleanup_resources) #works self.deallocate_memory() #does not work def cleanup_resources(self): self.deallocate_gpu_memory() def deallocate_gpu_memory(self): if torch.cuda.is_available(): device = torch.device('cuda:0') # Allocate a small amount of GPU memory dummy_tensor = torch.tensor([0.0], device=device) # Delete the dummy tensor del dummy_tensor # Empty the cache to release memory torch.cuda.empty_cache() print('GPU memory released') -
Django Redirect Urls.py errors
I would like to create a registration form, which then sends more data to another form. My user chooses his username and password on the first form that redirect to the second form where he fills in information such as his city, favorite sport...etc. These two steps work perfectly on their own. Only then I would like to send on a third form on which the user fills in the data of his dogs, which is in another app. For this I use the urls.py of the project, and I include the urls.py of the apps. From there it no longer works. If I only use the users form, and its urls, it works, but if I import the urls.py then I cannot access the second form without a "NoReverseMatch at /signup/ Reverse for 'additional_details_main_user' not found. 'additional_details_main_user' is not a valid view function or pattern name.NoReverseMatch at /signup/." This error happens after the first form, which is only username and password. I cannot even access to the other one of the user. This is my code structure: robert (main app) urls.py userProfile folders : templates, static...etc urls.py dogProfile folders : templates, static...etc urls.py urls.py from robert: from django.contrib import … -
Forbidden (403) CSRF check failed. Order cancelled. Djnago - python
Proibido (403) Verificação CSRF falhou. Pedido cancelado. Help Reason given for failure: Origin checking failed - https://dashboardequiuniemp.fly.dev does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. … -
class not seing it's properties
my class from django.db import models from django.contrib.auth.models import User class Task(models.Model): id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default="") deadline: models.IntegerField(default=None) creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.id) + str(self.content) my error: File "/Users/ironside/Documents/Python/PythonDjango-Project/api/models.py", line 13, in str return str(self.id) + str(self.content) AttributeError: 'Task' object has no attribute 'content' I tested, and all other properties give the same error ('content' changes to property name). It's as if it only sees id as valid property. I'd like to be able to print the id + content or any other property -
django.core.exceptions.ImproperlyConfigured Django 4.2.6
So, I started refactoring my project, but I also deleted my migrations folder (which I just learned is a no-no.) Now I can't run the server or tests. I only get the error below. File "C:\Users\Documents\projects\venv\Lib\site-packages\django\urls\resolvers.py", line 237, in _compile raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: "^users\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 2; was group 1 at position 37 I tried starting the project again in a separate folder with a new db, copying and pasting the necessary code, then running makemigrations and migrate, but the same error keeps appearing. I don't want to have to start from scratch again, so if there's a way to fix it, please let me know. I still have the migrations table and info in my first db, if that helps. -
How to add element class in ckeditor on django?
I'm trying add default element class in ckeditor on Django website like. <ul class="sm-circle"></ul> -
Set default widget for custom model field in django 4
I would like to have a custom field which uses a specific widget. In my example it's a model.CharField derived field. It should always use forms.Textarea instead of the default forms.TextInput. I want to have this definition in MyCustomField class, to not always have to override the admin form to use the specific widget. This is my code: class MyCustomField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 # Set the fixed max length here super().__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'widget': forms.Textarea} defaults.update(kwargs) return super().formfield(**defaults) It just shows forms.TextInput widget instead of forms.Textarea - any idea what is wrong? -
How do I inherit from different templates in Djanog based on whether the user is logged in or not
Exactly what the question says. I have three templates base.html, logged_in_base.html, and page.html. I want page.html to extend base.html when the user isn't logged in and to extend logged_in_base.html when the user is logged in. How do I do this? (This is basically because I have a different navbar for logged in users and not logged in users.) -
Textarea adding whitespaces everytime I submit
I have a form with textarea and everytime I click the submit button and use it again, it adds whitespaces. {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>Edit Page</h1> <form method="POST" action="{% url 'edit' title=title %}"> {% csrf_token %} <div id="title"> <label>Title:</label> <textarea name="title" class="form-control" style="width: 600px; height: 50px;">{{ title }}</textarea> </div> <div id="body"> <label>Body:</label> <textarea name="content" class="form-control" rows="5" style="width: 600px; height: 400px;">{{ content }}</textarea> </div> <input type="submit" class="btn btn-primary" value="Edit" style="margin-left: 546px; margin-top: 10px;"> </form> {% endblock %} I need to know how do I prevent it adding whitespaces -
Run a specific function on a specific field in a queryset
I am trying to run a function on a specific field in a queryset before i send it to the template for rendering. I have the following models. class Customer(models.Model): name = models.CharField(max_length=255) class Device(models.Model): cid = models.ForeignKey(Customer, on_delete=models.CASCADE) name = models.CharField(max_length=255) oid = models.TextField(null=True) I have the following view, that i am trying to run the checkStatus function on queryset field of objectid, but everytime it runs i get the following error, the "info" is the value that the checkStatus function is returning back. error TypeError: QuerySet.annotate() received non-expression(s): info. views.py def device_detail(request, cid): customers = models.Customer.objects.all() customer_details = get_object_or_404(models.Customer, id=cid) device_details = customer_details.device_set.all() device_details.annotate(checkStatus("objectid")) return render(request, 'devices/detail.html', { 'device_details': device_details }) -
deployed django webpage using apache and mode_wsgi doesnt show other pages aside from index.html
I am totally new to the world of Django, I recently tried to deploy my website on production server and I have been successful to some extent. I deployed the website on a windows base VPS, using apache and mode_wsgi. the webpage is up and running, I can view it on localhost, the problem is when I try to show other pages of the website like "localhost/about", it gives me " Not Found The requested resource was not found on this server. " does anybody had the same issue? any help in how to solve it would be much appreciated -
Django not sending debug errors in production
I have a django app running on production but server errors are not sent to the established e-mail. This is my settings.py: ADMINS = [('Foo the man', "******@gmail.com")] SERVER_EMAIL = os.getenv('SERVER_EMAIL') EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_HOST_IMAP = os.getenv('EMAIL_HOST_IMAP') EMAIL_PORT = '587' EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') Regular e-mails from within the app are being sent correctly, but debug errors are not sent and I can't figure out why. -
Accessing model attributes results in Self not defined error
Can anyone help me understand why I am receiving the error self is not defined while accessing a class attribute? Thanks for your help class Receipt(models.Model): "" receipt_id = models.AutoField( primary_key=True, db_comment="" ) store_name = models.TextField( max_length=255, default="Unidentified", db_comment="" ) total_amt = models.DecimalField( max_digits=6, decimal_places=2, default=0.00, db_comment="" ) def create_from_document(document): "" if (document is None): return False self.store_name = document.store_name self.total_amt = document.total_amt self.save() return self -
Why does my Django view return 'Reverse for 'initiate_transcription' with arguments '('',)' not found'?
A user uploads a file on page 1 and the site redirects them to page 2 where they can click a button which triggers the service. I'm trying to create a unique URL for each user upload and I know the error has to do with the {% url 'initiate_transcription' session_id %} in HTML page 2 form but i'm not sure what to change. Here is the code: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.transcribeSubmit, name = "transcribeSubmit"), path("init-transcription/<str:session_id>/", views.initiate_transcription, name = "initiate_transcription"), ] views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) session_id = str(uuid.uuid4()) request.session['session_id'] = session_id # Render the 'transcribe-complete.html' template to a string return JsonResponse({'redirect': reverse('initiate_transcription', args=[session_id])}) else: else: form = UploadFileForm() @csrf_protect def initiate_transcription(request, session_id): if request.method == 'POST': try: # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcript = transcribe_file(path_string,audio_language, output_file_type ) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, … -
Django inline with PolymorphicParentModelAdmin
i have a problem with my CreationInline, i have this code in models.py: class Creation(PolymorphicModel): """Model representing a creation.""" original_title = models.CharField('Título original', max_length=10000, null=True, blank=True,) subtitles = models.TextField('Subtítulos, capítulos y entregas', null=True, blank=True,) authorship = models.TextField('Autoría', null=True, blank=True,) publication_year = models.IntegerField("Año de publicación",default=2023, choices=((i,i) for i in range(1930, 2024))) synopsis = models.TextField('Sinopsis', null=True, blank=True,) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True,) keywords = models.ManyToManyField(KeyWord, blank=True) product = models.OneToOneField("Product", on_delete=models.CASCADE, related_name="product_creation") def __str__(self): return self.product.title class MediaCreation(Creation): original_language = models.ForeignKey(Language, on_delete=models.SET_NULL,blank=True, null=True) IMDb = models.CharField(max_length=10000,blank=True, null=True) commertial_editions = models.CharField('Ediciones comerciales', max_length=10000,blank=True, null=True) class Movie(MediaCreation): """Model representing a Movie.""" remastering = models.TextField('Reedición', null=True, blank=True) direction = models.TextField('Dirección', null=True, blank=True) producer = models.TextField('Producción', null=True, blank=True) genre = models.ManyToManyField(Genre, limit_choices_to={"type": "Movie"}) there are other models that inherit from Creation, such us Novel, Comin, etc. My code in admin.py is: class CreationInline(NestedStackedInline): model=Creation class CreationParentAdmin(PolymorphicParentModelAdmin): """Parent admin class for Creation model.""" base_model = Creation child_models = (Movie, Musica, TVSerie, Videogame, Theatre) @admin.register(Creation) class CreationAdmin(CreationParentAdmin, DisableAddButtonModelAdmin): """Admin class for Creation model.""" base_model = Creation readonly_fields = ('product',) child_models = (Movie, Musica, TVSerie, Videogame, Theatre, Novel, Comic, BoardGame) list_filter = (PolymorphicChildModelFilter, ) list_display = ('get_product_title', 'original_title', 'authorship', 'publication_year') def get_product_title(self, obj): return obj.product.title # Obtiene el título … -
Printing to thermal printer in python
I have been trying to print on a POS printer and a label printer, depending on the running function. Here is where I am at: import win32print, win32ui, win32con # X from the left margin, Y from top margin # both in pixels X=50; Y=50 # Separate lines from Your string # for example:input_string and create # new string for example: multi_line_string # @@@@@@@ lable = Lable.objects.all().last() # @@@@@@@ multi_line_string = label_text.splitlines() the_name_will_appear_on_printer_spool = str(f"print_job{lable.id}") hDC = win32ui.CreateDC () # Set default printer from Windows: # hDC.CreatePrinterDC (win32print.GetDefaultPrinter ()) hDC.CreatePrinterDC(win32print.OpenPrinter(printers.label)) hDC.StartDoc (the_name_will_appear_on_printer_spool) hDC.StartPage () for line in multi_line_string: hDC.TextOut(X,Y,line) Y += 50 print(hDC.TextOut.text()) hDC.EndPage () hDC.EndDoc () message.success(request, 'Test printer job send') I have been using p = win32print.OpenPrinter("EPSON LX-350") to grab a specific printer but in this case i need to use something like this: hDC.CreatePrinterDC (win32print.OpenPrinter("EPSON LX-350")). The problem is I'm getting this error: Objects of type 'PyHANDLE' can not be converted to Unicode. Since i grabbed this from a 2013 answer there may be a better way to do this, I'm open to suggestions. Thank you in advance -
DJango Left join issues
LEFT JOIN ISSUE Model1 KPI_ID KPI_Name 1 KPI1 2 KPI2 3 KPI3 4 KPI4 Model2 Emp_Name KPI_ID Amount Mr. A 1 100 Mr. A 3 200 Mr. B 2 300 Mr. B 4 400 Output For Employe : Mr. A KPI_ID KPI_Name Amount 1 KPI1 100 2 KPI2 NULL 3 KPI3 200 4 KPI4 NULL For Employe : Mr. B KPI_ID KPI_Name Amount 1 KPI1 NULL 2 KPI2 300 3 KPI3 NULL 4 KPI4 400 Django left join issue -
best practice for dynamic filtering
I want to filter with keywords the user can enter. for example: models.py: class Product(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() now I want to let the user enter "category": "teapot" or "name": "IKEA Glas 0.5L" and the code should in the get_queryset method execute: def get_queryset(self): VALUE = self.request.GET.keys(SOMEPARAM) return Product.objects.filter(SOMEPARAM__contains=VALUE) how can this be done (I know I can do a lot of if clauses, but my model is quite large in terms of fields that can all be handled equally. so for example for the IKEA example that would be: Product.objects.filter(name__contains="IKEA Glas ...")