Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selective loading of values to populate the ModelViewSet form / Phyton Django RestFramework
I admit I'm new to the Python world. I would like to add some loading moments while I compile the form of the Rest Framework ModelViewSet, in order to make the insertion of data in the forms more agile. below also 2 screens of the form generated by the Framework and a screen of the models, I think I'm working well, I made them in ForeingKeys Is it possible to make such customizations in the Rest Framework views? Rest Framework View Screenshot Django Models -
How extract array values and save to variable? Python
I dont understand how this line of code works in the function below. Mainly what I am asking is how is this line capturing any data? What is this method of capturing data called? Problem line below? self.cart[product_id]['quantity'] = quantity Full function below? def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() -
(python) How do i split a csv with /n if the fields have strings with /n inside
I'm having trouble splitting a csv because some of the fields have a "\n" inside them i'm using: file_data = csv_file.read().decode("utf-8") csv_data = file_data.split("\n") but the fields look something like 'string 1','string 2', 'string 3' 'string 4', i would like csv_data[0] to be strings 1 and 2, csv_data[1] to be string 3, and csv_data[2] to be string 4 the way i'm currently using, i get csv_data[0] correctly, but string 3 is split in two indexes since it has a /n inside it's text... -
Related name returning post.commentpost.none
Can anyone explain me, why i get Post.CommentPost.None? How to correct connect CommentPost with Posty in query? I need get {{posty.comments.user}} my result is Post.CommentPost.None Here something about my models and functions. class Posty(models.Model): title = models.CharField(max_length=250, blank=False, null=False, unique=True) sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True) content = models.TextField(max_length=250, blank=False, null=False) image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])]) author = models.ForeignKey(Profil, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(auto_now_add=True) T_or_F = models.BooleanField(default=False) likes = models.ManyToManyField(Profil, related_name='liked') unlikes = models.ManyToManyField(Profil, related_name='unlikes') created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE) test_wyswietlenia = models.IntegerField(default=0, null=True, blank=True) class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) VIEWS tag = request.GET.get('tag') if tag == None: my_tag = Posty.objects.prefetch_related('comments') my_view = Posty.objects.prefetch_related('my_wyswietlenia') else: my_tag = Posty.objects.filter(created_tags__tag=tag) my_view = Posty.objects.prefetch_related('my_wyswietlenia') TEMPLATES {% for post in my_tag %} {% if post.comments.last.user == None %} <span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">Brak komentarza</a></span><br/> <span class="forum_tag_author">Stworzony przez » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">{{post.author}} </a> </span><hr/> {% else %} <span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">{{post.comments.last.content1}}</a></span><br/> <span class="forum_tag_author">Odpowiadający » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">Dodany przez: {{post.comments.last.user}} </a> </span><hr/> {% endif %} {% endfor %} And this {{post.comments}} … -
Why do I get NameError: name '_' is not defined when setting custom templates for djangocms-video?
I am trying to get custom templates working for djangocms-video. So far there is a fresh djangocms project set up with some bootstrap and running fine. According to the readme we would need to specify this in the settings.py to make a custom template available (in this case a template named "feature"): DJANGOCMS_VIDEO_TEMPLATES = [ ('feature', _('Featured Version')), ] After setting this and running manage.py this error comes up: ('feature', _('Featured Version')), NameError: name '_' is not defined According to other threads we would need to import gettext like this in the modely.py: from django.utils.translation import gettext as _ or like this: django.utils.translation import ugettext_lazy as _ No luck so far. What am I missing here? Here is some info on the environment: python --version Python 3.9.2 pip list Package Version -------------------------- ----------- asgiref 3.4.1 cssselect2 0.4.1 dj-database-url 0.5.0 Django 3.1.14 django-classy-tags 2.0.0 django-cms 3.8.0 django-filer 2.1.2 django-formtools 2.3 django-js-asset 1.2.2 django-mptt 0.13.4 django-polymorphic 3.0.0 django-sekizai 2.0.0 django-treebeard 4.5.1 djangocms-admin-style 2.0.2 djangocms-attributes-field 2.0.0 djangocms-bootstrap4 2.0.0 djangocms-file 3.0.0 djangocms-googlemap 2.0.0 djangocms-icon 2.0.0 djangocms-installer 2.0.0 djangocms-link 3.0.0 djangocms-picture 3.0.0 djangocms-style 3.0.0 djangocms-text-ckeditor 4.0.0 djangocms-video 3.0.0 easy-thumbnails 2.8 html5lib 1.1 lxml 4.7.1 Pillow 9.0.0 pip 21.3.1 pkg_resources 0.0.0 pytz 2021.3 pytz-deprecation-shim 0.1.0.post0 reportlab … -
How to use work week in DateField in Django admin
In my model, I say: class Foo(models.Model): start = models.DateField(help_text='Start Date') In the django admin, when adding a new Foo object, I see a text field with a calendar attached allowing me to select the date. I want to customize this a little bit so that I can either select the date from the calendar or enter something like WW12'22 in the textfield and during Save, this gets converted into a DateField. I am not sure how to do implement this in the django admin. Any ideas would be helpful. -
How to call a js folder inside Django static folder from an html file inside its own folder
I have a question using django 3.2.10. I can't download my js file which is inside js folder, also inside static folder. Additionally, I have a folder called views where there are my html files, they are organized by webapp name. I am calling a js file (perbd.js) from perbd.html. This is the structure of my project. This is the line in my perbd.html: <script type="text/javascript" src="{% static 'js/perbd.js '%}" ></script> And I have these lines in my Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), ) The point is that It doesn't work my js. I have the snapshot from the firework inspector: The files which have %20 in the end, they are not working. I don't know what does it mean? Also I attach the image from the firefox console: I'm thinking that it could be the folders organization because perbd.html is inside persona folder. I really appreciate all your help. Thanks in advance. -
Wagtail & Django issues
I just updated from Wagtail 2.11.2 to 2.15.1 and Django 2.2.6 to 3.0. Everything works locally but when I deploy and visit the cms I get an internal server error. The error in django_errors.log is: Internal Server Error: /cms/ Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/test/utils.py", line 96, in instrumented_test_render return self.nodelist.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/test/utils.py", line 96, in instrumented_test_render return self.nodelist.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/test/utils.py", line 96, in instrumented_test_render return self.nodelist.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/loader_tags.py", … -
Django "[object] instance with id X does not exist" error when creating/updating object foreign key in admin, using sites framework
I have a Django application using the sites framework. I have a Category model and a Topic model. The Topic model has a "category" attribute pointing to a specific Category object. Both of these models have "site" attributes linking them to specific sites in the Django application. All of these websites are hosted on the same server. What I'm noticing is that, when I create/update an object (Topic) in the admin - and set the topic's foreign key field (category) to a category that is not on the site configured in the SITE_ID setting - I get this error message: category instance with id X does not exist When I change the SITE_ID in settings.py, I can now set the topic's category to a category on that site, but not on any other sites. Here's a chart to help you visualize this: flow chart There are two relevant models here, Category and Topic: class Category(models.Model): name = models.CharField(max_length=128) slug = models.SlugField() description = RichTextUploadingField( blank=True, default='', verbose_name='Category Description', help_text='''Category description to be displayed on category page goes here''' ) site = models.ForeignKey(Site, on_delete=models.CASCADE) on_site = CurrentSiteManager() objects = models.Manager() class Meta: verbose_name_plural = 'categories' ordering = ['name'] class Topic(models.Model): site … -
Django database relation
I am working on a forum using django, I have a problem accessing user fullname and bio, from a model class I have. I have no problem accessing the user.username or user.email, but not from the Author class.. This is from the models.py in the forum app User = get_user_model() class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=40, blank=True) slug = slug = models.SlugField(max_length=400, unique=True, blank=True) bio = HTMLField() points = models.IntegerField(default=0) profile_pic = ResizedImageField(size=[50, 80], quality=100, upload_to="authors", default=None, null=True, blank=True) def __str__(self): return self.fullname My form is in the user app, where i have a profile update site, and the form is like this from forums.models import Author class UpdateForm(forms.ModelForm): class Meta: model = Author fields = ('fullname', 'bio', 'profile_pic') Then here is some of the update site, however nothing let me get access to the bio or fullname, I've tried so many combos. and I am lost here.. {% block content %} <section class="section" id="about"> <!-- Title --> <div class="section-heading"> <h3 class="title is-2">Hey {{ user.username }}</h3> <div class="container"> <p>{{ user.bio }}bio comes here</p> </div> </div> If there is some relation i am missing please help -
Django, user customization of current site
Is there any way I can create in Django site that the user can customize for his purpose, by for e.g. adding as many charts as he likes to? -
Django Debug toolbar isn't showing up in the browser
I expected to see Django Debug toolbar on the right hand side of my browser. Instead on my browser I have a box with "Enter your search term" in it. I have looked over the installation instructions to see if I've missed a step and I haven't. Also, I imported the debug_toolbar on the urls.py page and it looks to be a bit gray. [enter image description here] 1Below is some of my code from the settings.py file and the picture is from my urls.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground', 'debug_toolbar' ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', ] INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] ROOT_URLCONF = 'storefront.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] -
Django Pagination show no data after clicking on next button
I have a pagination in Django application. when I load the page the data display is fine on the first page but when I click on second button of paginator no data is shown on next page. Following is my code: viwes.py def get_queryset(self, **kwargs): # get query params query = self.request.GET.get("q", "") page = self.request.GET.get("page", "1") size = self.request.GET.get("rows", "15") cname = self.request.GET.getlist("cname", []) tags = self.request.GET.getlist("tag", []) filter_param = self.request.GET.getlist("filter_param", []) # get size and set to default 15 if its not digit if size.isdigit(): size = int(size) else: size = 15 # get response from elastic search response = self.get_archives(query, page, size, cname, tags, filter_param) response = list(iter(response)) for res in response: if 'statement' in res: ref = self.get_reference(res['statement'], response) res['references'] = ref p = Paginator(response, 2) pages = p.get_page(page) return pages response list is passed to frontend, response has data when sending it to first page but when request is send again after clicking on second button response list is passed empty to frontend. claims.html <div class="row" style="padding-top: 30px;"> {%if archives.paginator.count %} <div class="col" style="float: right;"> <nav aria-label="Page navigation"> <ul class="pagination"> {% if archives.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1&q={{query}}&size={{size}}&cname={{cname}}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">begin</span> </a> … -
psycopg2.errors.DuplicateTable: relation "airgoLocator_translationexception" already exists
I am experiencing the error, psycopg2.errors.DuplicateTable: relation "airgoLocator_translationexception" already exists I have returned the migrations back, to a point where I am sure that everything worked python manage.py migrate app 0058 python manage.py migrate app python manage.py makemigrations I have also tried to do python manage.py migrate --fake app python manage.py migrate python manage.py makemigrations But I have not been lucky. I have the backend in a gitlab image that I lift from a docker, therefore the backend restarts all the time with this error. Therefore I have to make these changes in the migrations and generate a new image, every time I try to test a solution. The database is a postgres that is in another container. If someone can give me support in this regard, I would be more than grateful. Thank you -
django/bootstrap5 signup form unknown checkbox
I'm creating an app with Django and I created a sign up form with Django/Bootstrap5. It's all good. The only problem is a checkbox at the end of the form that I didn't expect. I'll try to add a screenshot to this post to show it to you. I would like your opinion about it. My guess is that probably with this checkbox the user would accept T&C, but I have no T&C for this registration to propose. Is there any way to remove this checkbox from here? Sorry but I could not find anything in the documentation. The code is very simple: {% extends "learning_steps/base.html" %} {% load bootstrap5 %} {% block page_header %} <h2 class="mt-5">Create your new account.</h2> {% endblock page_header %} {% block content %} <div class="col-7"> <form method="post" action="{% url 'users:register' %}" class="form form-red"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn-red btn-login-size">Sign up!<button> {% endbuttons %} <input type="hidden" name="next" value="{% url 'learning_steps:index' %}" /> </form> </div> {% endblock content %} And this is the screenshot, I hope it's useful. Thank you everybody! -
Getting 403 Forbidden error in django applicaion if user is logged-in in my website. I am not getting this error for anonymous user
I am new to django and ajax both. I am getting 403 error only if I am logged-in user. If am logged out same is working fine. Here is my ajax call: $("div#mainCont").on("click","#detail_icon", function(){ var _tickName = $(this).parent().attr('id'); var csrf = $("input[name=csrfmiddlewaretoken]").val(); $.ajax({ method: "POST", url: 'performance', data:JSON.stringify({ csrfmiddlewaretoken: csrf, ticker: _tickName }), success: function (data) { console.log(data) } }); This is my view: class PerformanceView(APIView): def get(self,request, format=None): queryset = Advice.objects.all() serializer = AdviceSerializers(queryset,many=True) return Response(serializer.data) def post(self, request): data=json.loads(request.body) print(data) queryset = Stocks.objects.filter(ticker=data["ticker"]) serializer = PerformanceSerializers(queryset,many=True) return Response(serializer.data) Thanks in advance -
Image is not showing up on my website (django)
I'am new to django. I wanted to upload an image but it doesn't show up on website. Instead it shows broken image icon. I tried to use load static block but it still doesn't work. My html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Website</title> </head> <body> <h1>Hello</h1> {% load static %} <img src="{% static 'webdev/static/webdev/images/images.jpg' %}"> </body> urls.py file: from django.contrib import admin from django.urls import path from homepage import views urlpatterns = [ path('', views.home_page, name='home'), path('admin/', admin.site.urls), ] views.py file: from django.shortcuts import render from django.http import HttpResponse def home_page(request, *args, **kwargs): return render(request, 'home.html', {}) -
Trying to display webcam footage on webpage from OpenCV (Django) while using docker
I am trying to create a facial recognition attendance system - My project framework is DJango and I have deployed it on docker, however I am running into issues trying to access the webcam through docker. This is my code: views.py: class mycamera(object): def __init__(self): self.frames = cv2.VideoCapture(0) def __del__(self): self.frames.release() def get_jpg_frame(self): is_captured, frame = self.frames.read() retval, jframe = cv2.imencode('.jpg', frame) return jframe.tobytes() def livefeed(): camera_object = mycamera() while True: jframe_bytes = camera_object.get_jpg_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jframe_bytes + b'\r\n\r\n') @condition(etag_func=None) def display_livefeed(self): return StreamingHttpResponse( livefeed(), content_type='multipart/x-mixed-replace; boundary=frame' ) urls.py: from users import views as user_views path('vidstream/', user_views.display_livefeed, name='vidStream') Error code when access 0.0.0.0:8000/vidstream/: web_1 | [04/Jan/2022 17:47:16] "GET /vidstream/ HTTP/1.1" 500 59 web_1 | [ WARN:0@3.508] global /io/opencv/modules/videoio/src/cap_v4l.cpp (889) open VIDEOIO(V4L2:/dev/video0): can't open camera by index web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/wsgiref/handlers.py", line 138, in run web_1 | self.finish_response() web_1 | File "/usr/local/lib/python3.10/wsgiref/handlers.py", line 183, in finish_response web_1 | for data in self.result: web_1 | File "/code/users/views.py", line 81, in livefeed web_1 | jframe_bytes = camera_object.get_jpg_frame() web_1 | File "/code/users/views.py", line 75, in get_jpg_frame web_1 | retval, jframe = cv2.imencode('.jpg', frame) web_1 | cv2.error: OpenCV(4.5.5) /io/opencv/modules/imgcodecs/src/loadsave.cpp:976: error: (-215:Assertion failed) !image.empty() in function … -
Which subscription events to monitor for and which actions to take?
I have a subscription product that offers users monthly and annual subscriptions without free trials. All the docs I've seen kind of assume that I should know what types of actions to take when a new user subscribes to my service. The Stripe docs on provision and monitor say the minimum events to monitor are: checkout.session.completed invoice.paid invoice.payment_failed But then what do after monitoring for these events? In the dj-stripe docs on webhooks there are some clues as to what I should be doing including: Notifying the customer via email "Invalidating a cache" "Fire off a celery task" Is there anything else I should consider doing? And how do I know when to do what? Sorry if these are newb questions but this all just seems really subjective and I am just grasping for some guidance. Of course with dj-stripe I will be adding a lot of info to the database and this is all handled automatically. And of know that I can and should email the user when an invoice is paid or payment failed. But what about checkout.session.completed? Why is this a minimum event to monitor for? When a checkout session is completed Stripe redirects the user back … -
How do I integrate Neo4j DB with Django application?
I've tried this "https://neomodel.readthedocs.io/en/latest/getting_started.html#connecting" but Didn't mention which code is need to be placed in which file. I installed neomodel package but it's still not recognizing neomodel. Also, I've tried Py2neo and neo4django. But it's not working in any way. Can anyone please suggest me something helpful for doing it? Thanks in advance. -
django-simple-menu multiple active at a time
I've select submenu of an item. But it selects top most parents and selects anothers what I've selected. Just like below. Though I've selected purchase submenu but it shows 1st one and selected one -
In Django, how do I obtain ONLY the file path from a FileField in a form without loading the file into memory?
For a Django form, I like and need the FileField feature where it allows the user to navigate to a file locally and select it, but on the backend I only want to retain the absolute file path WITHOUT loading the file into memory first. I'm dealing with files in the 300 million+ records and do not want to do any data storage in memory, only obtain its path on the system. I tried FilePathField but it mandates pre-specifying a home directory for the files, which would not allow for the navigation feature of FileField. -
Django FOREIGN KEY constraint failed on OneToOneField
So I've created 2 classes of models. One has an OneToOneField and this class was referenced by the other using the ForeignKey field. It returns an error whenever I save it even in Django admin. Model classes class First(models.Model): sample_field = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True) class Second(models.Model): another_field = models.ForeignKey(First, on_delete=models.CASCADE, blank=True, null=True, related_name='sample_related_name') Error Message IntegrityError at /admin/management/group/add/ FOREIGN KEY constraint failed Thank you! -
JS appending element to parent not working
I am trying to add the new row to my table, but the I am unable to append a new row to the table. If i console log the elements individually I get the expect response can anyone help me find a solution to the problem, below is the code Html <tbody id="tableProduct"> {%for product in products %} <tr> <td scope="row" class="rowCounter"></td> <td>{{product.nameP}}</td> <td>{{product.brand}}</td> <td>{{product.price}}</td> </tr> {%endfor%} </tbody> JS class UI { //Adding the new Product to the display static addProduct(product){ const table = document.querySelector('#tableProduct'); const newRow = document.createElement('tr'); newRow.innerHtml = ` <td scope="row" class="rowCounter"></td> <td>Camera</td> <td>Sony</td> <td>10000</td> `; console.log(table.firstElementChild); //Placing the new row into the table //table.insertBefore(newRow, table.firstElementChild); //table.insertBefore(newRow, table.firstChild); table.appendChild(newRow); console.log(newRow.innerHtml) } } document.querySelector('#productForm').addEventListener('submit', (event)=>{ event.preventDefault(); UI.addProduct(newProduct); }) -
Change Celery task to run on-demand with clicking a button
I have a celery task that runs periodically and fetches some data for all companies that use a certain accounting service. I now need to make that task run on-demand with a click of a button, and fetch only the current company's data. Modified celery task: @APP.task def import_data_for_company(company_id): for integration in settings.INTEGRATIONS: if integration["owner"]["company_id"] == company_id: print("omlette du fromage") Current button in Django template {% for integration in settings.INTEGRATIONS %} {% if company.company_id == integration.owner.company_id %} <div class="button"> <a class="btn" href="#">Import Data</a> </div> {% endif %} {% endfor %} I need to trigger that task from the Django template and pass a company ID as an argument while doing it. But according to this comment, I cannot pass arguments from the Django template. Writing a custom template tag/filter seems not to help here. What are my options for calling that function via this button? Have to note, that I'm very green at this still.