Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django with Electron React boilerplate
I'm using Electron React boilerplate for a desktop application. Now I want to use python django apis for database and business logics I'm just preferring django because of my good knowledge in it. Now I need some suggestions whether it is a good approach or not. If yes so how can I make standalone file for this approach django+eletron-react. I searched this on internet but didn't find answer -
Annotate closest OSM vertex
I'm trying to get the closest OSM vertex for each row of MyModel class MyModel(models.Model): location = GeometryField() I currently use RawSQL for this def annotate_closest_vertex(queryset): queryset = queryset.annotate( closest_vertex=RawSQL( """ SELECT id FROM planet_osm_roads_vertices_pgr ORDER BY the_geom <-> "mymodel"."location" LIMIT 1 """, (), ) ) And I would like to use the ORM I tried to create a unmanaged Model for OSM vertices class OSMVertex(models.Model): the_geom = GeometryField() class Meta: managed = False db_table = "planet_osm_roads_vertices_pgr" And a distance function class Distance(Func): arity = 2 def as_sql( self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context, ): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: arg_sql, arg_params = compiler.compile(arg) sql_parts.append(arg_sql) params.extend(arg_params) return f"{sql_parts[0]} <-> {sql_parts[1]}", params Then using a simple Subquery def annotate_closest_vertex(queryset): queryset = queryset.annotate( closest_vertex=Subquery( OSMVertex.objects.order_by( Distance("the_geom", OuterRef("location")) ).values_list("pk")[:1] ) ) However I get the error /usr/local/lib/python3.8/site-packages/django/db/models/query.py:1324: in _fetch_all self._result_cache = list(self._iterable_class(self)) /usr/local/lib/python3.8/site-packages/django/db/models/query.py:51: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1162: in execute_sql sql, params = self.as_sql() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:513: in as_sql extra_select, order_by, group_by = self.pre_sql_setup() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:55: in pre_sql_setup self.setup_query() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:46: in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:262: in get_select sql, params = self.compile(col) /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:445: in compile sql, params = node.as_sql(self, self.connection) /usr/local/lib/python3.8/site-packages/django/db/models/expressions.py:1126: in as_sql subquery_sql, sql_params … -
What is the proper way to pass a JS object as a django field value?
Given the following form: from django import forms class MyForm(forms.Form): my_field = forms.CharField() views.py from django.shortcuts import render from myapp.forms import MyForm def index(request): form = MyForm() if request.method == 'POST': form = MyForm(request.POST) return render(request, 'index.html', {'form': form}) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> </body> </html> I don't mean the field to be a character field, it's just for the sake of the example. What would be the proper and safe way to pass a JS object as the field value? This would be one possible way to do it. I'm not sure how safe or proper this is: document.querySelector('#id_my_field').value = JSON.stringify({a: 1, b: 2}) and then parse the resulting string: >>> json.loads(form.cleaned_data['my_field']) {'a': 1, 'b': 2} Yeah, I know I could just create a and b fields and make them numeric or whatever the dtype is but this is not an option in my case because these field values will be set dynamically and how many values are expected cannot be known in advance, so this is the convenient way to pass as many values as needed. -
ERROR `long_description` has syntax errors in markup and would not be rendered on PyPI
ERROR long_description has syntax errors in markup and would not be rendered on PyPI. No content rendered from RST source. WARNING long_description_content_type missing. defaulting to text/x-rst. Checking dist\sdk_passport-0.1.tar.gz: PASSED with warnings WARNING long_description_content_type missing. defaulting to text/x-rst. Checking dist\sdk_passport-1.0.tar.gz: PASSED with warnings WARNING long_description_content_type missing. defaulting to text/x-rst. WARNING long_description missing. i am facing this issue when i am going to upload my own package in Pypi. i have validated README.rst file also. Please give me any solution. my expectation is to find out long_description validation error -
How to get average by month in Django queryset?
I have been trying to get average values per month for the rainfall. There are dates, hours and values (hours don't matter here since average will be of all values per month). class TimeSeries(models.Model): station = models.ForeignKey(Station, on_delete=models.CASCADE) date = models.DateField() hour = models.IntegerField() value = models.FloatField() What i have tried is: delta = relativedelta(months=1) dateStart=TimeSeries.objects.values('date').order_by('date').values_list('date',flat=True).first() dateEnd=TimeSeries.objects.values('date').order_by('date').values_list('date',flat=True).last() for i in range(len(stationNumbers)): while dateStart <= dateEnd: timeSeries = TimeSeries.objects.filter(station__number=stationNumbers[i],date__range=[dateStart,dateStart+delta]).annotate(month=TruncMonth('date')).values('station__number','month').annotate(value=Avg('value')).order_by( 'station__number','month') I have tried making some changes into the query but it doesn't work in any way. Should i be using raw SQL here? and Can someone kindly help? i am new to Django. Thanks in advance. -
What should I do to edit django data?
I created a html page for a user page code that help the user to edit his information that stored in django admin, this code is to change (username, first name, last name, email) but whenever I try to change those 4 fields, it only changes username and email, but first name and last name is not being changed. I tried another html page and it worked, but I can't make this html to work. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Fontawesome CSS --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/stylee.css' %}"> </head> <body> <div style="backdrop-filter: blur(2px);"> <div class="homeicon"> <a id="homeicon" href="/MainPageAL/"> <img src="{% static 'image/Payment/homeIcon.png' %}" width="50" height="50"> </a> </div> <div class="container"> <form action="" method="POST" > {% csrf_token %} <div class="row"> <div class="imagelog"> <img class="imagelog-1" src="{% static 'image/UserProfilePage/UserProfile.png' %}" alt="Profile Picture"> </div> <div class="saker"> <div class="saker-left"> <div class="col"> <h3 class="title">User Profile</h3> <div class="inputBox"> <label for="username">Username:</label> <input type="text" id="username" name="username" placeholder="Username"> </div> <div class="inputBox"> <label for="first_name">First Name:</label> <input type="text" id="fname" name="fname" placeholder="First Name"> </div> <div class="inputBox"> <label for="last_name">Last Name:</label> … -
Add product to wish list in Djagno
I want to add a product in the wish list with click on the heart and become red when the product in the wishlist and remove when i click again here my views fonctions : @login_required(login_url='login') def favorie(request): if request.method == 'GET': query = request.GET.get('query', '') if query: products = Product.objects.filter(Q(nom__icontains=query) | Q(description__icontains=query)) return redirect(f'/products?query={query}') favories = Favorie.objects.filter(user=request.user) if favories : template = 'favorie.html' else: template = 'favorie_vide.html' return render(request, template , {'favories': favories}) def add_to_favorie(request,id): product = get_object_or_404(Product, id=id) favorie, created = Favorie.objects.get_or_create(user=request.user, product=product) if not created: favorie.delete() return redirect('detail', id=id) def remove_from_favorie(request, id): product = get_object_or_404(Product, id=id) favorite = Favorie.objects.filter(user=request.user, product=product).first() if favorite: favorite.delete() return redirect('product_detail', id=id) and here the template where i wanna to click : i try this make it bouton but nothing change -
Django Daphne - Secure websocket connection fails
I have setup my Django server to run on https mode and the API calls are also working. I have also configured Daphne which is starting without any problems. However, when I try to open a secure websocket connection using wss, it fails. It would be great if I can get any help on this. Thanks. docker-compose.yml services: api: platform: linux/amd64 container_name: api build: context: . dockerfile: Dockerfile.dev command: 'sh -c "./manage.py migrate && python manage.py runsslserver 0.0.0.0:8080"' restart: always networks: - default volumes: - ./:/app - $HOME/.aws:/root/.aws:ro - /var/run/docker.sock:/var/run/docker.sock - type: bind source: ./docker/cpuinfo_with_fake_speed.txt target: /proc/cpuinfo ports: - 8080:8080 env_file: - ./.env depends_on: - db daphne: platform: linux/amd64 container_name: daphne build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne --ws-protocol [ws, wss] -v 1 -e ssl:8000:privateKey=key.pem:certKey=cert.pem apps.asgi:application"' restart: always working_dir: /app networks: - default volumes: - ./:/app - /var/run/docker.sock:/var/run/docker.sock ports: - 8000:8000 asgi.py django_asgi_app = get_asgi_application() from channels.routing import ProtocolTypeRouter, URLRouter application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AuthMiddlewareStack(URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())])), } ) I can see that Daphne service is starting up fine daphne | 2023-04-28 05:39:32,845 INFO Starting server at ssl:8000:privateKey=key.pem:certKey=cert.pem daphne | 2023-04-28 05:39:32,847 INFO HTTP/2 support enabled daphne | 2023-04-28 05:39:32,847 INFO Configuring endpoint ssl:8000:privateKey=key.pem:certKey=cert.pem daphne | … -
How to allow users to attach multiple images to a Django post using a ModelForm and formset?
I'm building a Django app that allows users to create posts and attach images to those posts. Each user can create multiple posts, and each post can have multiple images. I'm using a ModelForm to handle the creation of posts, but I'm having trouble figuring out how to handle the creation of the images associated with each post. Here's my current code: models.py class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='post_images/') forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'body'] views.py def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'create_post.html', {'form': form}) What's the best way to modify my code to allow users to attach multiple images to their posts when they create them? How can I modify the PostForm to handle this, and how should I modify the create_post view to save the images along with the post? Any help is greatly appreciated! -
Candy translate to translate the data returned from controllers.py to javascript?
def mymethod(request): return_obj = {} if request.method == 'POST': info = request.POST try: ts_vals, coordinates, name = somefunction(params) return_obj["values"] = ts_vals return_obj["msg"] = candy.translated(request, "all_msg") # all_msg is from the excel return_obj["name"] = name return_obj["success"] = "success" except Exception as e: return_obj["error"] = candy.translated(request, "all_Error") return JsonResponse(return_obj) I tried the above process. The returned JSON is parsed in my javascript code and sent back to the interface from javascript code. How do we handle this situation with Candy Translation? -
When using group by count in a subquery using python django, an error occurs
I am using django 2.2.7, python3.7.9. class FuneralHall(models.Model): hall_name = models.CharField(max_length=100, null=False) flower_vender = models.ForeignKey('bugo.FlowerVender', default=None, null=True, blank=True, on_delete=models.SET_NULL) sales_partner = models.ForeignKey('main.SalesPartner', default=None, blank=True, null=True, on_delete=models.SET_NULL) class FlowerOrder(models.Model): STATUS_CHOICE = ( ('init', '결제준비'), ('ready', '입금대기'), ('paid', '입금완료'), ('confirm', '주문확인'), ('sent', '배송출발'), ('complete', '배송완료'), ('cancel', '배송취소'), ('refund', '환불'), ) funeral = models.ForeignKey(Funeral, null=True, blank=True, on_delete=models.SET_NULL) funeral_hall = models.ForeignKey(FuneralHall, null=True, blank=True, on_delete=models.SET_NULL) funeral_room = models.ForeignKey(FuneralRoom, null=True, blank=True, on_delete=models.SET_NULL) flower_product = models.ForeignKey(FlowerProduct, null=True, blank=True, on_delete=models.SET_NULL) flower_vender = models.ForeignKey(FlowerVender, null=True, blank=True, on_delete=models.SET_NULL) sales_partner = models.ForeignKey(SalesPartner, null=True, blank=True, default=None, on_delete=models.SET_NULL) order_status = models.CharField(max_length=10, null=False, choices=STATUS_CHOICE, default='init') flower_order_count = FlowerOrder.objects.filter(funeral_hall_id=OuterRef('id')).annotate(flower_order_count=Func('funeral_hall_id', function='Count')).values('flower_order_count') hall_list = FuneralHall.objects.annotate(flower_count=Subquery(flower_order_count)) This code works fine. However, if I add a filter condition to the subquery, an error occurs. flower_order_count = FlowerOrder.objects.filter(funeral_hall_id=OuterRef('id'), order_status='complete').annotate(flower_order_count=Func('funeral_hall_id', function='Count')).values('flower_order_count') hall_list = FuneralHall.objects.annotate(flower_count=Subquery(flower_order_count)) The error is 'Expression contains mixed types. You must set output_field.' occurs, but output_field doesn't seem to matter. When using group by count in a subquery, I shouldn't add a condition to the filter. Is there a way to add it? I've tried adding output_field to the subquery, and I've tried meeting different conditions. All failed to work. -
Python Django Framework Error: Could Not Find 'My Tasks' in the h1 tag
I am new to coding in Django. I am creating a Django App called Tasks. My code within each of the following files will be included. I keep getting the error that 'Could not find 'My Tasks' in h1 tag'...Could someone please explain to me what I am doing wrong here? admin .py from django.contrib import admin from tasks.models import Task # Register your models here. @admin.register(Task) class Task(admin.ModelAdmin): list_display = ( "name", "start_date", "due_date", "is_completed", "project", "assignee", ) Apps.py from django.apps import AppConfig class TasksConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "tasks" Forms.py from django import forms from tasks.models import Task class TaskForm(forms.ModelForm): class Meta: model = Task fields = [ "name", "start_date", "due_date", "project", "assignee", ] Models.py from django.db import models from django.conf import settings from projects.models import Project class Task(models.Model): name = models.CharField(max_length=200, default="New Task") start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( Project, related_name="tasks", on_delete=models.CASCADE, ) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="tasks", on_delete=models.CASCADE, null=True, ) Urls.py from tasks.views import create_task, show_my_tasks from django.urls import path urlpatterns = [ path("create/", create_task, name="create_task"), path("mine/", show_my_tasks, name="show_my_tasks"), ] Views.py from django.shortcuts import render, redirect from tasks.forms import TaskForm from projects.views import list_projects from django.contrib.auth.decorators import login_required from … -
integrating fusionauth and django-rest-framework
I am trying to integrate FusionAuth and Django-Rest-Framework (with a React frontend), and am getting very confused. I have some code that kind of works. It uses the "authorization code grant". The React frontend redirects to the FusionAuth login page which once submitted redirects back to the frontend with an authorization_code as a URL Parameter. The frontend passes that code to the Django backend which exchanges it for an access_token. That access_token is used to get some user information from FusionAuth including a unique id with which to create a local Django User (if one doesn't already exist). It then generates a local token and passes that to the frontend to use for authentication in future requests. Here is some pseudo-code: from fusionauth.fusionauth_client import FusionAuthClient client = FusionAuthClient(FA_API_KEY, FA_URL) def authenticate(request): authorization_code = request.data["code"] fa_token_response = client.exchange_o_auth_code_for_access_token() fa_user_response = client.retrieve_user(user_id=fa_token_response["userId"]) user, created = UserModel.objects.get_or_create( fa_id=fa_token_response["userId"], defaults={ "username": fa_user_response["username"], "email": fa_user_response["email"], }, ) token = generate_token(user) # THIS IS PROBABLY WRONG return Response( { "token": token, "user_id": user.id, } status=status.HTTP_200_OK, ) As you can see, I generate my own token (I happen to be using knox, but that's not important). But I want to just use the same access_token provided by … -
Getting the value of Foreign key values in Django
I just want to get the clientType.name through an ID of foreign key from Clients table and pass it to jsonResponse , I have tried but it doesn't work below I tried select_related but it doesn't work it says AttributeError: 'str' object has no attribute '_meta' def patientdetails(request): patient_id = request.POST.get('patient') context = { 'company' : Clients.objects.filter(id=patient_id).select_related() } qs_json = serializers.serialize('json', context) return JsonResponse({'data': qs_json}) models.py class ClientType(models.Model): name = models.CharField(max_length=128, blank=True, null=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = True db_table = 'client_type' class Clients(models.Model): client_type = models.ForeignKey(ClientType, models.DO_NOTHING) first_name = models.CharField(max_length=128, blank=True, null=True) middle_name = models.CharField(max_length=128, blank=True, null=True) last_name = models.CharField(max_length=128, blank=True, null=True) birthdate = models.DateField(blank=True, null=True) sex = models.CharField(max_length=128, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) occupation = models.CharField(max_length=128, blank=True, null=True) class Meta: managed = True db_table = 'clients' Result data in javascript }).done(function(data){ var resultdata = JSON.parse(data.data); }); -
I get the error "detail": "Method \"GET\" not allowed." when trying to make an action
Not really sure why this is happening. I want to send a leaderboard with some data. I already made it work as part of my view/ but i wanted to implement it in an action. Yet when I do it, I get this error. This is my code in my view file @action (methods="GET", detail=False, serializer_class=LeaderboardSerializer, permission_classes=[AllowAny]) def Leaderboard(self, request): return Response({ "results": str(request.results) },status=status.HTTP_200_OK) Not working :( -
What is best practice for storage of AWS credentials within a django application?
I'm new to using AWS Services and Django together and I'm having trouble finding information around best practices for storing your aws creds for Django to access? I have a basic django application that's connected to an S3 bucket, so I need to be able to use boto to invoke the connection to the bucket. But I'm not sure how to go about storing the aws credentials I would need to pipe into my boto functions to use any of the services. I have read in a few places of people putting their aws credentials into the settings.py file within their django project, but this doesn't really feel secure to me. I also looked into AWS Secrets Manager, but it looks to me as though it's more suited for keys related to other services. Could anyone perhaps explain what my other options are, or why storing them in settings.py is perhaps a safe option? Really not certain on the best way to go about this one. -
Change value in form with readonly_fields field when creating an object
class PostAdmin(admin.ModelAdmin): form = PostFormAdmin readonly_fields = ['author'] class PostFormAdmin(PostValidationMixin, forms.ModelForm): class Meta: model = Post fields = '__all__' author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, default=1) Since the field is readonly_fields, it is always default Before I submit the form, I need to substitute request.user there I want to understand at what stage it is possible to assign request.user so that the user sees himself in the form and not the default user -
Not getting fields to post data in Django REST framework
Perfoming a crud api rest in django rest framwork, i created class based views. But when i run my app in browse, I am not getting forms to post data. When i scroll down getting media type and content option not my model fields. There is my model: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from djongo import models as djongo_models from bson.objectid import ObjectId from django.contrib.auth.hashers import make_password, check_password from django.core.validators import RegexValidator from api.enums import Status, UserRole class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **extra_fields): if not email: raise ValueError('The email is required') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('role', UserRole.ADMIN) return self.create_user(username, email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): mongo_id = djongo_models.ObjectIdField() def save(self, *args, **kwargs): if not self.mongo_id: self.mongo_id = ObjectId() super().save(*args, **kwargs) username = models.CharField(max_length=20, blank=False) name = models.CharField(max_length=20, blank=False, default='') lastname = models.CharField(max_length=20, blank=False, default='') password = models.CharField(max_length=128, blank=False,) def set_password(self, raw_password): self.password = make_password(raw_password) def check_password(self, raw_password): return check_password(raw_password, self.password) phone_number = RegexValidator(regex=r'^\+\d{1,3}\s\d{6, 14}$', message='Insert a valid phone number and it\'s country code') email = models.EmailField(unique=True, blank=False) birth_date = models.DateField(null=True) role = models.CharField(max_length=10, choices=[(role, role.value) … -
Stripe card element stopped working and can't seems to know what wrong about it
HTML file <div class="new-card-form"> <form action="." method="post" class="stripe-form" id="stripe-form"> % csrf_token %} <div class="stripe-form-row" id="creditCard"> <label for="card-element" id="stripeBtnLabel">Credit or debit card</label> <div id="card-element" class="StripeElement StripeElement--empty"> <div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: none !important; display: block !important; background: transparent !important; position: relative !important; opacity: 1 !important;"> <iframe frameborder="0" allowtransparency="true" scrolling="no" name="__privateStripeFrame5"allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-19066928f2ed1ba3ffada645e45f5b50.html#style[base][color]=%2332325d&amp;style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&amp;style[base][fontSmoothing]=antialiased&amp;style[base][fontSize]=16px&amp;style[base][::placeholder][color]=%23aab7c4&amp;style[invalid][color]=%23fa755a&amp;style[invalid][iconColor]=%23fa755a&amp;componentName=card&amp;wait=false&amp;rtl=false&amp;keyMode=test&amp;origin=https%3A%2F%2Fstripe.com&amp;referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js&amp;controllerId=__privateStripeController1" title="Secure payment input frame" style="border: none !important; margin: 0px !important; padding: 0px !important; width: 1px !important; min-width: 100% !important; overflow: hidden !important; display: block !important; height: 19.2px;"></iframe><input class="__PrivateStripeElement-input" aria-hidden="true" aria-label=" " autocomplete="false" maxlength="1" style="border: none !important; display: block !important; position: absolute !important; height: 1px !important; top: 0px !important; left: 0px !important; padding: 0px !important; margin: 0px !important; width: 100% !important; opacity: 0 !important; background: transparent !important; pointer-events: none !important; font-size: 16px !important;"></div></div></div> <div class="stripe-form-row"> <button id="stripeBtn">Submit Payment</button> </div> <div class="stripe-form-row"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="save" id="save_card_info"> <label class="custom-control-label" for="save_card_info">Save for future purchases</label> </div> </div> <div id="card-errors" role="alert"></div> </form> </div> Views.py def post(self,*args, **kwargs): # Create Stripe payment order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') chargeID = stripe_payment(settings.STRIPE_SECRET_KEY,token, order.get_total(),str(order.id)) if (chargeID is not None): order.ordered = True # create and Save the payment payment = Payment() payment.stripe_charge_id = chargeID payment.user = self.request.user payment.price = order.get_total() … -
Updating values on frontend but returning NaN
I am trying to automatically update and refresh my item total in my cart page when an item quantity is updated. I keep getting an a return of NaN. I also see a console log of price is undefined, but I don't know how to solved this. Script: function updateCartItem(cartId, cartItemId, quantityToAdd, csrftoken, price) { console.log('price:', price); fetch(`/api/carts/${cartId}/items/${cartItemId}/`, { method: "PATCH", headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify({ quantity: quantityToAdd, }), }) .then((response) => response.json()) .then((data) => { console.log("Cart successfully updated:", data); console.log("CART:", cartId) fetch("/cart/") .then((response) => response.text()) .then((html) => { // update the cart items and total price on the page with the new cart data const parser = new DOMParser(); const doc = parser.parseFromString(html, "text/html"); const itemsContainer = document.getElementById("cart-items"); const totalContainer = document.getElementById("cart-total"); if (itemsContainer) { itemsContainer.innerHTML = doc.getElementById("cart-items").innerHTML; } if (totalContainer) { totalContainer.textContent = doc.getElementById("cart-total").textContent; } const itemTotalContainer = document.getElementById(`item-total-${cartItemId}`); console.log('itemTotalContainer:', itemTotalContainer); if (itemTotalContainer) { const quantity = parseInt(itemTotalContainer.dataset.quantity); const newQuantity = quantity + quantityToAdd; const newTotal = newQuantity * price; itemTotalContainer.textContent = `£${newTotal.toFixed(2)}`; itemTotalContainer.dataset.quantity = newQuantity; } }) .catch((error) => { console.error(error); }); updateItemQuantity(); // update the quantity values on the page after the cart has been updated updateCartQuantity(); // update the total cart … -
Is it possible to create multiple Swagger documentation pages using drf-spectacular?
There are two kinds of APIs in my DRF project. I want to multiple Swagger documentations for each of them. Is it possible to create multiple Swagger documentation pages using drf-spectacular? -
Django: socket doesn't seem to connect without returning any errors
my name is Liran and I am currently working on my computer science final project. my project is a web based ide with the main selling point of a room feature in which a couple of people can work on the same code together. for the backend I am using python - Django and for the frontend I am using JS and bootstrap for the design. At first I wanted to just create a basic html page in which I can write some text into a text-area and for every new input to the text area the server would get notified and update everyone via the socket and when someone pressed the submit button the code will run on the server and the outpot is returned real time (I know the security risks and how not smart it is to do that I just need a fast way to do it for my project). After getting a fully skeleton of the project (you can see the working skeleton of the project in the dev branch in the GitHub page) I started making a way to create "rooms" in which people can work together in a costume socket. For this I … -
TemplateSyntaxError using with filter() in template
I'm getting this issue web ussing filter on the template to display a button when a condition occurs My view: def grupos(request): modalidades = Modalidad.objects.filter(disciplina=1).filter(temporada__activo__exact=True).order_by('-siglas') context = {'modalidades': modalidades} return render(request, 'temporadas/grupos.html', context=context) My models: class Modalidad(models.Model): disciplina = models.ForeignKey(Disciplina, on_delete=models.SET_NULL, null=True, blank=True) descripcion = models.CharField(max_length=64, null=False, blank=False) categoria = models.ForeignKey(Categoria, on_delete=models.SET_NULL, null=True, verbose_name='Categoría') created = models.DateTimeField(auto_now_add=True) changed = models.DateTimeField(auto_now=True) categoria_insc = models.ManyToManyField(Categoria, related_name='categoria_insc') def __str__(self): return self.siglas class Grupos(models.Model): created = models.DateTimeField(auto_now_add=True) changed = models.DateTimeField(auto_now=True) activo = models.BooleanField(default=True) siglas = models.CharField(max_length=5, null=True, blank=True) def __str__(self): return f'G{str(self.siglas)}' class Team(models.Model): created = models.DateTimeField(auto_now_add=True) changed = models.DateTimeField(auto_now=True) activo = models.BooleanField(default=True) temporada = models.ForeignKey(Temporada, on_delete=models.CASCADE) modalidad = models.ForeignKey(Modalidad, on_delete=models.CASCADE) siglas = models.CharField(max_length=5, null=True, blank=True) club = models.ForeignKey(Club, on_delete=models.CASCADE) grupo = models.ForeignKey(Grupos, on_delete=models.SET_NULL, null=True, blank=True, related_name='grupos') def __str__(self): return str(self.id) And finally my template: {% for m in modalidades %} <div class="col-4 col-md-2 col-xxl-1 text-center pb-4 pb-xxl-0 "> <span class="fs-3 lh-1">{{ m.siglas }}</span> <h1 class="fs-3 pt-3">{{ m.team_set.all|length }}</h1> {% if m.team_set.filter(grupo__isnull=True) %} <button class="btn btn-primary btn-sm me-1 mb-1" type="button">Crear Grupos</button> {% endif %} </div> {% endfor %} I'm getting the error: Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(grupo__isnull=True)' from 'm.team_set.filter(grupo__isnull=True)' can I do this kind of things in the … -
How to transfer data from a JavaScript variable to a python file in a Django project?
I'm making a recipe generator website where each ingredient is an image inside a div. When that div is clicked, it toggles to another colour. When submit is clicked, I want the ids of all the selected divs to be consolidated into one array. I'm able to achieve this using JavaScript, using the following code. $(document).ready(function () { var selectedDivs = []; $(".square").click(function () { $(this).toggleClass("selected"); var divId = $(this).attr("id"); var index = selectedDivs.indexOf(divId); if (index === -1) { selectedDivs.push(divId); } else { selectedDivs.splice(index, 1); } }); $("#submit").click(function () { $("#result").text("Selected Divs: " + JSON.stringify(selectedDivs)); }); }); How do I now send this data to the views.py file in my Django project, where it can become a list? Or is there a way to achieve this functionality directly in the python file itself? I tried using AJAX but I'm not sure how to link the pages properly. -
can we use image url to detect video content in OpenCv
I am a beginner in OpenCV and I want to use it to detect video content that contains nudity. I tried using image_url to prompt OpenCV to display an error message when a user attempts to post a video file containing that image, but the method I used below did not work. The video was uploaded to my database. Could you please point out where I went wrong? Also, please note that the picture stored in the nude_url variable does not contain any nudity as Stack Overflow does not support such pictures. def create_video(request): if request.method == 'POST': video = request.FILES.get('video') cap = cv2.VideoCapture(str(video)) nude_url = 'https://ichef.bbci.co.uk/news/976/cpsprodpb/17638/production/_124800859_gettyimages-817514614.jpg while(cap.isOpened()): ret, frame = cap.read() if cap == nude_url: raise ValidationError('This video contains nudes, but nudes are not allowed') if video: video_type = video.content_type.split('/')[0] if video_type != 'video': raise ValidationError('File is not a video') video_ext = video.name.split('.')[-1] if video_ext not in ['mp4', 'avi', 'mov']: raise ValidationError('Unsupported video format') video_clip = VideoFileClip(video.temporary_file_path()) duration = video_clip.duration video_clip.close() if duration > 600: # 10 minute in seconds raise ValidationError('the video cannot be longer than 10 minute') new_video = Video.objects.create( user=request.user, video=video, ) new_video.save() return redirect('Video') else: raise ValidationError('No video file uploaded') return render(request, 'video/create_video.html')