Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to display the list of name of the tags django-taggit
I currently learning Django and creating my first blog in Django 4.0.x but something is error when i use django-taggit The problem is when i display the tags in my html it doesn't show, i tried watching an example but it is quite difficult for me to follow the method because i have a slug in my MangaDetailView. Here is my code: models class Manga_Info(models.Model): class Newmanager(models.Manager): def get_queryset(self): return super().get_queryset(). filter(status='published') options = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=350) about = models.TextField(max_length=500) type = models.ForeignKey(Type, on_delete=models.PROTECT, default=0, blank=False, null=False) genre = TaggableManager() upload = models.DateTimeField(auto_now_add=True) released = models.DateTimeField(max_length=100) menu_image = ProcessedImageField(upload_to= user_directory_path, processors=[ResizeToFill(175, 238)], default = 'images/blog-post-01.jpeg', format='jpeg', options={'quality': 100}) info_image = ProcessedImageField(upload_to= user_directory_path, processors=[ResizeToFill(175, 579)], default = 'images/blog-post-01.jpeg', format='jpeg', options={'quality': 100}) slug = models.SlugField(max_length=100, unique_for_date='upload', unique=True) status = models.CharField(max_length=15, choices=options, default='draft') objects = models.Manager() # default manager newmanager = Newmanager() # custom manager class Meta: ordering = ("upload",) def __str__(self): return self.title views def MangaDetailView(request,_id): try: dataset = Manga_Info.objects.all() type = Type.objects.exclude(name='default') data = Manga_Info.newmanager.get(slug =_id) except Manga_Info.DoesNotExist: raise Http404("Data does not exist") context = { 'data':data, 'dataset': dataset, 'type': type, 'tag':tag, } return render(request, 'base/home_info.html', context) def tagged(request, slug): tag = get_object_or_404(Tag, slug=slug) posts … -
django modeltranslation prefix_default_language
i add prefix_default_language = False in urls.py urlpatterns += i18n_patterns( path('', include('main.urls')), prefix_default_language= False ) but the form for changing the language stopped working for the default language form: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} {% if language.code == 'en' %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {%else%} <option value=""> {{ language.name_local }} ({{ language.code }}) {%endif%} {% endfor %} </select> <input type="submit" value="Go"> </form> how fix it? -
Python: how to select n number of elements of each type from OrderedDict?
I have a Django serializer returning an OrderedDict from the serializer.data. It can contain for example this type of data: [OrderedDict([('id', '1'), ('date', '2022-01-08'), ('type', 'A')]), OrderedDict([('id', '2'), ('date', '2022-01-09'), ('type', 'A')]), OrderedDict([('id', '3'), ('date', '2022-01-08'), ('type', 'B')]), OrderedDict([('id', '4'), ('date', '2022-01-09'), ('type', 'B')]), OrderedDict([('id', '5'), ('date', '2022-01-08'), ('type', 'C')]), OrderedDict([('id', '6'), ('date', '2022-01-09'), ('type', 'C')])] I'd like to take the first element of each type and make a json out of that data. I could use for -loops to iterate through the dict and make a new list containing one element of each type: A, B and C. I'd like to know if there's some cleaner and neater way to go through the dict and select n number from each type? -
Ajax Integration with Django and Font Awesome Icon Change
I have a Django app where I want to display a page containing user posts which can be liked by other users by clicking on a Font Awesome Icon which futher is in an anchor tag. When a post is liked by a user, the icon class should be changed from fa-heart to fa-heart-o and vice-versa. To achieve this an Ajax request is made by the click event on the icon. This changes the icon and increments/decrements the like count. I have this like FBV: #feeds/views.py @login_required def like(request): post_id = request.GET.get("post_id", "") user = request.user post = Post.objects.get(pk=post_id) liked= False like = Like.objects.filter(user=user, post=post) if like: like.delete() else: liked = True Like.objects.create(user=user, post=post) resp = { 'liked':liked } response = json.dumps(resp) return HttpResponse(response, content_type = "application/json") And in urls.py : urlpatterns=[ path('like/', views.like, name='like'), ] This is the template {% for post in posts %} ...... </li> <li> {% if post in liked_post %} <span class="like" data-toggle="tooltip" title="Unlike"> <a id="like" post_id="{{ post.id }}"><i class="fa fa-heart"></i></a> <ins>{{ post.likes.count }}</ins> </span> </a> {% else %} <span class="like" data-toggle="tooltip" title="Like"> <a id="like" post_id="{{ post.id }}"><i class="fa fa-heart-o"></i></a> <ins>{{ post.likes.count }}</ins> </span> </a> {% endif %} </li> ... {% endfor %} This is … -
How do I maintain the scroll position when returning to a page using lazy load?
Actually, the question is very clear, as seen in the title. The part I want to add is this, just like on Twitter, when I go down the page and then enter a user profile or post detail and return to the previous page by pressing the back button on the browser, the page opens where I left off, despite being lazy. How can I achieve this with Django. I don't know if it matters, but Vue is used as cdn in my project. I would like to talk about an example on the subject. In Safari and Chrome browsers on a computer with macOS, when the back button is pressed on the browser, exactly the event I want takes place. It comes back as if the previous page was cached, but on computers with Windows or Linux, when the back button on the browser is pressed, it goes to the previous page by requesting it again. -
How to set Django model attribute based on another attribute?
I have a model which takes time into account. So when I set is_all_day as True I want my start_hour and end_hour to return 6:00 and 23:59 respectively but it returns null. This is my model: class TestModel(models.Model): start_hour = models.TimeField(blank=True, null=True) end_hour = models.TimeField(blank=True, null=True) is_all_day = models.BooleanField(default=True) class Meta: managed = True db_table = 'test_model' def start_all_day(self): if self.is_all_day == 'True': self.start_hour = '6:00' self.start_hour.save() return self.start_hour else: return self.start_hour def end_all_day(self): if self.is_all_day == 'True': self.end_hour = '23:59' self.end_hour.save() return self.end_hour else: return self.start_hour What am I doing wrong here? -
How can i switch between databases at runtime based on settings?
Hello everyone and thanks in advance. In my scenario I need to configure different databases, each for every workshop DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'default.sqlite3', }, 'ws1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'ws1.sqlite3', }, 'ws2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'ws3.sqlite3', } } Workshops are centralized in the default database (as well as other info's which are not important for this use case) and they have the following structure [ { "name":"ws1", "database":"ws1.sqlite3" }, { "name":"ws2", "database":"ws2.sqlite3" } ] Based on the above settings the user can select the Workshop he needs and we (behind the scenes) will need to hot-switch database so Models will Query in ws1.sqlite3 or ws2.sqlite3. Each specific Workshop DB (ex: ws1.sqlite3) is structured in the following way. -- ws1.datas CREATE TABLE "datas" ( "id" INTEGER, "value" REAL, "unixtimestamp" INTEGER ); -- ws1.options CREATE TABLE "options" ( "name" TEXT, "value" TEXT ); -
Validating django rest api get request using traditional forms class
I am trying to validate a DRF get request using django form as follows, The view of django rest api @csrf_exempt @api_view(['GET', 'POST']) def pkg_list(request): if request.method == 'GET': frm=ThisForm(request.GET) if frm.is_valid: print("form ok") print(frm.cleaned_data) else: print("invalid") mydata=[{"email": request.GET['reseller']}] results=ResellerListPackages(mydata,many=True).data return Response(results) The view class is form is as follows, class ThisForm(forms.Form): reseller=forms.EmailField(max_length=255) def clean(self): self.cleaned_data = super().clean() print(self.cleaned_data) return self.cleaned_data The form validation seems working fine , but the frm.cleaned_data is not found with the following error, print(frm.cleaned_data) AttributeError: 'ThisForm' object has no attribute 'cleaned_data' Can some one point to me the correct direction. It is the first time using the DRF -
Enabling HTTP/2 Support in daphne with django
When I run this command command: daphne -e ssl:443:privateKey=key.pem:certKey=crt.pem server.asgi:application --port 8000 --bind 0.0.0.0 The error I get is as follows Starting server at ssl:443:privateKey=key.pem:certKey=crt.pem, tcp:port=8000:interface=0.0.0.0 HTTP/2 support enabled Configuring endpoint ssl:443:privateKey=key.pem:certKey=crt.pem Traceback (most recent call last): ... FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/crt.pem' Can someone tell how to fix this error? -
How to increase number of workers in Daphne with Django
With gunicorn I can increase thenumber of workers using -w 17 command: gunicorn server.asgi:application --bind 0.0.0.0:8000 -w 17 -k uvicorn.workers.UvicornWorker How can I do that with daphne to utilize the CPU available? command: daphne server.asgi:application --port 8000 --bind 0.0.0.0 -
How to show the errors in the template?
Working on a simple project using Django, and just finished the login/register form. What I'm trying to do is to show up the errors when the user doesn't do something in the right way(ex: not matching the password) I did the login/register form by using this library from django.contrib.auth import authenticate, login, logout and It did pretty well. How can I show the errors in the template? -
Django - How to check if the email already exist in the data base and if its mine or not
Am new to django and am trying to make a function where the user can change their info from their profile page but if I dont change the email I still get the validation error that the email already exist in the database. Forms.py def clean_email(self): email = self.cleaned_data['email'].lower() try: u = CustomerUser.objects.get(email=email) except CustomerUser.DoesNotExist and self.user == self.request.user: return email raise forms.ValidationError( 'Er bestaat al een account met het e-mailadres dat je hebt ingevuld. ' 'Gebruik dan alsjeblieft een ander e-mailadres.') Views.py @method_decorator(login_required(login_url='login'), name='dispatch') class Profile(SuccessMessageMixin ,UpdateView): form_class = UserInfo template_name="user/profile_page.html" success_message = f'Uw account is bijgewerkt' success_url = reverse_lazy("profile") def get_object(self): return self.request.user -
How do you fix ERROR: Command errored out with exit status 1:
I was running pip install -r requirements.txt when I got the following error. Does anyone know what I should do? Thank you. ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/t mp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/setup.py'"'"'; __file__='"'"'/tmp/pi p-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/setup.py'"'"';f = getattr(tokenize, '"'"' open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import s etup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code , __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-as1v9v4s/install-record.txt --single-v ersion-externally-managed --user --prefix= --compile --install-headers /web/.local/include/python3.6m /rcssmin cwd: /tmp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/ Complete output (16 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 copying ./rcssmin.py -> build/lib.linux-x86_64-3.6 running build_ext building '_rcssmin' extension creating build/temp.linux-x86_64-3.6 gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= 2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=g eneric -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DEXT_MODULE=_rcssmin -UEXT_PACKAGE -I_setup/include -I/usr/ include/python3.6m -c rcssmin.c -o build/temp.linux-x86_64-3.6/rcssmin.o In file included from rcssmin.c:18:0: _setup/include/cext.h:34:20: fatal error: Python.h: 그런 파일이나 디렉터리가 없습니다 #include "Python.h" ^ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import io, os, sys, setuptools , tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/set up.py'"'"'; __file__='"'"'/tmp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/setup.py '"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.Strin gIO('"'"'from setuptools import setup; setup()'"'"');code = … -
Legends not visible in django piechart
I created a donut pie chart using django. But it is not showing all the legends. Most of them are invisible.Pie chart Here is my django code. Plz suggest me the changes so that all legends are properly visible. def __get_fiat_piechart(balances, fiat): EPS = 0.009 return { 'charttype': "pieChart", 'chartdata': { 'x': [x['currency'] for x in balances if x['amount_fiat'] > EPS], 'y1': [x['amount_fiat'] for x in balances if x['amount_fiat'] > EPS], 'color':'blue', 'extra1': { "tooltip": { "y_start": "", "y_end": fiat, } } }, 'chartcontainer': "fiat_container", 'extra': { 'x_is_date': False, 'x_axis_format': '', 'tag_script_js': True, 'jquery_on_ready': False, 'donut':True, 'donutRatio':0.5, 'chart_attr':{ 'labelThreshold':0.0001, 'labelType':'\"percent\"',} } } -
Passing default values into an unbound django form
I have two select classes that I am trying to create in an unbound form. The data selections are only relevant to the presentation that is created in the view, so are throwaways and do not need to be saved in a model. The challenge I have is that I can pass in the field listings ok, but how do I set "default" checked / selected values so that the form becomes 'bound'? views.py def cards(request): sort_name = [] sort_name.append("Alphabetic Order") sort_name.append("Most Popular") sort_name.append("Least Popular") sort_name.append("Highest Win Rate") sort_name.append("Lowest Win Rate") sort_id = range(len(sort_name)) sort_list = list(zip(sort_id, sort_name)) <more code to make filt_list and zip it> if request.method == 'POST': form = cardStatsForm(request.POST, sortList=sort_list, filtList=filt_list) if form.is_valid(): do something else: do something else else: form = cardStatsForm(filter_list, sort_list) forms.py class cardStatsForm(forms.Form): def __init__(self, filterList, sortList, *args, **kwargs): super(cardStatsForm, self).__init__(*args, **kwargs) self.fields['filts'].choices = filterList self.fields['filts'].label = "Select player rankings for inclusion in statistics:" self.fields['sorts'].choices = sortList self.fields['sorts'].label = "Choose a sort order:" filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True) sorts = forms.ChoiceField(choices=(), required=True) The difficulty I am having is the the form fails the "is_valid" test since it is not bound, and I have the "required=true" setting (so that the user must select … -
Django +docker-compose + Celery + redis - How to use Redis deployed in my own remote server?
I have a Django app deployed in Docker containers. I have 3 config environnements: dev, preprod and prod. dev is my local environnement (localhost) and preprod/prod are remote linux environnements. It works when using the "public" Redis server and standard config. But I need to use our own Redis deployed in Docker container in a remote server (192.168.xx.xx) with name container redis_cont. And I do not really know how to config. I do not know if it is possible? I would appreciate some help. docker-compose version: '3.7' services: web: restart: always build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev entrypoint: [ "/usr/src/app/entrypoint.dev.sh" ] depends_on: - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 redis: container_name: redis_cont <= container running in remote linux server image: "redis:alpine" celery: build: context: ./app dockerfile: Dockerfile.dev command: celery -A core worker -l info volumes: - ./app:/usr/src/app env_file: - ./.env.dev depends_on: - web - redis celery-beat: build: context: ./app dockerfile: Dockerfile.dev command: celery -A core beat -l info volumes: - ./app:/usr/src/app env_file: - ./.env.dev depends_on: - web - redis settings.py CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' CELERY_ACCEPT_CONTENT = … -
cannot import name 'url' from 'django.conf.urls'
I have been trying to makemigrations in my django project but I keep getting this error constanly even though I'm using path instead of url can someone please help me? The error is being caused by the froala_editor path but I don't understand why. -
Django ModelForm Foreign Key Dropdown
I'm having a problem and I couldn't find the error. My dropdown with foreign key is showing "Client object(1)", but my models, views and forms is similar for all views that have the same situation. Model: class Cliente(models.Model): nome = CharField(max_length=50) cnpj = IntegerField() dateCriacao = DateTimeField(auto_now_add=True) def __self__(self): return self.nome Model for product: class ProdutoCliente(models.Model): def filePath(produto, file): return os.path.join('produtos', produto, file) numeroSerie = CharField(max_length=30, null=True) produto = CharField(max_length=30) file = FileField(upload_to=filePath) cliente = ForeignKey(Cliente, on_delete=CASCADE) dateCriacao = DateTimeField(auto_now_add=True) def __self__(self): return self.id Views: def NewCustomerProducts(request): createCustomerProducts = CustomerProductsForm() if request.method == 'POST': createCustomerProducts = CustomerProductsForm(request.POST or None) if createCustomerProducts.is_valid(): createCustomerProducts.save() return redirect('products:Customer_Products') else: createCustomerProducts = CustomerProductsForm() context = {'createCustomerProducts' : createCustomerProducts} return render(request, 'produtos/NewCustomerProducts.html', context) forms: class CustomerProductsForm(ModelForm): numeroSerie = fields.CharField (blank=True) class Meta: model = ProdutoCliente fields = [ 'numeroSerie', 'produto', 'cliente', 'file' ] labels = { 'numeroSerie': ('Número de Série'), 'produto': ('Produto'), 'cliente': ('Cliente'), 'file': ('Arquivo') } result: https://imgur.com/Cft5AOW -
Django: When a user updates a Profile Model information, the default User username adds ('username',)
I have a Profile model that updates the default django model User by using signals. The model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) The signal to send the information updated by the user to the default Django User is as follows: def updateUser(sender, instance,created, **kwargs): profile = instance user = profile.user if created == False: user.name = profile.name, user.email = profile.email, user.username = profile.username, user.save() post_save.connect(updateUser, sender=Profile) The updated User username changes to the following format: ('username',). Do you have any idea of why that is happening? I have failed in identifying the error. Than you in advance. -
How to send information between two html using json and POST?
In 'cart.html' I have a form of id="order-selection-cart" which is for selecting user's order, which the user wants to make payment for. <select id="order-selection-cart" onchange="order_cart()" class="form-control"> {% for order in orders_for_user %} <option>{{order.id_zamowienie}}</option> {% endfor %} </select> In the same html page, I also display the selected order value ({{order.id_zamowienie}} in a form of id="order-selection-cart": <div class="row cart-box" style="background-color:rgb(226, 226, 226);"> <h10>Szczegóły zamówienia </h10> <h4 type="value" id="order-details"></h4> </div> Now, I want to go to 'checkout.html' by clicking a button of name 'Zamawiam' and I have done it like this: <div class="row cart-box" style="background-color:rgb(226, 226, 226);"> <h4>Suma zamówienia</h4> <h10>Suma: {{cart_total|floatformat:2}} zł</h10> <br> <a class="btn btn-primary" href="{% url 'checkout' %}" role="button">Zamawiam</a> </div> This code works, but I have a problem with remembering selected user's order which he wants to make payment for. Let's say I selected option 2, I want to remember it and when clicked 'Zamawiam' I want to go to 'checkout.html' where this value (2) can be accessed and not changed when it is again changed (if user changes it in cart.html in other window for example). At first I have had js code which was changing value of selected option in 'cart.html': // ordernumber update in cart.html function order_cart() … -
How to modify the error form of the authentication in Django?
Working on a simple project using Django 4 and just finished the login register form, and now I'm working to show the errors if a credential is entered wrong. What I'm trying to do is to modify the error text that is shown. I show the errors on template: {{form.errors}} , and this is the result: How can I remove the password2 word from the form in the template? -
DRF. Trying to create a record that requires an instance of another DB object, and keep getting "int() argument must be a string..."
I'm new to Django and DRF and I'm really struggling with something. I'm attempting to create a record in a table that has a foreign key. We'll say the models looks like this: class Foo(models.Model): foo_id = models.IntegerField( primary_key=True, ) name = models.CharField( max_length=256, ) class Bar(models.Model): bar_id = models.CharField( primary_key=True, max_length=256 ) name = models.CharField( max_length=256, ) foo = models.ForeignKey( Foo, models.SET_NULL, related_name='rel', ) When I try this: Bar.objects.create( bar_id = "A1", name = "John", foo = 5 ) I get the error that I would expect: Cannot assign "5": "Bar.foo" must be a "Foo" instance. But if I try: Bar.objects.create( bar_id = "A1", name = "John", foo = Foo.objects.get(foo_id=7) ) I get: int() argument must be a string, a bytes-like object or a number, not 'Foo' Really don't understand as I'm sure I've created records like this elsewhere. -
How to list objects of the same date?
I want to list all items in my template, but I want to list items under the same year. For example, under the 2021 title, model objects for that year should be listed. Year titles should come dynamically. How can I do it? views.py def press_list(request): press_contents = PressContent.objects.all().order_by('-date') context = { 'press_contents': press_contents } return render(request, "press_list.html", context) models.py class PressContent(models.Model): label = models.CharField(max_length=500) url = models.URLField(max_length=500) date = models.DateTimeField(blank=True, null=True) press_list.html {% for press in press_contents %} <div class="card" style="width: 18rem; margin:15px"> <div class="card-header"> {{ press.date.year }} </div> <ul class="list-group list-group-flush"> <li class="list-group-item"><a href="{{ press.url }}">{{ press.label }}</a></li> # Other objects from this year should come here. </ul> </div> {% endfor %} To be clear: 2021 obj 1 obj 2 2020 obj 3 obj 4 ... ... -
Nginx 403 while accessing static files in docker volumes
I am trying to serve static files in docker volumes for my Django project. Nginx is able to access the files(403) error. I tried to solve this in different ways like updating the file permission. Nginx I am installed in a normal way without a container and Django, Postgres database is running in a container Nginx configuration server { listen 80; server_name 139.59.73.115; location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } location /static { root /var/lib/docker/volumes/m3-mobiles_m3-mobiles-assets/_data/; } } -
how to send django website user input data to external python script
I am trying to create a webpage where users input two data and then I receive that data and pass that to an external python script I cannot enter the python script the Django since its very big <form action='generate' method='post' > {% csrf_token %} enter the current status:<input type="text" name="status"></br> enter the water_level:<input type="text" name="level"></br> <input type="submit" value="submit"> </form> ''' I am receiving the value entered by the user into views. generate function as follows ''' def generate(request): a=int(request.POST["status"]) b=int(request.POST["level"]) out=run(sys.executable,['C:\Users\siddhant\Desktop\internship\indicator\work\templates\water.py',"a","b"],shell=False,stdout=PIPE) print(out) I want to run the water.py file here only bypassing the input a and b from os import read from random import randint import sys from tkinter.constants import X from datetime import* import pandas as pd import numpy as np from pandas.core.base import DataError from time import time start_time = datetime.now() # do your work here x=sys.argv[1] current_level=sys.argv[2] I want to pass the received input a and b to x and current_level respectively