Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Altering command in Django not working , i want to alter database in django?
I added a new coloumn in table and than run command 1. python3 manage.py makemigrations 2. python3 manage.py migrate it show that nothing to migrate but when i entered data it is showing table not found this is my models.py class name(models.Model): name = models.CharField(max_length=255) role = models.CharField(max_length=255) salary = models.IntegerField() def __str__(self): return f"naam = {self.name} and Kaam = {self.role} and tankhwa = {self.salary}" and this is 0001_initial.py operations = [ migrations.CreateModel( name='name', fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID' ), ), ( "name", models.CharField( max_length=75, ), ), ( "role", models.CharField( max_length=75, ), ), ( "salary", models.IntegerField( ), ), ], ), ] -
django subclass not calling superclass (derived from modelform) clean method
I have a django form (formA) that inherits from modelform. In another app, I have a form that derives from that form (formB). This all works ok, including obtaining fields from the base class formA, but when the clean method is called, it doesn't call the formA clean method. Instead it skips formA, and calls django's modelform.clean. I can create a clean method in formB and this is called, but calling the super().clean() method also steps immediately into django's modelform.clean. Why might this be happening and what do I have to do to get the correct inheritance chain for the clean method? MTIA -
Django auth group permission handling
I use Django auth groups. The groups contain permissions(https://docs.djangoproject.com/en/4.1/ref/contrib/auth/#group-model). Now groups are assigned to users based on their actual role. In my test setup one group contains the permission (market.xyz). This group is assigned to the logged in user. In the debugger I see that the group permission is assigned (line 88) But if I call user.has_perm(per1) I get False (line 87) I can not make sense of this result. Is it necessary to activate the auth group mechanism? Do I have to add some additional Middleware? -
Django - analyze query execution time before it gets executed
I have a web interface(in django), through which I execute sql queries on different MySQL DB servers. Can we analyze query execution time(how much time it will take to return the result set) and the size of result set before it actually gets executed? I am using Django and MySQL DB. If cpu utilization is not much and the result set is in few KBs or bytes then query should get executed. -
Counting object views in a ListView
How is it possible to track how many times an object has been viewed if it is shown in a ListView? Imagine the Facebook feed, I want to know how many times users actually see each post on their feed, without opening it. My only thought so far is making an AJAX call for each post when it comes into the user's view, but that seems like it would be too resource heavy. Or should I aggregate the post views and only make the AJAX call once in a while with a list of posts that have been viewed? Or is there any other better way? (Doing it server-side is not ideal, because I want to know that a user actually read the post, so if they spent at least 2-3 seconds reading it). -
Django API rename Model column from existing DB
I have a column ag_id and I want to show it as foo_ag_id on the returning from endpoint. class Foos(models.Model): ag_id = models.ForeignKey('Bars', on_delete=models.CASCADE, db_column='bars_ag_id') class Meta: managed = False db_table = 'foos' I can't change the column name directly at the DB (external). FROM: { "ag_id": 1, }, TO: { "foo_ag_id": 1, }, -
Can I navigate between iPad web applications running on different systems withou show the Safari's url address bar?
I’m a software developer and I developed a web application for iPad using Django. I have four embedded systems connected to the same network and each system run his web application. I added the apple meta-tags for the full-screen mode, which remove the url address bar of Safari. My problem is that i need to navigate between the system’s pages, but, when I load the page of another system, Safari show the address bar. There is a way to don’t show the address bar when I load a page from another system if it has the apple meta-tag too? I tried to automatically touch the screen on "done" to remove the bar on load, but i cannot find a way to persistent remove this bar. -
Using django form to display data
Im new to django and am doing a django project where the user can book appointment slots. I want the user to input a date from a datepicker and then see the slots available to book on that day. I've tried using get requests but i keep getting errors. These are my models class Slot(models.Model): title = models.CharField(max_length=50) def __str__(self): return f'There is a slot at {self.title}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.ForeignKey(Slot, on_delete=models.CASCADE) booking_date = models.DateField(("Date"), default=date.today) def __str__(self): return f'{self.user} has booked a session at {self.slot.title} on {self.booking_date}' Where I set slots as available times (9-10am etc) These are my views def BookingView(request): form = BookingForm(request.POST or None) if form.is_valid(): form.save() form = BookingForm() context = { 'form': form } return render(request, "bookingapp/book_form.html", context) def DateView(request): form = DateForm(request.GET or None) if form.is_valid(): form.save() form = DateForm() context = { 'form': form } return render(request, "bookingapp/date_form.html", context) These are my Forms This is the form I will use when the user is booking the slot. class BookingForm(forms.ModelForm): class Meta: model = Booking fields = [ 'user', 'slot', ] And this is the form I have so far for the user inputting the date. class DateInput(forms.DateInput): … -
Django requests : response much slower than function itself
My application has performance issues (worsening during busy hours). I've noticed following strange behaviour : When I set up the django enviroment: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings.test") django.setup() and try to run the function itself: views.dataCheckFunction (9277 is entry parameter) for i in range(1,10): zac=datetime.now() views.dataCheckFunction(9227) kon=datetime.now() delta=kon-zac print(delta) It runs as expected and each run takes from 0.7s to 1s However when I try to call same function via for i in range(1,10): zac=datetime.now() views.dataCheckFunction(9227) res = requests.get(url='https://profiextra-test.generali.sk/api/policy/9227/dataCheckFunction/', headers={'Content-Type':'application/octet-stream'}) kon=datetime.now() delta=kon-zac print(delta) The duration of each call is very volatile and it can be from 2.3s to 10s The function makes approx 200 database calls. To reduce the traffic I use Memcache Any idea what can be the cause ? Thanks -
How to implement custom authentication on function based view in django rest framework?
if i have created a custom Authentication class CustomAuthentication(BaseAuthentication): def authenticate(self, request): return super().authenticate(request) how do I implement this in function based views? Normally we can use decorators as from rest_framework.authentication import SessionAuthentication, BasicAuthentication @authentication_classes([SessionAuthentication, BasicAuthentication]) def view(request): pass -
Why am I getting a "Cannot return null for non-nullable field" error when doing a query?
**FOLDER STRUCTURE ** models.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Director filter_fields = { "name": ["exact", "icontains", "istartswith"], "first_directed_episode__name": ["exact", "icontains"], "last_directed_episode__name": ["exact", "icontains"], "age": ["exact"], } fields = "__all__" interfaces = (relay.Node,) types.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) … -
Django filters startswith
filters by creating a very simple site. There is a view and the user searches an object that I added as an admin. Views.py from django.shortcuts import render from .filters import * def home(request): myqs = Kati.objects.all() myFilter = SearchForm(request.GET, queryset=myqs) return render(request, 'home.html', {'myFilter':myFilter}) Models.py class Kati(models.Model): name = models.CharField(max_length=200) product = models.CharField(max_length=200) timi = models.CharField(max_length=200) Filters.py import django_filters class SearchForm(django_filters.FilterSet): class Meta: model = Kati fields = ['name','product','timi'] Html <form action='' method='get'> {{myFilter.form}} <button>OK</button> </form> {%for i in myFilter.qs%} <p>{{i.name}}</p> <p>{{i.product}}</p> <p>{{i.timi}}</p> {%endfor%} It works but is there a way to show an object just by typing the first letter. For example if the name is abcd show the object if you write ab. Like __startswith__. -
Django Celery show return value of task
i have a problem to display the return value of my celery task to the client. Redis is my result backend. I hope someone can help me. Thats the code: tasks.py: @shared_task def create_task(task_type): sleep(int(task_type) * 5) data={ 'test':'test' } return data The task should return the data after sleep for the given time. views.py: def home(request): return render(request, "async_project/home.html") @csrf_exempt def run_task(request): if request.POST: task_type = request.POST.get("type") task = create_task.delay(int(task_type)) return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result, } return JsonResponse(result, status=200) urls.py: from django.urls import path from . import views urlpatterns = [ path("tasks/<task_id>/", views.get_status, name="get_status"), path("tasks/", views.run_task, name="run_task"), path("home", views.home, name="home"), ] settings.py: # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' home.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django + Celery + Docker</title> <link rel="stylesheet" type="text/css" href="/staticfiles/bulma.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> </head> <body> <section class="section"> <div class="container"> <div class="column is-two-thirds"> <h1 class="title">Django + Celery + Docker</h1> <hr><br> <div> <h2 class="title is-2">Tasks</h2> <h3>Choose a task length:</h3> <div class="field is-grouped"> <p class="control"> <button class="button is-primary" data-type="1">Short</button> … -
Using signals in django while extending user model
Basically I have 2 models that are 1 to 1 related with User model, First model in Employee and second one is Customer. I am also using signals for updates #Signal functions inside each model @receiver(post_save, sender=User) def create_customer(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def update_customer(sender, instance, created, **kwargs): if created == False: instance.customer.save() When I register a user it gets duplicated both in customer and employee. Is there a way to prevent this? -
Customize group permissions in django?
I need to make role-based authentication. Firstly, I made group permissions for all my apps. I assigned some of them to role according to role's ability. from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group class Role(models.Model): title = models.CharField(max_length=32) groups = models.ManyToManyField(Group) def __str__(self) -> str: return self.title Here you can a see driver role which has access on some group permissions (in fact they are just names of groups) Now I have a user model: class Users(AbstractUser): role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name='roles', blank=True, null=True) def __str__(self): return (self.username) I don't want to pick group permissions every time when I created a new staff user. I just want to set a role to a user and it should automatically pick all permissions based on selected role's groups. How to customize groups in django models? -
Post a CharField to an ArrayField in from React to Django using Axios
I am trying to create a feature where if a user writes a post the ID of the post goes into an ArrayField in the User model so a list of their writing can be accessed. I introduced a new column in the User database, made the necessary migrations and trialed this feature just saving one post ID which worked fine. The issue arose when I made the model field an ArrayField. Now when I do the POST request I get an error response : "{\"posts_written\":{\"0\":[\"Expected a list of items but got type \\\"str\\\".\"]} Currently I am writing the REQUEST as let newPost = new FormData() newPost.append('title', title) newPost.append('content', content) updatePostList.append('posts_written', id + ',') await API.patch(`/profile/user/${loggedInProfile.id}/update/`, updateArticleList, { headers: { 'Authorization': `Token ${sessionToken}`, 'Content-Type': 'multipart/form-data', }, }) I am unsure of how to write the POST request to work with the ArrayField, I have looked online for answers but can't find anything. Here is the User model class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) profile_image = models.ImageField(upload_to='profile_images', default='/profile_images/DefaultAvatar.png') bio = models.CharField(max_length=500, default='', blank=True, null=True) display_name = models.CharField(max_length=250, blank=True, null=True) articles_written = ArrayField( ArrayField(models.CharField(max_length=36, blank=True, null=True)), ) Thank you -
Django Ninja API framework ValueError: Cannot assign "*": "*.*" must be a "*" instance
My project running Django 4.1 and Ninja 0.19.1. I'm trying to make a post request via Swagger or Postman and getting an error ValueError: Cannot assign "115": "Offer.currency_to_sell" must be a "Currency" instance. Post data is: { "currency_to_sell_id": 115, "currency_to_buy_id": 116, "user_id": 1, "amount": 100, "exchange_rate": 10 } Endpoint in api.py @api.post("/add_offer/") async def add_offer(request, payload: OfferIn): offer = await Offer.objects.acreate(**payload.dict()) return {"id": offer.pk} schemas.py class OfferIn(ModelSchema): class Config: model = Offer model_fields = [ "currency_to_sell", "currency_to_buy", "user", "amount", "exchange_rate", ] What am I doing wrong? I tried different approach with Schema instead of ModelSchema and it worked. class OfferIn(Schema): currency_to_sell_id: int = None currency_to_buy_id: int = None user_id: int = None amount: float -
Django like system
I'm doing a blog project, but I have a problem, I'm doing a liking system on the blog, but it gives an error def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_create(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return reverse('main:post_detail') path('blog/like', views.like_post, name='like-post'), class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) <form action="{% url 'main:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> <button class="btn btn-primary" type="submit"> Like</button> <br> <strong>{{ post.liked.all.count }} Likes</strong> </form> That's the mistake I got. https://prnt.sc/y6AHr4buWReN -
MultiValueDictKeyError for multiple file uploads
Goal: I'm looking to have multiple file upload fields from one model, under one view and in one template. The issue is that I get this error: 'MultiValueDictKeyError' when submitting the post request. I have searched https://stackoverflow.com/search?q=MultiValueDictKeyError+file+upload but none of the responses appear to be applicable - as they only cover one field file uploads. Some context: Not all file uploads are required and some can be blank. The user just uploads whatever files are applicable. models.py def user_directory_path(instance, filename): return 'PDFs/{1}'.format(instance.user, filename) class PDFUpload(models.Model): class Meta: verbose_name_plural = 'PDF Uploads' user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) pas = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) add_pass = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) gas_safe = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) oftec = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) hetas = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) bba = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) forms.py class PDF(forms.ModelForm): class Meta: model = PDFUpload fields = ['pas', 'add_pass', 'gas_safe', 'oftec', 'hetas', 'bba'] widgets = { 'pas': ClearableFileInput(attrs={'multiple': True}), 'add_pass': ClearableFileInput(attrs={'multiple': True}), 'gas_safe': ClearableFileInput(attrs={'multiple': True}), 'oftec': ClearableFileInput(attrs={'multiple': True}), 'hetas': ClearableFileInput(attrs={'multiple': True}), 'bba': ClearableFileInput(attrs={'multiple': True}), } labels = { "pas": "PAS", "add_pass": "Additional PAS (if applicable", "gas_safe": "Gas Safe", "oftec": "OFTEC", "hetas": "HETAS", "bba": "BBA", } views.py @login_required def upload(request): if request.method == 'POST': pdf_upload = … -
In the following code I write the Login API but when I print the user it's give me None result
In the following code I created a Login API but when I hit the request in Postman it's always give me Error Response anyone help me out to rectify the problem. I post all of the code and dependencies so anyone can check and give me the solutions. This is my views.py file from django.shortcuts import render from rest_framework.permissions import AllowAny from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer, RegisterSerializer, UserLoginSerializer from django.contrib.auth.models import User from rest_framework import generics, permissions from rest_framework import status from django.contrib.auth import authenticate,login from django.contrib import auth # from knox.models import AuthToken # Create your views here. from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view #Login Credentials "//Create a Login API in Django?" class UserLoginView(APIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def get(self,request,format=None): serializer=UserLoginSerializer(data=request.data) # print(serializer.is_valid(raise_exception=True)); if serializer.is_valid(raise_exception=True): email = serializer.data.get('email') password = serializer.data.get('password') print(email) print(password) user=authenticate(email=email,password=password) print(user) if user is not None: login(request, user) return Response({'msg':'Login Success'},status=status.HTTP_200_OK) else: return Response({'msg':{'Email or Password Does not match'}},status=status.HTTP_404_NOT_FOUND) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #This is my serializer.py file. class UserLoginSerializer(serializers.ModelSerializer): email=serializers.EmailField(max_length=200) class Meta: model = User fields= ['email','password'] When I hit the request then its always give me error so please check my login api … -
Django-Tenant-User Circular Dependency Error during setup
I got issues doing the migrations after setting up django-tenant-user. Just using django-tenant was no issue. Everytime I run python manage.py migrate I get the following circular dependency error: django.db.migrations.exceptions.CircularDependencyError: users.0001_initial, client.0001_initial My settings.py from pathlib import Path import os from dotenv import load_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent load_dotenv() SECRET_KEY = os.getenv('DJANGO_SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] # Application definition SHARED_APPS = [ 'django_tenants', # Django Shared Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tenant_users.permissions', 'tenant_users.tenants', 'client', 'users', ] TENANT_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'tenant_users.permissions', ] INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_USERS_DOMAIN = "localhost" AUTHENTICATION_BACKENDS = ( 'tenant_users.permissions.backend.UserBackend', ) AUTH_USER_MODEL = 'users.TenantUser' TENANT_MODEL = "client.Client" # app.Model TENANT_DOMAIN_MODEL = "client.Domain" # app.Model MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'good_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'good_django.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases print(os.getenv('DB_NAME')) print(os.getenv('DB_USER')) DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } DATABASE_ROUTERS = … -
DecimalField validation error, returns incorrect value Django
Ive got a DecimalField in one of my forms where a user enters a price. Say the user enters 11.00, now when i retrieve it as in (priceform.cleaned_data) it returns Decimal('11.00') so it looks like price = Decimal('11.00') which triggers a validation error when i try to insert it into the database. I'm coming up blank to any solutions for this -
How to copy multiple files from a directory in Dockerfile in one go?
Inside my Django project I have a directory for requirements that are separated for different environments which contains three files dev.txt, common.txt and prod.txt. in Dockerfile I just wanna copy only two of them dev.txt and common.txt into /app/requirements directory inside docker container in one go. FROM python:3.9.15 WORKDIR /app COPY /requirements/common.txt /requirements/dev.txt /requirements/ RUN pip install -r /requirements/dev.txt COPY . /app EXPOSE 8000 I have copied them in this way. but I think there is a better and more readable way. If you know a better way, please tell me. -
Django field choices doesn't appear
I want to appear the issubmitted_choice in my list but it doesn't appear. Can someone has a solution? -
Custom GL Lines Plug-in creates error on paid in full invoices
I created a script that re-books certain transactions depending on the account they were booked to. The script is running fine on all invoices and creating the expected outcome except when an invoice has the status "paid in full". The error states Cannot use 0 as input to setDebitAmount(). Amount to debit must be positive. Already tried the script on the same invoice with different statuses - same outcome. Why does the invoice status make a difference here? /** * Custom GL lines Plug-In Implementation for rebooking Invoices (articles and discounts) * Configuration of Plug-In Implementation: * Transaction Type: Invoice * Subsidiaries: MTE * @param {*} transactionRecord * @param {*} standardLines * @param {*} customLines */ function customizeGlImpact( transactionRecord, standardLines, customLines ) { function sign(x) { // If x is NaN, the result is NaN. // If x is -0, the result is -0. // If x is +0, the result is +0. // If x is negative and not -0, the result is -1. // If x is positive and not +0, the result is +1. return ((x > 0) - (x < 0)) || +x; } if (standardLines.getCount() > 0) { var tranid = transactionRecord.getFieldValue("tranid"); var customername = …