Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Error When Click Button for send data. Please Helping me to solve problem. Error When Click Button for send data. Please Helping me to solve problem. Error When Click Button for send data. Please Helping me to solve problem. detail.html td> <!-- <a href="{% url 'Detail_pem' %}"><button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </a> --> <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> --> <script> var id_order = document.getElementsByClassName('id_order') for (i = 0; i < id_order.length; i++) { id_order[i].addEventListener('click', function(){ var orid = this.dataset.product var ornm = this.dataset.act console.log('orid :', orid) console.log('ornm :', ornm) codata(orid, ornm) }) } function codata(orid, ornm){ console.log('orid :', orid, 'ornm :', ornm) const url = "Detail" fetch(url, { method :'POST', headers : { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'orid':orid, 'ornm':ornm}), }) .then((response) =>{ return response.json(); }) .then((data) => { console.log('Success:', data); }) } </script> {% endblock %} view.py def Detail(request): data = json.loads(request.body.decode("utf-8")) orid = data['orid'] ornm = data['ornm'] print('id :', orid,'nama :', ornm) context = {'orid ':orid , 'ornm':ornm} return render(request, 'store/detail.html', context ) -
Heroku Django Postgre
So, I was building a Django app, I created an intro field for a post formular, I did that in my models.py file: class Post(models.Model): title = models.CharField(max_length=100) intro = models.CharField(max_length=1024) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('donut-post-detail', kwargs={'pk': self.pk}) I renamed 'description' into 'intro' so, when I did the makemigrations command it maked me a file named: 0002_rename_description_post_intro.py I hosted it into heroku, commited changes and migrated it when this happened: ~ $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, users Running migrations: Applying blog.0002_rename_description_post_intro...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "description" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, … -
Custom rest_framework_simplejwt authentication class for reading HTTPonly cookies ignores permission_classes = (permissions.AllowAny,)
I have defined a custom authentication class that extends the default rest_framework_simplejwt.authentication.JWTAuthentication as follows: myaccount.authenticate.py def authenticate(self, request): header = self.get_header(request) if header is None: # If header is None, get token from cookie raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_ACCESS_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) return self.get_user(validated_token), validated_token I then added the following to settings.py 'DEFAULT_PERMISSION_CLASSES':[ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES':[ 'myaccount.authenticate.CustomJWTAuthentication' ] } views.py class Login(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): pass When I make a call to the above view despite having permissions set to AllowAny, I get the following response. { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } What could I have missed? Thank you. -
Python list overwritten each time the previous items
The objective of my application is to create a copy of documents and insert them into the database for each annotator, for example, let's say the master user has 3 documents and two annotators, let's say the first annotator has the email testmail1@mail.com and the second one has the email testmail2@mail.com, finally, I need to insert in the database 3 documents for testmail1@mail.com and 3 other documents for testmail2@mail.com. So to do this, I created first a list containing the copy of documents, and I didn’t assign the annotator created_documents_in_iaa = [] created_documents_in_iaa += [DocumentIAATask( name=document.name, spans=document.spans, entity=document.entity, original_document=document, IAA_Task=iaa_task) for document in all_documents_in_iaa.iterator(chunk_size=1)] And after that, I added an annotator to each document, and I append each modified created_documents_in_iaa list to the tsks_list: tasks_list = [] for user in users_instance_list: try: for i in range(len(created_documents_in_iaa)): created_documents_in_iaa[i].annotator = user tasks_list.append(created_documents_in_iaa) except Exception as e: print(e) Finally, I created a copy of documents in the PostgreSQL database: for task in tasks_list: DocumentIAATask.objects.bulk_create(task) However, in the result, I found 6 documents inside the table of the first annotator, and nothing for the other one, after I debugged the code, I found that tasks_list overwritten each time the list, that's means when I … -
Best approach to implement server-side caching on a Django GraphQL API?
I have an Angular frontend that uses Apollo Graphql client to interface with a Django Graphql backend (using graphene). It all works well, but the API is very slow, especially when there are concurrent users. I am trying a few things to speed up the API server. One of the things that I am seriously considering is to use server-side caching. I'm aware that there are some caching solutions that exist for Django out of the box, but these seem to be for caching the views. Is it possible to use these methods to cache Graphql API requests? What is the most effective caching solution for caching the responses to graphql queries in Django? I'm posting some of my project's code here so that you get a sense of how my API works. This is a sample of the Query class containing the various graphql endpints that serve data when queries are received from the client. And I suspect this is where we'll need most of the optimization and caching applied:- class Query(ObjectType): # Public Queries user_by_username = graphene.Field(PublicUserType, username=graphene.String()) public_users = graphene.Field( PublicUsers, searchField=graphene.String(), membership_status_not=graphene.List(graphene.String), membership_status_is=graphene.List(graphene.String), roles=graphene.List(graphene.String), limit=graphene.Int(), offset=graphene.Int()) public_institution = graphene.Field(PublicInstitutionType, code=graphene.String()) public_institutions = graphene.Field(PublicInstitutions, searchField=graphene.String(), limit = … -
I can't run websocket django in server nginx
nginx map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name www.abo3aly.com abo3aly.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/www/abo3aly.com; } location / { include proxy_params; proxy_pass http://unix:/run/abo3aly.sock; } location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8002; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } *The error* _____ ERROR [Failure instance: Traceback: <class 'TypeError'>: __call__() got an unexpected keyword argument 'scope' /root/django/nayf/env/lib/python3.8/site-packages/autobahn/websocket/protocol.py:2878:processHandshake /root/django/nayf/env/lib/python3.8/site-packages/txaio/tx.py:369:as_future /root/django/nayf/env/lib/python3.8/site-packages/twisted/internet/defer.py:190:maybeDeferred /root/django/nayf/env/lib/python3.8/site-packages/daphne/ws_protocol.py:72:onConnect --- --- /root/django/nayf/env/lib/python3.8/site-packages/twisted/internet/defer.py:190:maybeDeferred /root/django/nayf/env/lib/python3.8/site-packages/daphne/server.py:200:create_application] -
Django Github CI cannot connect to mysql 'db'
Issue When trying to setup a Github action to test a Django project automatically, we ran into an issue with the django.yml setup. Whenever we ran the .yml, we got this exception on the last step (python manage.py test): django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-3)") To state, our docker environment and tests alone work fine, just when trying to do this in a Github action, we get issues. What we have tried We have tried running a docker-compose up -d before running the test, to know for sure that our DB is running. Tried adding environment variables with DB info like this: https://github.com/Cuda-Chen/django-mysql-github-actions-demo/blob/main/.github/workflows/django-ci.yml Current code name: Django CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.8] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test Does anyone know what is going on here, and how we can resolve this? -
When I gave command on CMD manage.py runserver it instead took me into VS Code and when i ran it in VS code error was on (from django.core.management)
when I ran the command on CMD manage.py runserver it intern redirected to VS Code. When I tried to run on VS Code it showed the system cannot find the specified path. It was underlining this statemnt try: from django.core.management ---------------------- -
Django: The QuerySet value for an exact lookup must be limited to one result using slicing
i am tring to access a page using a slug url, but i keep getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. i thought it would be a filter or get error in my view but i don't know where the error is coming from view.py def tutorial_topic_category(request, slug): tutorial_category = TutorialCategory.objects.get(slug=slug) tutorial_topic_category = TutorialTopicCategory.objects.filter(tutorial_category=tutorial_category) context = { 'tutorial_topic_category': tutorial_topic_category, } return render(request, 'tutorials/tutorial_topic_category.html', context) def topic(request, slug, slug2): tutorial_category = TutorialCategory.objects.get(slug=slug) tutorial_topic_category = TutorialTopicCategory.objects.filter(tutorial_category=tutorial_category) topic = Topic.objects.get(slug=slug2, tutorial_topic_category=tutorial_topic_category) context = { 'topic': topic, } return render(request, 'tutorials/topic.html', context) urls.py path("<slug>", views.tutorial_topic_category, name='tutorial-topic-category'), path("<slug>/<slug2>", views.topic, name='topic') and how do i pass in the slug in my template using django template tag <a href="{% url 'tutorials:topic' category.slug category.slug2 %}"> -
Celery task is pending in the browser but succeeded in the python shell of Django
I'm using Django, Celery, and RabbitMQ for simple tasks on Ubuntu but celery gives no response. I can't figure out why the task is pending in the browser, while it is done when I used the shell by executing python3 manage.py shell. Here is my tasks.py file: from celery import shared_task, task @shared_task def createContainer(container_data): print(container_data,"create") return "created" @shared_task def destroyContainer(container_data): print(container_data,"destroy") return "destroyed" Here is my views.py file: def post(self,request): if str(request.data["process"]) == "create": postdata = { "image_name" : request.data["image_name"], "image_tag" : request.data["image_tag"], "owner" : request.user.id } # I tried to print the postdata variable before the task and it is working createContainer.delay(postdata) elif str(request.data["process"]) == "destroy": postdata = { "cont_id" : request.data["cont_id"] } # I tried to print the postdata variable before the task and it is working destroyContainer.delay(postdata) # I tried to print anything here, but it was not reachable and never executed Here is the code I tried in the shell: >>> from dockerapp.tasks import create_container >>> create_container.delay("fake data") >>> <AsyncResult: c37c47f3-6965-4f2e-afcd-01de60f82565> Also, I can see the logs of celery here in another terminal by executing celery -A dockerproj worker -l info It results in these lines when I used the shell: Received task: dockerapp.tasks.create_container[c37c47f3-6965-4f2e-afcd-01de60f82565] fake … -
When i create Django Project with environment i have had a mistake line but when i deleted the environment file the line had disappeared !! Any Idea?
import os from django.core.wsgi import get_wsgi_application // Mistake in any import commands line but it is working os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AIDjango.settings') application = get_wsgi_application() -
How can I get .vscode folder and settings.py file on my django project
I was following a tutorial on django . The tutor was using Mac OS he got the .vscode folder and settings.py in json But I can’t access that on my windows I’m using vscode editor -
Cache Key Warning
Project and unit test still works. But showing me this warning. (CacheKeyWarning: Cache key contains characters that will cause errors if used with memcached: ':1:nasa_neo_2019-01-01 00:00:00_2019-01-01 00:00:00') I want to get rid of this warning. So could you help me please? Here I check if there is data in the cache. cache_key = f'nasa_neo_{start_date}_{end_date}'.strip("") json_data = cache.get(cache_key) if not json_data: some process else: making a new request from api. and add to cache memory. cache.set(cache_key, json_data, timeout=4000) -
CSS not loading properly when html element appended using jquery in django template
I'm working on an ecommerce app where trying to get products using ajax and append the product list using .append method and data is being appended the problem is that css doesn't load properly also icons are loading. CSS loads sometimes when hard reloaded then again not loading once refreshed normally. Please find the below codes for your reference and help to resolve. <script> $.ajax({ url: "{% url 'frontend:get_products_by_tag' tag.id tag.slug %}", type: "GET", success: function (data) { {#console.warn(data)#} $("#productsByTagProductList").empty() $.each(data, function (index, value) { console.warn(value) const productId = value.id; const productName = value.name; const productPrice = value.product_price; const productDiscountedPrice = value.product_discounted_price; const thumbnailFront = value.thumbnail_front; const thumbnailBack = value.thumbnail_back; const productSlug = value.slug; const productBrand = value.brand; const productSize = value.size; const productColor = value.color; const avgRating = value.avg_rating; const productCategory = value.category; let addToCartBtn; if (productSize !== null || productColor.length !== null) { addToCartBtn = '<li><a href="javascript:void(0)" class="productViewModal"' + 'data-product-id="'+productId +'"' + 'title="Add to cart">' + '<i data-feather="shopping-bag"> </i></a></li>' } else { addToCartBtn = '<li><a href="javascript:void(0)"' + 'class="addtocart-btn update-cart"' + 'data-action="add"' + 'data-product_id="'+productId +' "' + 'title="Add to cart">' + '<i data-feather="shopping-bag"> </i> </a></li>' } let price if (productDiscountedPrice !== null) { price = '<span class="product-price">' + 'Rs.' … -
How to have multiple one to one relations to a specific model
I have a scientific info model that has a one-to-one relationship to my User model. this is my model: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) **other fields** I want to add an interviewer field to it as well so that I can chose an interviewer from the user model so I added it like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') interviewer = models.OneToOneField(User, on_delete=models.CASCADE, related_name='interviews') **other fields** but when I want to create a new user it gives me unique constraint failed error -
Error while loading the pytest module in Django project
I am trying to run pytest in a django project with it is showing me error of no module loading. I have created init.py in test folders, but that also not worked for me to resolve this issue. ______________ ERROR collecting lib/python3.9/site-packages/tenacity/tests/test_tornado.py _______________ ImportError while importing test module '/Users/xxxx/Documents/ecommerce/lib/python3.9/site-packages/tenacity/tests/test_tornado.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) lib/python3.9/site-packages/tenacity/tests/test_tornado.py:19: in <module> from tenacity import tornadoweb lib/python3.9/site-packages/tenacity/tornadoweb.py:23: in <module> from tornado import gen E ModuleNotFoundError: No module named 'tornado' File Tree is as follows: ecommerce ┣ __pycache__ ┃ ┣ __init__.cpython-39.pyc ┃ ┣ settings.cpython-39.pyc ┃ ┣ urls.cpython-39.pyc ┃ ┗ wsgi.cpython-39.pyc ┣ dashboard ┃ ┣ __pycache__ ┃ ┃ ┗ __init__.cpython-39.pyc ┃ ┣ migrations ┃ ┃ ┗ __init__.py ┃ ┣ tests ┃ ┃ ┣ __pycache__ ┃ ┃ ┃ ┣ __init__.cpython-39.pyc ┃ ┃ ┃ ┗ test_selenium_dashboard.cpython-39-pytest-6.2.5.pyc ┃ ┃ ┣ __init__.py ┃ ┃ ┗ test_selenium_dashboard.py ┃ ┣ __init__.py ┃ ┣ admin.py ┃ ┣ apps.py ┃ ┣ models.py ┃ ┗ views.py ┣ tests ┃ ┣ __pycache__ ┃ ┃ ┣ __init__.cpython-39.pyc ┃ ┃ ┣ selenium.cpython-39-pytest-6.2.5.pyc ┃ ┃ ┗ test_selenium.cpython-39-pytest-6.2.5.pyc ┃ ┣ __init__.py ┃ ┗ test_selenium.py ┣ .DS_Store ┣ __init__.py ┣ asgi.py ┣ settings.py ┣ urls.py ┗ wsgi.py conftest.py db.sqlite3 … -
how to create a employee multiple Experince in django
How to Create Multiple Experinces in Django This is Model.py Files code from django.db import models # Create your models here. class Detail(models.Model): first_name = models.CharField(max_length=96) last_name = models.CharField(max_length=96) email_id = models.CharField(max_length=96) mobile_no = models.CharField(max_length=96) dob = models.CharField(max_length=96) qualification = models.CharField(max_length=96) def __str__(self): return self.first_name class Experince(models.Model): detail = models.ForeignKey(Detail, on_delete = models.CASCADE) organization = models.CharField(max_length=96) designation = models.CharField(max_length=96) date_from = models.CharField(max_length=96) date_to = models.CharField(max_length=96) def __str__(self): return self.organization This is View.py file code: from django.shortcuts import render from .models import * #from .forms import * # Create your views here. def home(request, id): if request.method == 'POST': Detail(first_name = request.POST['first_name'], last_name = request.POST['last_name'], email_id = request.POST['email_id'], mobile_no = request.POST['mobile_no'], dob = request.POST['dob'], qualification = request.POST['qualification']).save() Experince(organization = request.POST['organization'], designation = request.POST['designation'], date_from = request.POST['date_from'], date_to = request.POST['date_to']).save() return render(request,"home.html") This is my html page: <!DOCTYPE html> <html> <head> <title>test page</title> <link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity= "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <script> $(document).ready(function () { // Denotes total number of rows var rowIdx = 0; // jQuery button click event to add a row $('#addBtn').on('click', function () { // Adding a row inside the tbody. $('#tbody').append(`<tr id="R${++rowIdx}"> <td class="row-index text-center"> <p>${rowIdx}</p> … -
How to execute my python script which is in HTML
Their is a recent update where we can embeed the python script within html code. That is called as pyscript : https://pyscript.net/ Just need to import the CDSN link in between <head> </head> tags of HTML. But only one issue is how do I pass my input to my python script and return output on SUBMIT button click I tried to create a simple page with choose file and submit button My code : <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <p>Click on the "Choose File" button to upload a file:</p> <form action="/action_page.php"> <input type="file" id="myFile" name="filename"> <input type="submit"> </form> <py-script> def readfile(): with open(filename) as myfile: head = [next(myfile) for x in range(1,5)] print(head) </py-script> </body> </html> The data in ABC.txt file 1,2,A 1,1,B 0,0,1 1,1,K h,j,l y,u,i a,h,g a,h,l e,t,y How do I call my python script code on SUBMIT button click & print first 5 text lines of file and display. -
Django customUser models
I have faced two or three issues with django customuser model. The first one being the skills models. I wanted to add the Skills in the custom user, realized that there has been some drawbacks, things like, I can not add this skill field properly and when adding the age in django, I dont kno, but the age field seems a bit confusing. My question is, how important is creating the separate userProfile that would inherit the custom user? I think I have come to realise that customuser is better left a lone. How do u guys manage such issues if ever faced? -
I need to split array to sub arrays of similar values in python
lets suppose i have this queryset_array: queryset_array = [{"category":"a"},{"category":"a"},{"category:"b"},{"category":"b"},{"category":"c"}, {"category":"c"}] how can i convert this array using most efficient pythonic way into: array_1 = [{"category":"a"},{"category":a"}}] array_2 = [{"category":"b"},{"category":"b"}] array_3 = [{"category":"c"},{"category":"c"}] -
React - Module parse failed: You may need an appropriate loader to handle this file type 6:15
Help me with this error: NPM run error my webpack setting: module.export = { module: { rules: [ { test: /\.js$|\.jsx/, exclude: /node_modules/, use: { loader: "babel-loader", presets: ['es2015'] } } ], } } -
How do I upload a webcam image using JavaScript ajax to a Django site?
I am creating a livestreaming site using Django and I need to upload an image using an ajax post request to a model form on the django site. I am working with the following code: Models: from django.db import models from django.contrib.auth.models import User class Camera(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='camera') image = models.ImageField(upload_to='live/', null=True, blank=True) Views: from .models import Camera from .forms import CameraForm @login_required @csrf_exempt def golive(request): cameras = Camera.objects.filter(user=request.user) camera = None if cameras.count() == 0: camera = Camera.objects.create(user=request.user) camera.save() else: camera = cameras.first() if request.method == 'POST': print(request.FILES) form = CameraForm(request.POST, request.FILES, instance=camera) if form.is_valid(): form.save() print("Working") return redirect('live:live') return render(request, 'live/golive.html', {'object': request.user.camera, 'form': CameraForm()}) @login_required def live(request, username): profile = get_object_or_404(Profile, user__username=username, identity_verified=True, vendor=True) cameras = Camera.objects.filter(user=profile.user) return render(request, 'live/live.html', {'profile': profile, 'camera': cameras.first()}) Templates: {% extends 'base.html' %} {% block content %} <h1>Go live</h1> <div id="container"> <video autoplay="true" id="video"> </video> <canvas id="canvas" width="1028" height="728"> </canvas> <button id="capture"></button> </div> {% endblock %} {% block javascript %} var video = document.getElementById('video'); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); function capture(){ ctx.drawImage(video, 0, 0, 1024, 728); ctx.save(); canvas.toBlob(function(blob){ console.log(blob); var fileOfBlob = new File([blob], 'camera.png'); var formData = new FormData(); formData.append('image', fileOfBlob, 'camera.png'); … -
How Can I get the tag id on clicked in Django?
Here's the html <div class="items-link items-link2 f-right"> <a href="{% url 'applytojob' %}" name="job_id" id="{{job.job_id}}" >Apply</a> </div> Here the id is dynamic, so whenever I clicked on this link I need to get id of this tag to my python code in Django. How can I achieve this? Thanks in advance -
I need to apply the values_list() function to queryset after filtering
Following is my View Class: from apps.embla_services.filters import RentPostFilters from django_filters import rest_framework as filters from apps.embla_services.models import RentPost from apps.embla_services.serializers import RentPostBriefSerializer class SearchRentPosts(generics.ListAPIView): def get_queryset(self): city = self.request.query_params.get("city") if city: return RentPost.objects.filter(city__name=city) else: return RentPost.objects.all() serializer_class = RentPostBriefSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = RentPostFilters Following is my Filter Class: from django_filters import rest_framework as filters from apps.embla_services.models import RentPost class RentPostFilters(filters.FilterSet): title = filters.CharFilter(lookup_expr="icontains") is_available = filters.BooleanFilter() rent_type = filters.ChoiceFilter(choices=RentPost.RentTypeChoices.choices) category__id = filters.NumberFilter() available_from = filters.DateFromToRangeFilter() price = filters.RangeFilter() class Meta: model = RentPost fields = ["title", "is_available", "rent_type", "category", "available_from", "price"] Following is my Serializer Class: from apps.embla_services.models import RentPost class RentPostBriefSerializer(serializers.ModelSerializer): uploaded_media = FileSerializer(source='media', many=True, read_only=True) category = serializers.CharField(source="category.title") is_expired = serializers.SerializerMethodField() def get_is_expired(self, obj: RentPost): if obj.available_To and obj.available_To < date.today(): return True return False class Meta: model = RentPost fields = ["id", "available_from", "title", "created_at", "latitude", "longitude", "is_available", "uploaded_media", "delivery", "price", "rent_requests", "is_available", "is_expired", "city","category"] What i want is that after all the filters are applied to queryset, i can split this queryset into sub arrays depending upon the category. For example if query set contains 30 items of 3 different categories (10 items in each category). i want the response that is sent … -
Django: How to filter model with multiple whitespaces?
I have a model with char field with values like this: "Justin Roseman" (one single whitespace betwen words) "Justin Roseman" (two whitespaces betwen words) " Justin Roseman " (a lot whitespaces betwen words) etc. etc... I want get all records searching "Justin Roseman". My database is MySQL. I have tried the icontains function, but it does not work if there is more than one whitespace between words: results = MyModel.objects.filter(name__icontains="Justin Roseman") # Only returns values whit one whitespace between words, none whit two or more whitespaces :( Any ideas? please. Maybe whit regex? Thanks :D