Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: How to round down (truncate) a query number?
I'm working with sensitive currency values. In my case, i have to reproduce a sheet with it's formulas. The point is that i need to round down a currency value with 2 decimal places. A practical example is the number: 9809.4069, it should be rounded to 9809.40, with a truncation. Otherwise, normal rounding function returns me 9809.41. Obs. For performance reasons i need to bring all my values in one query. Usual ways, with normal functions as round(), doesen't work inside non-query functions. Well, my Query i'ts working completly FINE and brings everything that i want, the problem are the fields with Round() function, that returns me the "wrong" value. The Query: activetime_qs = activetime_qs.values( 'user', 'user__team__name','user__foreign_id','user__location','user__team__cost_center' ).annotate( full_name=Concat(('user__first_name'),Value(' '),('user__last_name')), project_id=Subquery(UserProject.objects.filter(user_id=OuterRef('user')).values('project')[:1]), item_id=Subquery(Project.objects.filter(id=OuterRef('project_id')).values('item')[:1],), project_name=Subquery(Project.objects.filter(id=OuterRef('project_id')).values('name')[:1]), project_code=Subquery(Project.objects.filter(id=OuterRef('project_id')).values('code')[:1]), item_name=Subquery(Item.objects.filter(id=OuterRef('item_id')).values('name')[:1]), item_value=Subquery(Item.objects.filter(id=OuterRef('item_id')).values('unitary_value')[:1]), available_time=Sum('duration'), completed_tasks_amount=Case( When(user__activity_type=ActivityType.DELIVERABLE, then=Subquery(TaskExecution.objects.filter(members=OuterRef('user'), completed=True, start__date__gte=initial_date, start__date__lte=final_date) .values('pk').annotate(count=Func(F('pk'), function='Count')) .values('count'), output_field=IntegerField() ) ), default=1, ), availability_percentage=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(F('available_time') / expected_time, 3)), default=0, output_field=FloatField() ), subtotal_value=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(F('item_value') * F('availability_percentage'),2) ), default=Round(F('item_value') * F('completed_tasks_amount'),3), output_field=FloatField() ), availability_discount=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(-1 + F('availability_percentage'),3), ), default=0, output_field=FloatField() ), discount_value=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(F('item_value') - F('subtotal_value'),2), ), default=0, output_field=FloatField() ), ) return activetime_qs Then, i've tried two aprocches to round the annotate values down. Use a DecimalField as output_field with the … -
How to create a new csv from a csv that separated cell
I created a function for convert the csv. The main topic is: get a csv file like: ,features,corr_dropped,var_dropped,uv_dropped 0,AghEnt,False,False,False and I want to conver it to an another csv file: features corr_dropped var_dropped uv_dropped 0 AghEnt False False False I created a function for that but it is not working. The output is same as the input file. function def convert_file(): input_file = "../input.csv" output_file = os.path.splitext(input_file)[0] + "_converted.csv" df = pd.read_table(input_file, delimiter=',') df.to_csv(output_file, index=False, header=True, sep=',') -
How to prevent the page scrolling back to the top after clicking on a button?
I have a small form on django, when the button is clicked it display a django message bellow the form to tell the user that he successfully clicked on the button but it redirect the user in the top of the page. I want the page to stay where it is or redirect where the form is so he can see the message. <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-dark">Soumettre</button> </form> views.py def home(request): if request.method == 'POST': form = LeadForm(request.POST) if form.is_valid(): nom = form.cleaned_data['nom'] messages.success(request, "Merci pour votre message. Nous allons vous contactez le plus vite possible.") else: form = LeadForm() return render(request, 'main/index.html', {'form': form}) I tried to add a href="#!" or href="javascript:void(0);" to the button but it is not working either. -
Django - special query or another field holding Boolean data to get view from multiple models
I have few models, but right now I want to focus on two: class Client(models.Model): first_name last_name car # Client's car to be serviced class Service(models.Model): service_name service_type service_date client = models.OneToOneField(Client, on_delete=models.CASCADE, verbose_name="Client served") def __str__(): return f"Client {self.client} was serviced at {self.service.date}" I want to show all clients data in form of a table... first_name Last_name Car (make/model) Serviced? Service date John Watson Toyota Auris Yes 2023-02-01 Bob Kilicki Toyota Corolla Yes 2023-02-01 Mark Smith Honda Civic No -------- David Bobson VW Polo Yes 2023-02-03 Andrew Hutchinson Renault Clio No -------- (...) But I need additionaly information if Client was served (car was serviced), if so - when (the date)? How can I do that from views.py? Should I make another field in Client model - for example boolean field holding information - client served: True or False? Or better way is to construct - some more advanced - query which will retrieve data from both models, but how? If it is common problem in Django, please point me to the right direction (in Django Docs). Don't know exactly what terms should I use... Of course any example, is welcome, too. -
The ability to like/vote posts from the post list
I have a problem. I made likes to the posts on the video from YouTube. It is possible to like a post only from post_detail view and it's works correctly! How to make it possible to like posts in the post_list (in my case it's 'feed')? Please help! MY CODE: utils.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' views.py from .utils import is_ajax def feed(request): comments = Comment.objects.all() posts = Post.objects.all().order_by('-created_at') return render(request, 'main/feed.html', {'posts': posts, 'comments': comments}) def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post, reply=None).order_by('-created_at') is_voted = False if post.votes.filter(id=request.user.id).exists(): is_voted = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post = post, author = request.user, content = content, reply = comment_qs ) comment.save() return redirect(post.get_absolute_url()) else: for error in list(comment_form.errors.items()): messages.error(request, error) else: comment_form = CommentForm() return render(request, 'main/post_detail.html', {'post':post, 'comment_form':comment_form, 'comments':comments, 'is_voted':is_voted}) @login_required def post_vote(request, slug): post = get_object_or_404(Post, id=request.POST.get('id'), slug=slug) is_voted = False if post.votes.filter(id=request.user.id).exists(): post.votes.remove(request.user) is_voted = False else: post.votes.add(request.user) is_voted = True context = { 'post': post, 'is_voted': is_voted, } if is_ajax(request): html = render_to_string('main/votes.html', context, request) return JsonResponse({'form':html}) votes.html <form … -
Page not found (404) No Booking matches the given query - Django web application
I am having trouble figuring out where my issue is. I am parsing a slug to the url, via my view pulling from the SlugField in my model. For an object instance that exists in my database, the slug is being parsed successfully into the url. However, I am receiving the above error and cannot work out why. The corresponding model is Booking, and the slug field is as follows: booking_reference = models.SlugField(verbose_name="Slug Field", blank=False, unique=True) (I wanted to use the booking_reference as the slug field). My views.py is as follows: class EditBookingView(UpdateView, NextUrlMixin): model = Booking form_class = BookingForm template_name = 'bookings/edit_booking.html' success_url = '/' default_next = '/' def form_valid(self, form): form.instance.user = self.request.user form.save() next_path = self.get_next_url() return redirect(next_path) def get_context_data(self, **kwargs): context = super(EditBookingView, self).get_context_data(**kwargs) context['slug'] = self.kwargs['booking_reference'] return context def get_object(self): slug = self.kwargs.get('booking_reference') return get_object_or_404(Booking, booking_reference=slug) And my urls.py are: from django.urls import path from .views import ( CreateBookingView, ViewBookingsView, EditBookingView, DeleteBookingView ) app_name = 'bookings' urlpatterns = [ path('createbooking/<str:slug>/', CreateBookingView.as_view(), name='create_booking'), path('viewbookings/<str:slug>/', ViewBookingsView.as_view(), name='view_booking'), path('editbooking/<str:slug>/', EditBookingView.as_view(), name='edit_booking'), path('cancelbooking/<str:slug>/', DeleteBookingView.as_view(), name='delete_booking'), ] Please note, I have a list view for which the booking reference is being displayed under each model instance successfully. It is from … -
Mutation in django graphene for model with foreign key and many to many relationship
I have 2 models in my django app, the first is Tags model and the second is Post model, the problem is when i try to use mutation for the Post model to add a post from the graphql it doesn't work but it works fine in the Tags model, also the Queries works fine when i try to get data from the database. Here's my Code: model.py: from django.db import models from django.utils.translation import gettext as _ from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Tag(models.Model): name = models.CharField(_("Tag Name"), max_length=50, unique=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(_("Title"), max_length=50, unique=True) slug = models.SlugField(_("Post Slug"), unique=True) body = models.TextField(_("Post Content")) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) published = models.BooleanField(_("Published"), default=False) author = models.ForeignKey(User, verbose_name=_("Author"), on_delete=models.CASCADE) tags = models.ManyToManyField("Tag", verbose_name=_("Tags"), blank=True) class Meta: ordering = ['-createdAt'] def __str__(self): return self.title schema.py: import graphene from graphene_django import DjangoObjectType from django.contrib.auth import get_user_model from .models import Post, Tag User = get_user_model() class PostType(DjangoObjectType): class Meta: model = Post class TagType(DjangoObjectType): class Meta: model = Tag fields = ('id', 'name',) class TagInput(graphene.InputObjectType): name = graphene.String(required=True) class CreatePostMutation(graphene.Mutation): class Arguments: title = graphene.String() … -
How to render update element (graph) with HTMX if two (2) elements (selector) have new value?
I have an element - dropdown list selector. Which works and there is a choice of value. Based on the value received, I send a request to execute the code and, at the end, to change / render another element (graph). I added one more element to the template - one more selector list. And also redirected the change route to this element in the template. It also began to change based on the received value in the first selector list. I'm thinking about how you can change the third element of the template (graph) - based on the values obtained - by the first and second elements (two selector lists). The first selector list - refines filters the model query. The second selector list - refines, filters the model request more precisely - the values already left in the request after the first selector and already at the end sends the result to display in the form of a graph. How can you think of changing only the schedule - rebuilding without changing the entire template? Whether it is possible to think up such by means of HTMX? zamer_tabl_2_htmx.html <div class="row"> <div class="col-4"> <select id="select-name" class="custom-select" name="select" autocomplete="off" hx-get="{% … -
IntegrityError at /clinic_management/patients/1/medhistory/ NOT NULL constraint failed: clinic_management_medical_history.patient_id
I'm trying to create an app which stores medical records of patients. I'm trying to get information about the patient but I have encountered a problem. When it comes to posting the medical history I receive the following error: "IntegrityError at /clinic_management/medhistory/ NOT NULL constraint failed: clinic_management_medical_history.patient_id" Any help is appreciated in advance. models.py class PatientPersonalInfo(models.Model): file_number = models.IntegerField(unique=True) identification_number = models.IntegerField(unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) father_name = models.CharField(max_length=50) birth_date = models.DateField(null=True, blank=True) occupation = models.CharField(max_length=50) phone = models.IntegerField() mobile_phone = models.IntegerField() address = models.TextField(null=True, blank=True) class Medical_history(models.Model): ailment = models.CharField(max_length=50) hospitalization_history = models.CharField(max_length=50) hospitalization_cause = models.TextField(null=True, blank=True) medication_use = models.CharField(max_length=50) patient = models.OneToOneField(PatientPersonalInfo, on_delete=models.CASCADE) views.py class PatientPersonalInfoViewSet(ModelViewSet): queryset = PatientPersonalInfo.objects.all() serializer_class = PatientPersonalInfoSerializer pagination_class = DefaultPagination search_fields = ['file_number', 'identification_number', 'last_name'] class MedicalHistoryViewSet(ModelViewSet): queryset = Medical_history.objects.all() serializer_class = MedicalHistorySerializer serializers.py class PatientPersonalInfoSerializer(serializers.ModelSerializer): class Meta: model = PatientPersonalInfo fields = ['id', 'file_number', 'first_name', 'last_name', 'father_name', 'identification_number', 'birth_date', 'phone', 'mobile_phone'] class MedicalHistorySerializer(serializers.ModelSerializer): class Meta: model = Medical_history fields = ['ailment', 'hospitalization_history', 'hospitalization_cause', 'medication_use'] -
Passing partial=True down to nested serializer in DRF
I have two serializers organised like this : class OuterSerializer(): inner_obj = InnerSerializer(many=True, required=False) other fields ...... class InnerSerializer(): field_1 = CharField() field_2 = CharField() Now my use case is to partial update the outer serializer's model. How I'm doing that is: def partial_update(self, request, *args, **kwargs): serializer = OuterSerializer(data=request.data, context={'request': self.request}, partial=True) serializer.is_valid(raise_exception=True) data = serializer.data outerobj = self.service_layer.update(kwargs['pk'], data, request.user) response_serializer = OpportunitySerializer(instance=outerobj, context={'request': self.request}) return Response(response_serializer.data, HTTPStatus.OK) The issue is this partial flag does not get passed down to the InnerSerializer. For example if my request body looks like below, I want it to work: {"inner_obj": { "field_1" : "abc" } } Currently I get a 400 error for this saying the field is required. What I've tried : Setting the partial variable within the OuterSerializer in the init method by modifying it as such def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # We pass the "current serializer" context to the "nested one" self.fields['inner_obj'].context.update(self.context) self.fields['inner_obj'].partial = kwargs.get('partial') However this doesn't travel down. -
How can I create a get function that returns data using only the id in Django?
Here we have the views.py file for the favorites model. The favorite model consists of two foreignkeys. One which links the favorites to the user's account, and the other that links it to the property the user favorited. I am trying to write a new get function that returns all of the properties that are favorited by a user using the parameter of the user's account id. The function should return all of the properties that are favorited with that account id. from .models import Favorites from .serializers import FavoritesSerializer from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response class FavoritesViewSet(viewsets.ModelViewSet): queryset = Favorites.objects.all() serializer_class = FavoritesSerializer class FavoritesGetView(APIView): def get(self, request, id): snippet = Favorites.objects.get(id=id) serializer = FavoritesSerializer(snippet, many=False) return Response(serializer.data) class FavoritesPropertyGet(APIView): def get(): So far, I have tried rewriting the get function under FavoritesGetView but realized that that get function is still required. So now I am trying to write a new get function under FavoritesPropertyGet. -
Ask Django - Nginx Invalid HTTP_HOST header: 'attacker.web'. You may need to add 'attacker.web' to ALLOWED_HOSTS
recently i had this error message in my sentry Invalid HTTP_HOST header: 'attacker.web'. You may need to add 'attacker.web' to ALLOWED_HOSTS. and i saw the request like this curl \ -H "Accept: */*" \ -H "Content-Length: " \ -H "Content-Type: " \ -H "Forwarded: for=\"attacker.web:8888\";by=\"attacker.web:9999\"" \ -H "Host: attacker.web" \ -H "User-Agent: Report Runner" \ -H "X-Forwarded-For: " \ -H "X-Forwarded-Host: mysite.com" \ -H "X-Forwarded-Proto: https" \ -H "X-Real-Ip: " \ "https://attacker.web/subpage/" how do i prevent this kind of request ? and what's the name of the attack ? i've been config my nginx to drop curl request return 444 when the host name doesn't the same with server_name how to deal with this kind of request ? -
How to find subtotal price of all products in shopping cart in django
Cart Model has product,user,quantity and def total_price(self): return self.quantity * self.product.price My Cart html page has cart.product.name, cart.product.price, cart.quantity, cart.total_price How to find the subtotal of all products in cart -
How to use both simple jwt token authentication and BasicAuthentication?
I have an DRF api and I have implemented the simplejwt authentication system. It works well. It is usefull when I want to connect my api from external script (I don't need to store credential and just use the token). However I also want to be able to use the DRF interface login when i reach my api from browser so I have implemented also the Basic and SessionAuthentication. Is it the good way to do that ? in my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), } in my api views.py from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.decorators import permission_classes, authentication_classes # Create your views here. @api_view(['GET']) #@authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def get_all(request): # as a token is used, the user with this token is know in the requets user = request.user # show only mesures of user having the token provided mesures = Mesure.objects.filter(user_id=user.id) serializer = MesureSerializer(mesures, many=True) return Response(serializer.data) In my urls.py from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('mesures/', views.get_all), path('mesure-add/', views.add_mesure), path('token/', TokenObtainPairView.as_view(), name='obtain_tokens'), path('token/refresh/', TokenRefreshView.as_view(), name='refresh_token'), path('api-auth/', include('rest_framework.urls')) ] As you can see I had to comment the @authentication_classes decorator to … -
Move my Django application + Apache to Docker
I am trying to migrate my test app to Docker, but I am always getting the same error, despite of trying many approaches. This is my Dockerfile: FROM python:3.10-slim-buster RUN apt-get update && apt-get install -y apache2 libapache2-mod-wsgi-py3 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY morabusa /app/ COPY app.conf /etc/apache2/sites-available/app.conf RUN a2dissite 000-default.conf && a2ensite app.conf CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] This is the app.conf for Apache vHost, which I have simplified a lot, in order to try to find the issue: <VirtualHost *:80> ServerName morabusa.com ErrorLog /app/morabusaprj/logs/error.log CustomLog /app/morabusaprj/logs/access.log combine <Directory /app> Require all granted </Directory> WSGIScriptAlias / /app/morabusaprj/wsgi.py </VirtualHost> This is my wsgi.py file configuration (I have added the import sys, but it still fails): import os import sys sys.path.append('/app') sys.path.append('/app/morabusaprj') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'morabusaprj.settings') application = get_wsgi_application() Traceback: [Wed Feb 08 17:57:56.488523 2023] [wsgi:error] [pid 9:tid 140315142702848] [client 192.168.1.33:60062] mod_wsgi (pid=9): Failed to exec Python script file '/app/morabusaprj/wsgi.py'. [Wed Feb 08 17:57:56.488574 2023] [wsgi:error] [pid 9:tid 140315142702848] [client 192.168.1.33:60062] mod_wsgi (pid=9): Exception occurred processing WSGI script '/app/morabusaprj/wsgi.py'. [Wed Feb 08 17:57:56.488622 2023] [wsgi:error] [pid 9:tid 140315142702848] [client 192.168.1.33:60062] Traceback (most recent call last): [Wed Feb 08 17:57:56.488633 2023] [wsgi:error] [pid 9:tid 140315142702848] … -
TheCurrentPath...DidntMatch Django
"I am encountering the error 'The current path, say/welcome/, didn’t match any of these' while trying to access a certain URL in my Django application. I have checked my URL patterns in my app's urls.py file, and there doesn't seem to be a typographical error in the URL. [[enter image description here](https://i.stack.imgur.com/gazLZ.png)](https://i.stack.imgur.com/4bPSK.png) I am not sure what is causing this error, and I would like to resolve it so that I can access the desired URL. Can anyone help me figure out what's causing this error and provide a solution? -
How can i make models in django with form input
I Want to make a backend service website, for that I am working in django and want to make django models but with form input, if a user create a table in my frontend I want to create a table or model in data base how can i do it? Hello stackies , I Want to make a backend service website, for that I am working in django and want to make django models but with form input, if a user create a table in my frontend I want to create a table or model in data base how can i do it? -
Running Django in IIS
I have a Python application that's that has been working correctly as backend for my website, up to now I have been running it using "python manage.py runserver IP:8000" in CMD. However I would like it to start using HTTPS, but when I try to access through my browser on https://IP:PORT I get the following error: You're accessing the development server over HTTPS, but it only supports HTTP. The server I am running all of this is a Windows Center 2019 DataCenter, normally on a linux environment I would just use NGINX+GUNICORN. I was browsing possible solutions and stumbled upon this, however I already am using IIS to host a website (My frontend), so I needed to figure out how to host several websites for the same IP, I have now found this. Long story short, I configured the new IIS website for it to access my django, I then changed the hostname since both frontend and the new backend will using the same ip and ports (80, 443). But now I have hit a spot where I'm confused due to my lack of experience in IIS and networking. I can't seem to understand how the request will go through … -
How create task with celery in django ? POO issue?
I'm trying to set up a task with Django and Celery. The Celery and Django configuration is okay, nothing to report on that side. However, I have a problem, I think with the writing, of my code in OOP. I can't locate where the problem is. It's an argument problem, 4 arguments are expected by delay(), but my method only expects 3. Here are the files and what I tried to do, as well as the error trace. My files helpers.py i want create a task for run_test_optimization method class MachineLearniaXHelpers(MagicModels): def __init__(self, data_dict, target_name, type_model, test_size = 0.33, random_state = 42, **kwargs) -> None: super().__init__() self.test_size = test_size self.random_state = random_state self.process = DataProcessor( data=data_dict, target_name=target_name ) self.metrics = MetricsScorer(type_model=type_model) self.model = self.several_algorythme(type_model, **kwargs) @staticmethod def split_data(data_dict): return train_test_split(*data_dict) @staticmethod def train_model(model, X, y): model.fit(X, y) def run_test_optimization(self): dict_result = [] for model in self.model: feature_model, values = self.process.transform_dict_to_array_structure() x_train, x_test, y_train, y_test = self.split_data(values) self.train_model(model, x_train, y_train) dict_metrics_train = self.metrics.choice_metrics_by_type_model(y_train, model.predict(x_train)) dict_metrics_test = self.metrics.choice_metrics_by_type_model(y_test, model.predict(x_test)) dict_result.append({ "name_model" : model.__class__.__name__, "features_model" : feature_model, "train_performances" : dict_metrics_train, "test_performances" : dict_metrics_test }) return dict_result tasks.py create my task task_run_test_optimization from celery import shared_task from .helpers import MachineLearniaXHelpers @shared_task def task_run_test_optimization(data_dict, target_name, … -
How to connect Python Django to Informix DB on a remote Windows Server
I need to connect my Django app to the Informix db I have an Informix db installed on a VM Windows server 2019 Datacenter I can access the db through dbvisualiser on my laptop I installed the Informix client SDK on my laptop in the Programs Files directory I tried this settings https://pypi.org/project/django-informixdb/ **In my settings.py ** DATABASES = { 'default': { 'ENGINE': 'django_informixdb', 'NAME': 'testdb', 'SERVER': "ol_test", 'HOST': '172.20.10.3', 'PORT': '9092', 'USER': 'informix', 'PASSWORD': 'test@12345', 'OPTIONS': { 'DRIVER': "C:\\Program Files\\IBM Informix Client-SDK\\bin\\iclit09b.dll", # Or iclit09b.dylib on macOS 'Setup': "C:\\Program Files\\IBM Informix Client-SDK\\bin\\iclit09b.dll", 'CPTIMEOUT': 120, 'CONN_TIMEOUT': 120, 'ISOLATION_LEVEL': 'READ_UNCOMMITTED', 'LOCK_MODE_WAIT': 0, 'VALIDATE_CONNECTION': True, }, 'CONNECTION_RETRY': { 'MAX_ATTEMPTS': 10, }, 'TEST': { 'NAME': 'testdb', 'CREATE_DB': False } } } I got this error C:\Users\test\PycharmProjects\bdm_reporting_app\bdm_reporting_app\settings.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\bas e.py", line 282, in ensure_connection self.connect() File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", l ine 26, in inner return func(*args, **kwargs) File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\bas e.py", line 263, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django_informixdb\base.py", line 251, in get_new_connection self.connection = self._get_connection_with_retries(connection_string, conn_params) File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django_informixdb\base.py", line 299, in _get_connection_with_retries conn = pyodbc.connect(connection_string, autocommit=conn_params["AUTOCOMMIT"], pyodbc.InterfaceError: ('IM002', … -
Unable to Pass Django Context Data to HTML View
Can anybody please tell me how I can pass context data to view. I get nothing in HTML page. views.py def cart(request): if request.method == 'POST': return redirect('index') else: if request.method == 'GET': # Recieve local storage product in post_id varibale post_id = request.GET.get('get_cart') cat_product = Product.objects.filter(id=.11) if post_id is not None: # Fomrat and remove { } and " from post_id string post_id = post_id.replace('{','') post_id = post_id.replace('}','') post_id = post_id.replace('"','') print("The Id is", post_id ) # Find ':' in string and get the value of id in cart_prod_index index =0 while index < len(post_id): index = post_id.find(':', index) if index == -1: break local_storage_prod_id = post_id[index-1] # '|' operator is used to append the queryset result cat_product = cat_product | Product.objects.filter(id=local_storage_prod_id) index+=2 print(cat_product) return render(request, "cart.html" ,{"x":cat_product,}) In cart.html {% for search in x %} {{search.name}} {% endfor %} Please tell How I can get my query set in HTML page -
I wanted to craete a 5 star rating system in django but it keeps getting this error:
i check with django document and But my problem was not solved [08/Feb/2023 15:57:18] "POST /courses/2/learning-django HTTP/1.1" 403 2506 error: Forbidden (CSRF token missing.): /courses/2/learning-django this is my models class Review(models.Model): course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) rating = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) comment = models.TextField() created = models.DateField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} my views: def productDetailView(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) new_comment = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.course = product new_comment.rating = request.POST['rating'] new_comment.save() else: form = ReviewForm() return render(request, 'shop/product_detail.html', {'product': product, 'form': form}) js function: $(document).ready(function(){ $('.rate .rate-item').on('click', function(){ var value = $(this).data('value'); $.ajax({ url: '{{ product.get_absolute_url }}', type: 'POST', data: {'rating': value}, success: function(response){ alert('Rating saved successfully!'); } }); }); }); my template <form method="post"> <div class="row"> <div class="col-md-6"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Fast name" }} </div> </div> <div class="col-md-6"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Last Name"}} </div> </div> <div class="col-lg-12"> <div class="form-singel"> <div class="rate-wrapper"> <div class="rate-label">Your Rating:</div> <div class="rate"> <div data-value="1" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="2" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="3" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="4" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="5" class="rate-item"><i … -
How to get identityToken from apple account?
I want to create "Sign in with apple" function and using for this drf-social-oauth2. Does anyone knows how to get identityToken from apple account for testing, for example google has OAuth2 playground? Should I create apple developer account? -
Unable to proxy Shiny using Django and Nginx (HHTP Response Code 101)
I am trying to use Nginx and Django to help me serve Shiny applications within my company's internal servers. I am testing everything locally first to make sure all is working properly. I am following two tutorials: https://pawamoy.github.io/posts/django-auth-server-for-shiny/#proxying-shiny-requests-to-the-shiny-app https://testdriven.io/dockerizing-django-with-postgres-gunicorn-and-nginx I started with the testdrive.io post to setup Django and Nginx and then combined the ideas with pawamoy's blogpost to setup the Shiny part. The final setup: Django app is listening on 8000 Shiny on 8100 Nginx is 1337 (as per testdriven.io tutorial). My final nginx conf file looks like this: upstream django_app { server web:8000; } upstream shinyapp_server { server shiny:8100; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name localhost; client_max_body_size 100M; location / { proxy_pass http://django_app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; # proxy_pass http://django_app; if (!-f $request_filename) { proxy_pass http://django_app; break; } } location /static/ { alias /home/app/web/staticfiles/; } location /media/ { alias /home/app/web/mediafiles/; } location ~ /shiny/.+ { # auth_request /auth; rewrite ^/shiny/(.*)$ /$1 break; proxy_pass http://shinyapp_server; proxy_redirect http://shinyapp_server/ $scheme://$host/shiny/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 20d; proxy_buffering off; } # location = /auth { # internal; # proxy_pass http://django_app/shiny_auth/; # proxy_pass_request_body off; # proxy_set_header … -
HOW CAN I VIEW PDF FILES FROM AN API WITH VUE JS
Hello friends I need your support.. I am currently developing an app with django rest framework in the backend and vue js in the frontend.. the app consists of saving pdf files, which I can list in a table.. but the problem is that it only I can see by table the path where they are saved and I have not been able to view the files. Can someone tell me how I can place a button to view these files? I have tried functions to download the files but I have not achieved a solution