Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with API pagination in django
the problem I'm having is that when I try to click next in the pagination that I did, the link param name "dataType" dosen't stays and it resets to none value, please help. I'm Using django I did some debug and appears like this: [13/Jan/2024 13:33:57] "GET /search/?query=Spaghetti&dataType=&page=27 HTTP/1.1" 200 9901 query: Spaghetti, dataType: Branded, page: 1 [13/Jan/2024 13:34:06] "GET /search/?query=Spaghetti&dataType=Branded HTTP/1.1" 200 7304 query: Spaghetti, dataType: , page: 2 And this is my html: <!-- PAGINATION LINKS --> <div class="pagination"> <span class="step-links"> {% if pagination.current_page > 1 %} <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page=1">&laquo; first</a> <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{ pagination.current_page|add:'-1' }}">previous</a> {% endif %} <span class="current"> Page {{pagination.current_page}} of {{pagination.total_pages}}. </span> {% if pagination.current_page < pagination.total_pages %} <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{ pagination.current_page|add:'1' }}">next</a> <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{pagination.total_pages}}">last &raquo;</a> {% endif %} </span> </div> I don't know if the issue is from the views.py or the html or the forms.py, apreciate your responses!!! I have tried changing the links in the html and nothind I did worked. -
Django ecommerce modeling- how to model product/service options?
I am currently facing a dilemma where we are creating a service which can be used for billing or ecommerce-type applications where products and services are modeled and can be sold. I am working on Services, which have ServiceOptions. The Services are assigned to Businesses, which will each contain a unique combination of Services and ServiceOptions. Because of this, I have represented a Service which all possible ServiceOptions point to as a foreign key relation, creating a BusinessService to assign the unique variants to a Business. However, I am currently unable to understand how to model the relationship between ServiceOptions and the BusinessService. My current service models are as follows: class Service(models.Model): name = models.CharField(max_length=150) description = models.CharField(null=True, max_length=450) price = models.IntegerField(null=True) class ServiceOption(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) name = models.CharField(max_length=150) description = models.CharField(null=True, max_length=450) price = models.IntegerField(null=True) class BusinessService(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) price_override = models.IntegerField(null=True) is_active = models.BooleanField(default=False) activation_date = models.DateTimeField(default=timezone.now) Here we create a unique entity tying the Service to the Business, but this is not sufficient to represent the ServiceOptions, as the BusinessService.service.serviceoption relation contains ALL possible options, not those specific to the business. I have considered structuring the models as follows: … -
Django/Stripe No Reverse Match
I've been following this tutorial (https://www.saaspegasus.com/guides/django-stripe-integrate/) on integrating a subscription service to my application. Everything seems fine, when i checkout it updates my stripe database with the new subscription, but i get a NoReverseMatch error after clicking the checkout button. Specifically, the error says "NoReverseMatch at /subscription-confirm/ Reverse for 'subscription_details' not found. 'subscription_details' is not a valid view function or pattern name." Nowhere in my code do i define a "subscription_details", i was assuming that maybe this was something that came included in the djstripe package? Also the tutorial does nothing to define it either. I'm kind of lost here. The one thing that i see is a little odd is on my views file, when trying to import 'from djstripe.settings import djstripe_settings' and 'from djstripe.models import Subscription', that Pylance isnt recognizing djstripe.settings or djstripe.models. Here is some of the code i think is relevant, if you guys want to see more just ask. Thanks in advance! views.py: from typing import Any from django.db.models.query import QuerySet from django.urls import reverse_lazy, reverse from django.views.generic.edit import CreateView from django.views.generic import TemplateView, ListView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from .models import Picks from django.shortcuts import render from django.core.mail import send_mail, … -
The Connection between two models inside model.py Django
I have database for my Music's and I wanna add a new one for my Artists. What I need is that when I'm adding a new music application check the artist name if artist name was in the Artist Model then pass ,and if not artist name add to Artist Model. class Artist(models.Model): name = models.CharField(max_length=100) followers = models.IntegerField(default=0) class Music(models.Model): name = models.CharField(max_length=150) artist = models.CharField(max_length=150) length = models.CharField(max_length=20) genre = models.CharField(max_length=100) release_date = models.IntegerField() likes = models.IntegerField(default=0) imageLink = models.CharField(max_length=200) mp3Link = models.CharField(max_length=200) def get_artist(self): return self.artist # Set Artist in Artist Model try: # To check Artist exists or not Artist.objects.get(name = get_artist) except: # if Artist not exist then add it Artist(name = get_artist).save() -
Wraning in Django Model
I don't Understand What this exactly means! RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning) Watching for file changes with StatReloader Performing system checks... -
Static files not loading properly
Things I have done: 1.base template i have provide {% load static %} <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="apple-touch-icon" sizes="76x76" href="/static/assets/img/apple-icon.png" > <link rel="icon" type="image/png" href="{% static 'assets/img/favicon.png' %}" > <title> Al Amal Jewellery - {% block title %}{% endblock %} </title> <!-- Fonts and icons --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet" /> <!-- Nucleo Icons --> <link href="{% static "assets/css/nucleo-icons.css" %}" rel="stylesheet" /> <!-- Font Awesome Icons --> <script src="https://kit.fontawesome.com/42d5adcbca.js" crossorigin="anonymous"></script> <!-- CSS Files --> <link id="pagestyle" href="{% static "assets/css/soft-ui-dashboard.css?v=1.0.5" %}" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha256-eTyxS0rkjpLEo16uXTS0uVCS4815lc40K2iVpWDvdSY=" crossorigin="anonymous"></script> <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} </head> <body class="{% block body_class %}{% endblock %}"> {% include "includes/sidebar.html" %} <main class="main-content max-height-vh-full h-100"> {% include "includes/navigation.html" %} {% block content %}{% endblock content %} </main> {% include "includes/fixed-plugin.html" %} {% include "includes/scripts.html" %} <!-- Specific JS goes HERE --> {% block javascripts %}{% endblock javascripts %} <script> var win = navigator.platform.indexOf('Win') > -1; if (win && document.querySelector('#sidenav-scrollbar')) { var options = { damping: '0.5' } Scrollbar.init(document.querySelector('#sidenav-scrollbar'), options); } </script> </body> </html> statics in setting.py based on Managing Static Files """ Django settings for … -
build docker container with postgresql on rpi2
I built django project with cookie-cutter-django. Everything works fine on my local, I could build and running stacks. Now, I am trying to deploy it to my raspberry pi 2. But having issue with psycopg. First, here is the basic config of the project. cookie-cutter-django django 4.2.8 python 3.11.7 Secondly, here is my rpi os info. Operating System: Raspbian GNU/Linux 11 (bullseye) Kernel: Linux 6.1.21-v7+ Architecture: arm postgresql is not installed Thirdly, my local device for development. ubuntu 22.04 I cloned the repo and tried to build production.yml. And got this error. 417.5 Collecting prompt-toolkit==3.0.43 (from -r production.txt (line 50)) 417.6 Downloading prompt_toolkit-3.0.43-py3-none-any.whl.metadata (6.5 kB) 420.4 ERROR: Could not find a version that satisfies the requirement psycopg-binary==3.1.17 (from versions: none) 420.4 ERROR: No matching distribution found for psycopg-binary==3.1.17 I researched a lot, but couldn't find the right answer. The possible solution I could think of was installing the pure python installation on psycopg official documentation. so I tried to add libpq5 to Dockerfile, but having different error like this screenshot. Here is my production Dockerfile. FROM node:20-bullseye-slim as client-builder ARG APP_HOME=/app WORKDIR ${APP_HOME} COPY ./package.json ${APP_HOME} RUN npm install && npm cache clean --force COPY . ${APP_HOME} RUN npm run … -
Django no app_label in model
I have a django rest app called hotels, my structure directory is the following: app/ ├── config │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── hotels │ ├── admin.py │ ├── apps.py │ ├── filters.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── serializers.py │ ├── tests │ └── views.py ├── __init__.py └── __pycache__ └── __init__.cpython-38.pyc In the models.py file I have defined a class called HotelChain as follows: class HotelChain(TimestampedModel): PRICE_CHOICES = [ (1, "$"), (2, "$$"), (3, "$$$"), (4, "$$$$"), ] title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) description = models.TextField(blank=True) email = models.EmailField(max_length=50, blank=True) phone = models.CharField(max_length=50, blank=True) website = models.URLField(max_length=250, blank=True) sales_contact = models.CharField(max_length=250, blank=True) price_range = models.PositiveSmallIntegerField(null=True, blank=True, choices=PRICE_CHOICES) def __str__(self): return f"{self.title}" But I am getting this error: RuntimeError: Model class app.hotels.models.HotelChain doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried adding class Meta: app_label = 'hotels' To the class definition but it doesn't fix the issue. My app config is this one: INSTALLED_APPS = ( 'hotels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'import_export', ) -
How to grant permissions to a so that server allows the creation of directories on the fly
When a user uploads a picture, my django code creates a directory (or folder if you want) with his name (picked up from the session user). This works in my local development environment but production does not grant that permission just like that. So, for savy system administrators out there here it goes: This code is fine MODEL def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) images = ResizedImageField(size=[500, 300], upload_to=user_directory_path, blank=True, null=True) VIEWS.py for image in images: Photos.objects.create(images=image, builtproperties_id=last_built_id, user=username) So, this creates me a directory in this path: media/user_peter media/user_mary etc I thought that by doing this: sudo chmod 775 media It would allow the creation of subdirectories (user_peter, user_mary etc) but, apparently it does not as I got a "permission denied" wrist slap. What command would do that? Thank you -
Is it possible to use requests-cache functionalities on vercel?
Since vercel doesn't support SQLite, I am wondering if python applications like Django deployed on vercel will be able to leverage the functionalities of python's popular requests-cache library. Reason for this is because this library generate SQLite files for caching purpose. Also, is there any workaround using SQLite on vercel. What I tried: using requests-cache library for serverless environment. What is expected: Django app running without any problem on vercel -
Using Model Field Values inside Model.py
I have Model in django and I wanna use username value inside this Account Model to Address ImageField How can I do that? class Account(models.Model): nickname = models.CharField(max_length=150) username = models.CharField(max_length=70) password = models.CharField(max_length=70) email = models.EmailField(max_length=70) avatar = models.ImageField(upload_to = f'userdata/{username}/avatar/' ,default= MEDIA_ROOT + 'default/img/avatar.png') -
Dealing with Tokens in django and react
I'm currently working on a social network app for my Backend, I'm using Django and for the Frontend React-TS. After doing a bit of research, I've decided to use a JWT Token (Generated with help of rest_framework_simplejwt), and use it in requests as a BearerToken. Currently, I'm saving the AccessToken and the RefreshToken in the local storage, but having read a bit about how storing tokens in local storage can pose security risks, such as exposure to Cross-Site Scripting (XSS) attacks, I grew a bit worried. I thought I'd ask here since I came across too many suggestions online (HTTP-Only Cookies, Database Storage with Encryption and Password-Based Encryption). Since I lack the experience to decide which to use when, I would appreciate any and every advice. How do you store your Tokens and why? -
Contact Form, with sending emails but no email is received, DJANGO REST FRAMEWORK
My problem is the terminal says that it is sending email, but there is no email received. Here is my views ` from rest_framework.views import APIView from GoGet import settings from .models import * from rest_framework.response import Response from .serializer import * from django.core.mail import send_mail from django.conf import settings Create your views here. class ContactView(APIView): serializer_class = ContactSerializer def post(self, request): serializer = ContactSerializer(data=request.data) # subject = models.Contact.subject if serializer.is_valid(raise_exception=True): serializer.save() self.send_contact_email(serializer.validated_data) return Response(serializer.data) def send_contact_email(self, data): subject = 'New Contact Form Submission' message = f''' Name: {data['name']} Email: {data['email']} Subject: {data['subject']} Message: {data['message']} ''' send_mail( subject, message, settings.EMAIL_HOST_USER, # Sender's email address [settings.CONTACT_EMAIL], # Receiver's email address (can be a list of multiple emails) fail_silently=True, )` Im expecting an email, but i dont receive any, checked the spams, sent, there is nothing -
Django Auth Login
I have a django project, when I create a user from empty migration files, I can logged in perfectly. But when I create a user from POST method, I can't logged in and it throwing invalid credentials. This is my user model class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField("Username", max_length=50, unique=True) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_password_reset = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) roles = models.ManyToManyField(Role, related_name='users') def delete(self, *args, **kwargs): self.deleted_at = timezone.now() self.save() def save(self, *args, **kwargs): # Hash the password before saving self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def __str__(self): roles_str = "\n".join([str(role) for role in self.roles.all()]) return f"(username: {self.username}, id: {self.id}, is_active: {self.is_active}, is_password_reset: {self.is_password_reset}, roles:\n{roles_str})" this is my login API view @api_view(['POST']) @authentication_classes([]) @permission_classes([AllowAny]) def login(request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user: serializer = UserSerializer(user, context={'request': request}) refresh = RefreshToken.for_user(user) data = { 'user': serializer.data, 'refresh': str(refresh), 'access': str(refresh.access_token), } return Response(data) else: return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) I already tried to debug using raw password without hashing and print out the request from login. It prints out exactly the same as in the database. But it keeps … -
Herokuga django loyihamni joylashtirdim
Men loyihamni migrate va createsuperuser qilishim lozim. Lekin buni amalga oshirib bulmayapti. Qanday qilib loyihamni migrate qilsam buladi. Qanday tavsiya beraszlar Run consoledan migrate va boshqa buyruqlarni berdim ammo buyruqlarimni loyiha papkasiga saqlamayapti -
Django 5 signal asend: unhashable type list
Trying to make a short example with django 5 async signal. Here is the code: View: async def confirm_email_async(request, code): await user_registered_async.asend( sender=User, ) return JsonResponse({"status": "ok"}) Signal: user_registered_async = Signal() @receiver(user_registered_async) async def async_send_welcome_email(sender, **kwargs): print("Sending welcome email...") await asyncio.sleep(5) print("Email sent") The error trace is: Traceback (most recent call last): File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\karonator\Desktop\signals\main\views.py", line 34, in confirm_email_async await user_registered_async.asend( File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\django\dispatch\dispatcher.py", line 250, in asend responses, async_responses = await asyncio.gather( ^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\asyncio\tasks.py", line 819, in gather if arg not in arg_to_fut: ^^^^^^^^^^^^^^^^^^^^^ TypeError: unhashable type: 'list' Will be grateful for any help, already broken my head. Thanks for your time. -
Getting 'Something went wrong' on form submission in Django signup view
I am experiencing an issue in my Django project's signup view. When I submit the form, the console prints 'Something went wrong,' and the user is not created. I have a custom User model, and the signup view appears to be correctly handling form data. However, despite thorough checks of my code, I'm unable to identify the root cause of the problem. --views.py from django.shortcuts import render, redirect from .models import User def signup(request): if request.method == 'POST': name = request.POST.get('name', '') email = request.POST.get('email', '') password1 = request.POST.get('password1', '') password2 = request.POST.get('password2', '') if name and email and password1 and password2: user = User.objects.create_user(name, email, password1) print('User created:', user) return redirect('/login/') else: print('Something went wrong') else: print('Just show the form!') return render(request, 'account/signup.html') I have also made the following settings: AUTH_USER_MODEL = 'account.User' --models.py import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.db import models class CustomUserManager(UserManager): def _create_user_(self, name, email, password, **extra_fields): if not email: raise ValueError('You did not provide an valid e-amil address') email = self.normalize_email(email) user = self.model(email=email, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, name=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user_(name, email, password, **extra_fields) def create_superuser(self, name=None, email=None, password=None, **extra_fields): … -
Guidelines to be good with programming [closed]
Please I really need help, I have been in the field of building websites for more than 3 years now as self thought but it seems as if I'm not learning, please guide me through on how best to be self thought I have tried building projects from Youtube but I always fail. how where and how can I build websites with python and Framework Django -
DRF override default router path
When i register viewset in SimpleRouter i get paths like [get] objects/ [post] objects/ [get] objects/{id} etc. Is there a way to replace default post route with its detailed version? like [post] objects/{id} I've tried to replace it with action in viewset @action(detail=True, methods=['post'], url_path="my-path"): def my_action: ... but all i've got is [post] /objects/{id}/my-path and default post path is still there -
how to delete cache on my VPS Ubuntu Server. Whatever I write on any page is never shown
This is driving me insane. No matter what I do on the pages nothing is shown. Even if I write "hello" on my index.html page it will not show it. The server only shows what I pulled from github a week ago. Nothing, no change. I added the sentry logging tool, it takes zero notice, I copied pasted the logging snippet used and it completely ignores it. I write an extra word on the menu bar at the top, nothing is shown. -
drf-yasg: how to skip some operations during generate_swagger
I use Django with drf-yasg. I have a REST endpoint similar to the following: @swagger_auto_schema( method="POST", request_body=... ) @api_view(["POST"]) def do_something(request: Request) -> HttpResponse: ... When I run the server, I see the do_something operation in /swagger panel, which is fine. Now, when I run ./manage.py generate_swagger I would like do_something operation to NOT show in the resulting OpenAPI yaml. I would like to be able to somehow annotate the operation to be conditionally included, like with some custom @include_conditionally decorator: @include_conditionally @swagger_auto_schema(...) @api_view(["POST"]) def do_something(request: Request) -> HttpResponse: ... I know that setting auto_schema=None prevents the endpoint from being included in Swagger, but it excludes the endpoint from both Swagger web panel and the yaml schema, which I do not want. I tried to use my own generator in ./manage.py generate_swagger -g MyGenerator class MyGenerator(OpenAPISchemaGenerator): def should_include_endpoint(self, path, method, view, public): ... while should_include_endpoint seems to be the right way to go, I failed to detect if the operation was annotated with include_conditionally. Background: I want to exclude some of the endpoints from being exposed with Google ESP while being available locally. How can I exclude some endpoints conditionally from being included in Swagger schema yaml file? -
Re-translate Django
Django comes translated in my language however it's not complete and I don't like some of the translated phrases (personal preference). So I set the locale folder up and run python manage.py makemessages -l fa_IR and I get the file django.po but when I open it, I find that the phrases that are already translated and included with Django are not there. So looks like I have to edit (for example) \venv\Lib\site-packages\django\contrib\auth\locale\fa\LC_MESSAGES\django.po but if I ever update Django package of this project, all my edits will be lost, right? Is there any other solution? -
sorting DataTables from Django
I'm currently working on a Django project where I need to display and sort weather station data in a DataTable. I'm facing an issue when it comes to sorting columns that contain calculated values, such as averages and sums. this code result in clickhouse error due to a problem with the inner join not working as properly I am out of ideas to sort the values (avg_value, max_value,min_value, sum_value, and count_value) please help @cache_page(120) @api_view(['GET']) def station_list(request): serializer = StationListSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) # Extracting DataTables parameters draw = int(request.GET.get('draw', 1)) start = int(request.GET.get('start', 0)) length = int(request.GET.get('length', 10)) order_column_index = int(request.GET.get('order[0][column]', 0)) order_direction = request.GET.get('order[0][dir]', 'asc') search_value = request.GET.get('search[value]', '') selected_region = request.GET.get('region') selected_governorate = request.GET.get('governorate') # QuerySet for AwsGov station_queryset = AwsGov.objects.all() if selected_region: station_queryset = station_queryset.filter(ADMIN=selected_region) if selected_governorate: station_queryset = station_queryset.filter(REGION_ID=selected_governorate) # Define columns for sorting and filtering direct_fields = ['station_id', 'Name', 'ADMIN_NA_1', 'REGION_N_1'] all_fields = direct_fields + ['avg_value', 'max_value', 'min_value', 'sum_value', 'count_value'] # Adjust for language if request.LANGUAGE_CODE == 'ar': direct_fields = ['station_id', 'Name', 'ADMIN_Name', 'REGION_NAM'] if order_column_index < len(all_fields): order_column = all_fields[order_column_index] else: order_column = all_fields[0] # else: # order_column = columns[0] # Default to the first column if out of range if order_column in direct_fields: if … -
Django models, filter based on the division of two fields
I am having trouble understanding the annotate of django models. I am trying to build a datatable where one of its value is the division of two fields that might contain zeros and filter the rest based on the user input so what I tried so far is: model from django.db import models from django.utils import timezone class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.FloatField(default=0.0) unit_per_item = models.FloatField(default=1) description = models.TextField(default='') is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) date_added = models.DateTimeField(default=timezone.now) views from django.db.models import Q, F, Case, When, FloatField from .models import Item if request.POST['search[value]']: model_obj = Item.objects.annotate( unit_price = Case( When(Q(item_price__exact=0) | Q(unit_per_item__exact=0), then=0), default=F("item_price") / F("unit_per_item"), output_field=FloatField() ) ).filter( Q(item_name__icontains=request.POST['search[value]'])| Q(item_price__icontains=request.POST['search[value]'])| Q(unit_per_item__icontains=request.POST['search[value]'])| Q(description__icontains=request.POST['search[value]'])| Q(unit_price__icontains=request.POST['search[value]']) )[start:length] But I am getting an error that says RegisterLookupMixin.get_lookup() missing 1 required positional argument: 'lookup_name' What I am essentially trying to achieve here in SQL is this SELECT *, item_price/unit_per_item AS unit_price FROM inventory_item WHERE item_name LIKE '%some_value%' OR item_price LIKE '%some_value%' OR unit_per_item LIKE '%some_value%' OR description LIKE '%some_value%' OR CONVERT( CASE WHEN item_price=0 OR unit_per_item=0 THEN item_price ELSE item_price/unit_per_item END, CHAR) LIKE '%some_value%'; I am honestly a little lost at this point, if there is a documentation that can expound further … -
Which package to use when dealing with storing and displaying document files like pdf word excel etc in Django and Oracle
I have a requirement where I need to store documents( pdf, word, excel in Oracle database) and display a list of these files on a page serially. When clicked on its name it should open in next tabs in browser. I also need to be able to search and count few keywords in these documents while it been store in the Database. I am just not sure which package I must use in Django for this requirement and which datatype to be used in Oracle. Can anybody please help me for getting started in right direction.