Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run asynchronous function synchronously in python
I am learning Django and I am stuck with this problem. So basically, I have written two run functions and the second run function uses the first's output as input. Now it seems that the run function runs asynchronously so before the first run function executes completely and produces its output the second run function starts executing and since it needs the first run function output as input it does not produce any output. So, I want the run function to run synchronously. Here is the code snippet run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac {final_tutorial}"], cwd="media/") for i in range(1000000000): continue run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {final_tutorial} -vcodec libx265 -crf 28 reduce_{final_tutorial}"], cwd="media/") In the above code I have used a for loop and it works but I don't think it's the correct way. Can someone please suggest me the correct way? Here is my views.py file. def video(request): if request.method == 'POST': uploaded_video_file = request.FILES["video"] video_file_name = uploaded_video_file.name fs = FileSystemStorage() video_name = fs.save(video_file_name, uploaded_video_file) run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name} -c:v copy -an {video_name}_audio_stripped.mp4"], cwd="media/") final_tutorial=video_name+"_spoken_tutorial.mp4" run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac … -
How to get data from a django model and show it into a bootstrap modal popup?
i'm new in django framework, in my app i have two model, BoardsList and BoardLink: class BoardsList(models.Model): master_code = models.CharField(max_length=6, primary_key=True) uc_code = models.CharField(max_length=20) description = models.CharField(max_length=200) customer_name = models.CharField(max_length=30) def __str__(self): return "MASTER_CODE = " + self.master_code class BoardLink(models.Model): boardsList = models.ForeignKey(BoardsList, on_delete=models.CASCADE) configuration_sheet_link = models.CharField(max_length=300) wiring_diagram_link = models.CharField(max_length=300) def __str__(self): return self.boardsList_id And the relative views are : class BoardsListView(generic.ListView): template_name = 'index.html' context_object_name = 'boards_list' paginate_by = 75 def get_queryset(self): query_filter = self.request.GET.get("find_master", None) if query_filter is not None: return BoardsList.objects.filter(Q(master_code__contains=query_filter) | Q(uc_code__contains=query_filter) | Q(customer_name__contains=query_filter)).order_by('customer_name') return BoardsList.objects.order_by('master_code') class BoardLinkView(generic.DetailView): template_name = 'index.html' context_object_name = 'board_link_list' paginate_by = 1 def get_queryset(self): query_filter = self.request.GET.get("find_master_link", None) if query_filter is not None: return BoardLink.objects.filter(Q(boardsList__exact=query_filter)) in my html page i correctly showed boardlist data into a table : <tbody> {% for board in boards_list %} <tr> <td>{{ board.master_code }}</td> <td>{{ board.uc_code }}</td> <td>{{ board.description }}</td> <td>{{ board.customer_name }}</td> <td> <form method="GET" action=""> <button type="button" class="btn" name="find_master_link" data-bs-toggle="modal" data-bs-target="#boardLinksModal"> <i class="fa-solid fa-file-lines"></i> </button> </form> </td> </tr> {% endfor %} </tbody> now my problem is how i can get BoardLink model data record on button click event and show it on bootstrap modal popup that i have already created and include it on … -
Run a separate task in django rest framework
I've to perform two tasks in an API request but I want to run the second task asynchronously in the background so the API doesn't have to wait for the second task and return the response after the completion of the first task, so how can I achieve it? @api_view(['POST']) def create_project(request): data = first_task() second_task(data) # want to run this function at background return Response("Created") # want to return this response after completion of first_task() -
'social' is not a registered namespace
Im trying to implement google authentication but I got the following error: django.urls.exceptions.NoReverseMatch: 'social' is not a registered namespace i have like this in my login.html: <a href="{% url 'social:begin' 'google-oauth2' %}"> Sign in with Google</a> I also added this in my setting.py SOCIAL_AUTH_URL_NAMESPACE = 'social' Does anyone know how to solve this? -
problems trying to migrate from django to postgrsql
when trying to migrate from django to postgresql I get this error: C:\Users\Al2Misael\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\makemigrations.py:121: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': warnings.warn( could you help me, please,I'm new working with databases and django,I'm trying to make a web site for our animal rescue club.thanks in advance -
Django create post with reverse relation foreign key
I have a Protein model that is linked to the Domain model through the proteins foreign key in the Domain model like below. class Protein(models.Model): protein_id = models.CharField(max_length=256, null=False, blank=False) sequence = models.CharField(max_length=256, null=True, blank=True) length = models.IntegerField(null=False, blank=False) taxonomy = models.ForeignKey(Organism, blank=True, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.protein_id class Domain(models.Model): domain_id = models.CharField(max_length=256, null=False, blank=False) description = models.CharField(max_length=256, null=False, blank=False) start = models.IntegerField(null=False, blank=False) stop = models.IntegerField(null=False, blank=False) proteins = models.ForeignKey(Protein, blank=True, null=True, related_name="domains", on_delete=models.DO_NOTHING) def __str__(self): return self.domain_id And I have a Protein serializer that displays the Queryset like so: domains = DomainSerializer(many=True) taxonomy = OrganismSerializer() class Meta: model = Protein fields = [ 'protein_id', 'sequence', 'taxonomy', 'length', 'domains', ] The problem comes when I have to create a new record of the Protein using the Protein serializer. I write a post API function to create a new record but it gives errors when attempting to create the foreign key fields. @api_view(['POST']) def protein(request): if request.method == 'POST': serializer = ProteinSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I added the following function to my Protein serializer to override the create function for the two foreign keys but it doesn't seem to work when attempting to … -
UnboundLocalError at / local variable 'email' referenced before assignment django error
I am getting local variable referenced before assignment django error. Here is views.py from django.shortcuts import render from verify_email import verify_email def valid_email_verifier(email): email_vrifier_task = verify_email(email) results = {} if email_vrifier_task == False: results['email_altert'] = 'Wrong Email' else: results['email_altert'] = 'This email is correct!' return results # Create your views here. def home_view(request): if request.method == "POST" and 'email' in request.POST: email = request.POST.get(email) results = valid_email_verifier(email) context = {'results':results} else: context = {} return render(request, 'home.html', context) my form on templates file <form action="" method="post"> {% csrf_token %} <input class="form-control m-3 w-50 mx-auto" type="text" name="email" id="email" placeholder="Enter email...."> <input class="btn btn-secondary btn-lg my-3" type="submit" value="submit"> </form> </div> {% if results %} Email Info {{results.email_altert}} {% endif %} Please, anyone, help me where I did wrong? Thanks is advance. -
How to declare in Django Models a class with an attribute pointing to the same class?
How can I declare the previous or next attributes pointing to the same class type ? I couln't find the answer in official documentation In the models.py below I have just written "scenes" for previous and next from pickle import TRUE from django.db import models from django.contrib.auth.models import User class scenes(models.Model): name = models.CharField('Event name', max_length=120) record_date = models.DateTimeField('Event date') manager = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True) previous = models.ForeignKey(scenes, blank=True, null=True, on_delete=models.SET_NULL) next = models.ForeignKey(scenes, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name -
unsupported operand type(s) 'Decimal128' and 'decimal.Decimal' | (django)
I started a project in Django and just switched the local SQLite Database to mongodb Now that I'm trying to test the functionality of the site, I'm getting misunderstood errors. for example when I want to view all my data regarding a particular course and I send all the data back to HTML I get an error: unsupported operand type(s) for /: 'Decimal128' and 'decimal.Decimal' i am using star-rating django so i also have this package in my html files see down how i load the rating obj. Terminal Errors: Traceback (most recent call last): File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/Users/a2019/Documents/GitHub/TEAM_15_ESTUDY/Estudy_Project/category/views.py", line 54, in get return render(request,"HomeWorks.html",{'course':course,'homeworks':homeworks}) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/Users/a2019/opt/miniconda3/envs/EstudyEnv/lib/python3.9/site-packages/django/template/base.py", line … -
why Django use int auto primary key instead of other fields?
I'm developing a rest API service that use DRF in back-end,my question is can I user username of user as PK instead of Django auto field default ID?why Django uses this method what are the benefits? -
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder
I am trying to display the image in html template in python Django project. passed list of object as downloadData <div class="col-sm-6"> {% for d in downloadData %} <div class="row content"> <div class="col-sm-3"> <!--<img src="{{ 'static/assets/images/about-us.jpg' }}" >--> <img src="{{ url_for('static', filename='assets/images/' + d.img1) }}" > </div> <div class="col-sm-9"> <h3>{{ d.title }} </h3> <p>{{ d.p1 }}</p> </div> </div> <br> {% endfor %} </div> Error : django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '('static', filename='assets/images/' + d.img1)' from 'url_for('static', filename='assets/images/' + d.img1)' Images present in XYZProject-> static-> assets-> images-> about-us.jpg Could anyone point out the what I am doing wrong? Any link or pointer would be helpful -
ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 when dockerize a django app
Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. lib/zoneinfo_module.c: In function ‘zoneinfo_fromutc’: lib/zoneinfo_module.c:600:19: error: ‘_PyLong_One’ undeclared (first use in this function); did you mean ‘_PyLong_New’? 600 | one = _PyLong_One; | ^~~~~~~~~~~ | _PyLong_New lib/zoneinfo_module.c:600:19: note: each undeclared identifier is reported only once for each function it appears in error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 please need help to solve this and why this error happened, I have no idea. Thanks -
how to run django project with gunicorn
I have uploaded my Django app on the RHEL7 server it's running with help of gunicorn but not with full width so how do I customize it to use with full width. gunicorn_config.py command='/home/tarun/env/bin/gunicorn' pythonpath='/home/tarun/' bind='10.88.32.40:8000' workers =11 to run this project i use this command gunicorn -c conf/gunicorn_config.py ecom.wsgi -
How do I change the text color of a default UserCreationForm in Django?
I'm working on a simple website using django and bootstrap. I've used the UserCreationForm class to make a standards registration page. But I'd like to make the texts a little darker so it's more legible and has a good contrast from the background image and mask. What'd be the best solution? View module def register(request): #if the request method is a 'get' #Yes initial data if request.method != 'POST': form = UserCreationForm() #no initial data #f the request method is a 'post' else: form = UserCreationForm(data=request.POST) if form.is_valid(): new_user=form.save() authenticated_user = authenticate(username=new_user.username, password=request.POST['password1']) login(request, aunthenticated_user) return HttpResponseRedirect(reverse('my_websites:home')) context = {'form': form} return render(request, 'users/register.html', context) bootstrap {% extends "pages/base.html" %} {% load bootstrap5 %} {% block header %} <div="container my-5"> <div class="bg-image position-relative rounded" style="background:url('https://wallpaperaccess.com/full/1708426.jpg') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; height: 100vh;"> <div class="mask position-absolute rounded p-4 top-0 end-0 bottom-0 start-0" style="background-color: rgba(251, 251, 251, 0.8);"> <h2 class="text-center display-6"> Register </h2> <form method="post" action="{% url 'users:register' %}" class="form text-dark" style="max-width: 400px; margin:0 auto;"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-dark">Register </button> {% endbuttons %} <input type="hidden" name="next" value="{% url 'my_websites:home' %}" /> </form> </div> </div> </div> … -
How can i omit a url so i reach the url i want
hi i have a Form an the action method is 'Home_Search' i want to reach the Home_Search view but when ever i Post something the url will be like this http://127.0.0.1:8000/home/Home_Search and Page not found error will be raised , is there any method so i can exclude /home from the url?Only for this Form... my url.Py : path("home/", views.home, name="home"), path("Home_Search/", views.Home_Search, name="Home_Search"), and my Form is : <form action="Home_Search" method="post" role="form"> -
Function Based View to Class Based View
How would I convert my Function Based View into Class Based View. urls.py urlpatterns = [ path('', views.SlideShowView, name="slideshow"), ] models.py class Carousel(models.Model): title = models.CharField(max_length=255, blank=True) description = models.TextField(max_length=255, blank=True) image = models.ImageField(upload_to="showcase/%y/%m/%d/", blank=True) def __str__(self): return self.title views.py def SlideShowView(request): carousel = Carousel.objects.all() context = { 'carousel' : carousel, } return render(request, "showcase.html", context) -
Forbidden (CSRF cookie not set.) Django
I'm trying to do an endpoint API. And for that, i'm using django. My url in urls.py is : path('tutorials/', tutorial_list_test.as_view()), and my views.py is like class tutorial_list_test(GuestOnlyView, FormView): print("test"); @api_view(['GET', 'POST', 'DELETE']) def tutorial_list(self): request = self.request; if request.method == 'POST': alldata=request.POST username = alldata.get("username", "0") print("POST name: " + username) return Response('The tutorial does not exist', status=status.HTTP_404_NOT_FOUND) But when i'm doing a request, i have everytime the same error "Forbidden (CSRF cookie not set.): /accounts/tutorials/" So I did some research, and I could see several proposed solutions. The first was to use csrf_exempt but it's not working for me: path('tutorials/', csrf_exempt(tutorial_list_test.as_view())), And it's the same for all the methods I used. Even if I remove this line from my settings.py, nothing changes # django.middleware.csrf.CsrfViewMiddleware', To test, I use Postman, but even using my angular front end, it does the same. const formData = new FormData() formData.append('username', this.username_signup); this.http.post('http://127.0.0.1:8000/accounts/tutorials/', formData) .map((data: Response) => { if (data !== null) { console.log(JSON.stringify(data)); }; }).subscribe(response => console.log(response)) I would like to know if you have any idea how I can do this. Because I need to be able to access my Models, so not using a class and directly making a def … -
How to Update Django Model Relationship only with Foreign Key Value
I'm looking for a way to update a relationship on a model in Django by only passing the foreign key value and not the model being referenced in the relationship. I understand that Django wants me to do this publisher = Publisher.objects.get(id=2) book = Book.objects.get(id=1) book.update(publisher=publisher) But I'm looking to just update the publisher using the publishers PK so something more along the lines of this. book = Book.objects.get(id=1) book.update(publisher=2) I have a significant amount of data that needs to get updated and I don't necessarily have a reference to what the model is for each field that needs to get updated on the "Book". -
Relation does not exist behavior in django + postgresql
After looking at all the other answers here I still can't figure this out. In my project I have two apps, the first app users manages users and the second one signals manages the contents to be displayed. Right now I am just trying to make the second app signals work but even the simplest models will throw errors in admin. The error i get: ProgrammingError at /admin/signals/signal/ relation "signals_signal" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "signals_signal" This is what I have in models.py: class Asset(models.Model): name = models.CharField(max_length=30) ticker = models.CharField(max_length=30) def __str__(self): return "%s, %s" % (self.name, self.ticker) class Signal(models.Model): type = models.CharField(max_length=100) date = models.DateField() asset = models.ForeignKey(Asset, on_delete=models.CASCADE) def __str__(self): return self.type In settings.py; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': BASE_DIR / 'db.sqlite3', 'NAME': 'users', 'USER': 'admin', 'PASSWORD': 'password', 'HOST': 'localhost' } } And the admin.py for signals is: from django.contrib import admin from .models import Asset, Signal # Register your models here. class AssetAdmin(admin.ModelAdmin): pass admin.site.register(Asset, AssetAdmin) class SignalAdmin(admin.ModelAdmin): pass admin.site.register(Signal, SignalAdmin) I have tried basically everything: deleting migrations, doing startapp from scratch etc. I have never used postgres before. Thank you for any assistance. -
ModuleNotFoundError: No module named 'django.core'
I want to create django project so I've configured virtualenv ,and I installed django pipenv install django==4.0.1 when I create app using this command python3 manage.py startapp Accounts I got this error. (env) zakaria@ZAKARIA:/mnt/c/Users/ZAKARIA/Desktop/project$ python manage.py startapp Accounts Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django.core' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? can any one help to solve this problem ? -
When I try to build docker in locally - Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects?
Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [41 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-310 creating build/lib.linux-x86_64-cpython-310/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-cpython-310/backports creating build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/__init__.pyi -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.linux-x86_64-cpython-310 creating build/temp.linux-x86_64-cpython-310/lib gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/usr/local/include/python3.10 -c lib/zoneinfo_module.c -o build/temp.linux-x86_64-cpython-310/lib/zoneinfo_module.o -std=c99 lib/zoneinfo_module.c: In function ‘zoneinfo_fromutc’: lib/zoneinfo_module.c:600:19: error: ‘_PyLong_One’ undeclared (first use in this function); did you mean ‘_PyLong_New’? 600 | one = _PyLong_One; | ^~~~~~~~~~~ | _PyLong_New lib/zoneinfo_module.c:600:19: note: each undeclared identifier is … -
Junction table referencing non existent entity
I have the following models in django class WorkSession(models.Model): pass class Invoice(models.Model): work_sessions = models.ManyToManyField(WorkSession, blank=True) what I noticed is that when i do the following: invoice = Invoice() session = WorkSession(a=a, b=b) invoiceo.work_sessions.set([session]) The invoice_worksession junction table gets populated with a relation, even though I haven't saved invoice yet. Meaning that the invoices table, there's no row, but in the junction table, there's a row that references an invoice that doesn't exist yet. Is this normal ? Because this is causing an integrity error on fixture teardown since the invoice doesn't exist and yet, there's a refrence to an invoice id in the junction table -
Why javascrpt does not select the button?
I am creating with javascript that when I select the like button it prints Hi. I don't understand why when inspecting it is not selecting the button. I don't understand what I'm doing wrong. Can it be that I do not get the javascript url? index.hmtl <script src="{% static 'network/index.js' %}"></script> <form method="post">{%csrf_token%} <button onclick="darLike()">Like</button> <a id="resultado"></a> <svg xmlns="http://www.w3.org/2000/svg" width="16 " height="16 " fill="currentColor " class="bi bi-heart " viewBox="0 0 16 16 "> <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z "/> </svg> </form> index.js document.addEventListener('DOMContentLoaded', function() { document.addEventListener('click', () => function darLike() { const contenido = document.querySelector('#resultado') fetch(`like/${post.id}`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken } }) // Put response into json form .then(response => response.json()) .then(data => { console.log(data); contenido.innerHTML = "Hi" }) // Catch any errors and log them to the console .catch(error => { console.log('Error:', error); }); }); // Prevent default submission return false; }) -
How to dynamically submit form input values with OnChange event using JQuery in django
I'm currently developing a simple true odd finder calculator using python, django and jquery. I need to have form input submit actions executed by jQuery as the user types in the input values. The goal is to get rid of submit buttons in the frontend html. As of nowadays calculator based web applications don't require submit buttons. The functionality behavior should look like here. I did a research and found out that i need to use JQuery. After implementing the functionality in my app, am able to type the first form input element, however upon clicking the second form input so as to start typing, my application crashes with server error 500, if i go back then type the second form input, it updates output. How can i implement form input onChange using jquery to match the referenced functionality above. My template and JQuery code {% extends "base.html" %} {% block title %}Two Way True Odd Finder{% endblock %} {% block content %} <script type="text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('.form-control').change(function () { $('#myform').submit(); }); }); </script> <div class="container m-5"> <a href="{% url 'dashboard' %}" class="btn btn-primary">Dashboard Home</a> <a href="{% url 'index' %}" class="btn btn-primary">3 Way True … -
How to add secondary y axe in a graph object with Plotly?
I'm new with Plotly and I would like to add a secondary y axis to a Line graph in my Django view, how can I do that ? class AccountDetailView(SingleTableMixin, generic.DetailView): data_assets_hist = [] data_assets_hist.append(go.Line(x=x, y=get_test(), name='Test')) data_assets_hist.append(go.Line(x=x, y=get_bench(), name='Benchmark')) layout_weights = { 'yaxis_title': 'Title y axis', 'height': 520, 'width': 1100 } plot_div_1 = plot({'data': data_assets_hist, 'layout': layout_weights}, output_type='div',) context['plot_div_1'] = plot_div_1 return context From what I understand of the documentation the recommended way to add a secondary y axis is to call update_yaxes() but in my case it's not possible because I don't create a figure with make_subplots. I tried to insert the secondary_y parameter in several places but it throws an error. Invalid property specified for object of type plotly.graph_objs.Layout: 'secondary'