Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to compare two querysets in django
I'm writing an if statement in Django that compares two querysets and extracts the same assignment. Although the results of cycle_per_day and next_visit_per_day are different, the field values are the same because the same Class Model is used. The assignment_id field is also included in both querysets. In other words, I would like to add a condition called if next_visit_per_day query reset exists in the cycle_per_day query set. But it doesn't apply. What went wrong? cycle_per_day = cycle_visit.filter(dosing_date__day=day, dosing_date__year=self.year, dosing_date__month=self.month, assignment__teacher=self.user.first_name) next_visit_per_day = next_visit.filter(next_visit__day=day, next_visit__year=self.year, next_visit__month=self.month, assignment__teacher=self.user.first_name) d = '' for cycle_visit in cycle_per_day: d += f'{cycle_visit.get_html_url_cycle}' for next_visit in next_visit_per_day: if next_visit.assignment_id in cycle_per_day: d += f'{next_visit.get_html_url_drop}' else: d += f'{next_visit.get_html_url_next_visit}' -
Form not submitting to the DataBase when using HTMX
I have the following models, and as you can see they are related to each other class Leads(models.Model): project_id = models.BigAutoField(primary_key=True, serialize=False) created_at = models.DateTimeField(auto_now_add=True) expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD') expected_licenses = models.IntegerField() country = CountryField(blank_label='(select_country)') status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled'), ('Idle', 'Idle') ], max_length=10) estimated_closing_date = models.DateField() services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'), ('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'), ('Software License', 'Software License'), ('Software Development','Software Development')], max_length=40) agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE) company = models.ForeignKey(Company,on_delete=models.CASCADE) point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) application = models.CharField(choices=[('O&G','O&G'),('Renewables','Renewables'),('Mining','Mining'), ('Other','Other'),('CSS','CSS')], default='O&G',max_length=20) sub_category = models.CharField(choices=[('Wind','Wind'),('Geo-Thermal','Geo-Thermal'),('Solar','Solar'), ('Tidal','Tidal')], max_length=20, blank=True) @property def age_in_days(self): today = date.today() result = self.estimated_closing_date - today return result.days def __str__(self): return f'{self.project_id}' class LeadEntry(models.Model): revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD',blank=True) date = models.DateField() lead_id = models.ForeignKey(Leads,on_delete=models.CASCADE) id = models.BigAutoField(primary_key=True, serialize=False) probability = models.DecimalField(max_digits=2, decimal_places=2, default=0, blank=True) @property def est_revenue(self): result = self.revenue * probabiity return result Essentially a lead entry is related to the lead, and I'm using HTMX to essentially add data to LeadEntry database using a form. Form class LeadEntryForm(forms.ModelForm): class Meta: model = LeadEntry fields = ('lead_id','date','revenue','probability') widgets = {'date': DateInput()} I have 2 views, one that will simply pass an HTML with a button for the user … -
bad performance for loop with instance and bulk create
I need to use bulk_create to create a lot of "detalle"(details), the problem is i have to iterate trough a json to get the arguments, and i got 4 fk so django ask to me for the instance, not the id. but to have id i have to do a .get(), so i got a bad performance, because its 4 gets by each iteration. its there a way to get all objects instances and put in a list or something to perform load then the instance without using get every time? class DetalleFichaAllViewSet(viewsets.ModelViewSet): serializer_class = DetalleFichaUpdateAllSerializer def create(self, request, *args, **kwargs): user = self.request.user data = request.data try: ficha = Ficha.objects.get(autor=user.id) DetalleFicha.objects.filter(ficha=ficha.id).delete() except Http404: pass # Create Ficha now = datetime.now() date_time = now.strftime("%Y-%m-%d %H:%M") print("AAAAAA DATA:", data) Ficha.objects.filter(autor=user.id).update(fecha_creacion=date_time, autor=user, nombre=data["nombreFicha"], descripcion=data["descripcionFicha"]) ficha = Ficha.objects.filter(autor=user.id).last() recintos = Recinto.objects.all() productos = Producto.objects.all() estandar_productos = EstandarProducto.objects.all() cotizaciones = Cotizacion.objects.all() detalles_ficha = [] for detalle in data["detalles"]: recinto = recintos.get(id=detalle[1]) producto = productos.get(id=detalle[10]) estandar_producto = estandar_productos.get(id=detalle[9]) try: cotizacion = cotizaciones.get(id=detalle[4]) except ObjectDoesNotExist: cotizacion = None print("Fecha: ", detalle[8]) detalle = DetalleFicha(carreras=detalle[0], recinto=recinto, nombre=detalle[2], cantidad_a_comprar=detalle[3], cotizacion=cotizacion, valor_unitario=detalle[5], valor_total=detalle[6], documento=detalle[7], fecha_cotizacion=detalle[8], estandar_producto=estandar_producto, producto=producto, ficha=ficha) detalles_ficha.append(detalle) DetalleFicha.objects.bulk_create(detalles_ficha) print("Array convertida", detalles_ficha) print(detalles_ficha[0]) return Response(status=status.HTTP_200_OK) -
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17) for Python venv
I'm having trouble setting up my database on Django. I am running my server on CentOS7 and although I downloaded the version of SQLite I wanted to use, Python keeps pointing to the preinstalled version that is not compatible with my version of Django. I've looked through the other questions that had the same problem as me: django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17)) How to use the latest sqlite3 version in python https://number1.co.za/upgrading-sqlite-on-centos-to-3-8-3-or-later/ But the thing that differs between all of these problems and mine is that I used the Python Manager that comes with aaPanel to install my version of Python (3.8.3) which creates a virtual environment for the version of Python that I'm using whereas the others download and compile it from the source. I have tried finding where the correct configure file (as I have found multiple that were not helpful) that is outlined in each of the answers to these questions could be, but to no avail. How could I go about pointing my version of Python to the up-to-date version of SQLite that I have installed? -
Getting "Authentication credentials were not provided" error when I don't want to require authentication
I have a project with JWT authentication in Django Rest Framework. Usually I require user to be authenticated but in the case of GET action (both list and retrieve) I would like everyone to be able to access it with no authentication required. The code for this functionality is very simple: class GetUserViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin): # allowed for everyone serializer_class = UserSerializer permission_classes = [permissions.AllowAny] queryset = User.objects.all() The permissions are set to allow any but there is probably some inconsistency with default auth class in Settings.py # --------------------------REST-framework-------------------------- REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } The last thing that could matter are my endpoints: urlpatterns = [ path("", UserViewSet.as_view({"post": "create"}), kwargs={'quantity': 1}), path("<int:quantity>/", UserViewSet.as_view({"post": "create"})), path("", GetUserViewSet.as_view({"get": "list"})), path("<int:pk>/", GetUserViewSet.as_view({"get": "retrieve"})), path("<int:pk>/", UserViewSet.as_view({"put": "update", "delete": "destroy"})), ] What I don't understand is that in other app where I have register functionality there is no such an error. I will show you this viewset: class ApiUserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer_class = ApiUserSerializer permission_classes = [permissions.AllowAny] queryset = ApiUser.objects.all() @extend_schema(request=ApiUserSerializer, responses=TokenSerializer) def create(self, request, *args, **kwargs): api_user_serializer = self.get_serializer(data=request.data) api_user_serializer.is_valid(raise_exception=True) api_user = api_user_serializer.save() refresh = RefreshToken.for_user(api_user) token_serializer = TokenSerializer( data={ "access": str(refresh.access_token), "refresh": str(refresh) } ) … -
Django-allauth: My post-sign-up redirect flow with Google Auth is broken and I can't figure out why
I integrated django-allauth with my Django app but something is not fully working: Problem If a user that does not have an account in my DB tries to sign-up using the the google allauth process, after the authentication process it is sent to the home page (behind login filter) successfully. However, if a user that already has an account in my DB (manually created) tries to login using the google auth by visiting /accounts/google/login/, after the authentication process it is sent to /accounts/social/signup/ (a weird page that django-allauth has). Funny enough thought, the user is logged in and if they try to access the home page they can and everything works. So it's just the redirect that is broken. I narrowed it down to the fact that the user's email already exist BUT there is no social account associated. Setup I have a custom user model where email is the main unique id of a user. from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create … -
Django Heroku Porting
Trying to set up Django configurations for a public url. So I ran this first. $ echo "web: python manage.py runserver 0.0.0.0:\$PORT" > Procfile $ git add Procfile $ git commit -m "Specify the command to run your project" In Procfile: web: python manage.py runserver 0.0.0.0:\$PORT release: python manage.py migrate In settings.py: PORT = os.getenv("PORT", default="5000") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["url"] In env.: PORT=5000 SECRET_KEY=value Was using the above commands and got (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku config:get PORT 5000 (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 3:08:10 PM web.1 | CommandError: "0.0.0.0:\$PORT" is not a valid port number or address:port pair. [DONE] Killing all processes with signal SIGINT 3:08:10 PM web.1 Exited with exit code null I also used $PORT without the backslash and $. How would I proceed from here to make the public url working. -
Django FileField auto urlencoding problem
image_file = models.FileField(storage=s3, max_length=512, blank=True) I have a model with theis image_file field backed by s3 storage. The only problem I have with this field is if the filename contains any url-encode-able characters, it will auto encode the filename. For example, if the filename contains %40, when retrieve the value from the model, it becomes %2540. I wonder if there is a switch I can turn this feature/bug off. -
Django cannot display model fields to template
I have a model from a package I would like to retreive fields from for the user to my template but am struggling to get this to work as I have done with user model previously: models class DeviceManager(models.Manager): def devices_for_user(self, user, confirmed=None): devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class Device(models.Model): user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE) name = models.CharField(max_length=64, help_text="The human-readable name of this device.") confirmed = models.BooleanField(default=True, help_text="Is this device ready for use?") objects = DeviceManager() class Meta: abstract = True def __str__(self): try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user) view from django_otp.models import Device def account(request): user = request.user device = Device.objects.all() context = {"user": user, "device": device} return render(request, 'account.html',context) template {{ device.name }} {{ device.confirmed}} I am getting the folowing error: AttributeError: Manager isn't available; Device is abstract I have also tried to change device = Device.objects.all() # To device = DeviceManager.objects.all() But the produces the following error: AttributeError: type object 'DeviceManager' has no attribute 'objects' Help is much apprecaietd in displaying the content from model to my template. Thanks -
Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided'
I've got a tiny function that just looks to get a response from my DRF API Endpoint. My DRF settings look like this: "DEFAULT_AUTHENTICATION_CLASSES": [ # Enabling this it will require Django Session (Including CSRF) "rest_framework.authentication.SessionAuthentication" ], "DEFAULT_PERMISSION_CLASSES": [ # Globally only allow IsAuthenticated users access to API Endpoints "rest_framework.permissions.IsAuthenticated" ], I'm using this to try and hit the endpoint: def get_car_details(car_id): headers = {"X-Requested-With": "XMLHttpRequest"} api_app = "http://localhost:8000/" api_model = "cars/" response = requests.get(api_app + api_model + str(car_id), headers=headers) json_response = response.json() return json_response I keep getting 'detail': 'Authentication credentials were not provided' Do I need to generate a CSRF token and include it in a GET request? The only time this gets hit is when a user goes to a view that requires they are logged in. Is there a way to pass that logged-in user to the endpoint?? -
Django Rest Framework API is being called twice
I am using Django Rest Framework to make a custom backend that does the web3 login flow. However, it is calling my authenticate function twice. And I can't figure out why. my token view: #expects public_address, nonce and token if user is currently signed in @api_view(["POST"]) def get_token(request): logger.debug(request.data) public_address = request.data["public_address"] web3 = Web3Backend() logger.debug(web3) logger.debug('running authenticate from token endpoint') user, token = web3.authenticate(request) logger.debug(user) logger.debug(token) if token: return JsonResponse({'token': token}) else: return Response({'message': 'Missing token'}, status=400) Authenticate Function: def authenticate(self, request, **kwargs): logger.debug(request); public_address = request.data.get('public_address', None) nonce = request.data.get('nonce', None) curr_token = request.data.get('token', None) Web3User = get_user_model() if public_address: if curr_token: #TODO: decode token and check if public_address is the same as the user calling it and if not expired #TODO: if yes then just return true and token token =jwt.decode(curr_token, SECRET_KEY, algorithms="HS256") #TODO: convert into datetime and make sure the current datetime is not pass this expiry = datetime. strptime(token['expiry'],'%y-%m-%d') now = datetime.date.today() logger.debug(expiry) logger.debug(now) if(token['user'] == public_address and expiry < now): logger.debug('JWT still valid') return True, curr_token else: return AuthenticationFailed() #TODO: decode the JWT and check if the user is the proper user try: #TODO: database check; will want to switch to JWT tokens in … -
How can I integrate jquery timepicker in my django project
Here is the jquery timepicker code: $('.timepicker').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: '10', maxTime: '6:00pm', defaultTime: '11', startTime: '10:00', dynamic: false, dropdown: true, scrollbar: true }); Here is my forms.py from django import forms from bootstrap_datepicker_plus import TimePickerInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content','chamber','address','fees','days','hours','review'] widgets = { 'hours': forms.DateField(widget=forms.DateInput(attrs={'class':'timepicker'})) } Here is my models.py class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField('Doctor\'s Name',max_length=100) content = models.CharField('Specialty',max_length=100) chamber = models.CharField('Chamber\'s Name',max_length=200) address = models.CharField('Address',max_length=100) fees = models.IntegerField(default=0) days = MultiSelectField(choices= DAYS_OF_WEEK) hours = models.TimeField() review = models.TextField() liked = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='liked') date_posted = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ('-date_posted', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) I am new to django and jquery how can I add a timepicker in my hours field? Where I put my mouse on right side of hours field it changes shape. But no event is triggered when pressed. Here no timepicker comes When I inspect this comes -
'int' object is not iterable when count the number of rows in database in Django
I have database created in Django. File models.py class Guest(models.Model): first_name = models.CharField(max_length=30, verbose_name='First name') last_name = models.CharField(max_length=30, verbose_name='Last name') middle_name = models.CharField(max_length=30, verbose_name='Middle name', blank=True, null=True) date_of_birth = models.DateField(verbose_name='Birthday') address = models.CharField(max_length=50, verbose_name='Address', default='VP 5/7') city = models.CharField(max_length=30, verbose_name='City') email = models.CharField(max_length=50, verbose_name='Email',blank=True, null=True) phone = models.CharField(max_length=20, verbose_name='Phone number', default='897777777') passport = models.CharField(max_length=15, default='C5555555') def __str__(self): return "First name: {}, Last name: {}".format(self.first_name, self.last_name) File views.py class GuestListView(generics.ListAPIView): serializer_class = GuestSerializer def get_queryset(self): queryset = Guest.objects.all() params = self.request.query_params city = params.get('city', None) if city: queryset = queryset.filter(city__startswith=city).count() return queryset File serializers.py class GuestSerializer(serializers.ModelSerializer): class Meta: model = Guest fields = "__all__" I run url like: http://127.0.0.1:8000/guests/all/?city=Kazan I got a error: 'int' object is not iterable How to fix that? -
How to query image path with right if condition from Django template?
In Django I have a box model. Each box has some images related to that box. from django.db import models from products.models import Product # Create your models here. class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) boxDescription = models.TextField() boxPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) boxSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from box name") boxCreatedAt = models.DateTimeField(auto_now_add=True) boxUpdatedAt = models.DateTimeField(auto_now=True) product = models.ManyToManyField(Product) def __str__(self): return self.boxName class Meta: db_table = 'boxes' ordering = ['-boxName'] class BoxImage(models.Model): image = models.ImageField() imageMetaKeyWords = models.CharField("Meta keywords for SEO", max_length = 255, help_text = "Comma delimited words for SEO") imageMetaDescription = models.CharField("Meta description", max_length = 255, help_text = "Content for image meta tag description") defaultImage = models.BooleanField(default= False) box = models.ForeignKey(Box, on_delete=models.CASCADE, related_name="images") In the views.py I need put all the boxes in the context so that they can be passed to the template from django.shortcuts import render from django.views import View from index.views import createNavContent from box.models import Box # Create your views here. class MainShop(View): def __init__(self): context = createNavContent() self.context = context.context def get(self, request, *args, **kwargs): self.context['title'] = 'Dimsum Box Shop' self.context['boxes'] = Box.objects.filter().all() return render(request, template_name='mainShop.html', context = self.context) … -
React axios patch overwrites manytomany field instead of adding to element
My react code is patching the model field group and completely erasing the original content within the group. I realize it might be my serializer or my view set but i can not find any examples of this being done through google search any help would be greatly appreciated. Request Handler handleJoin = (e, group) => { e.preventDefault(); axios.get('http://127.0.0.1:8000/core/current_user/', { headers: { Authorization: `JWT ${localStorage.getItem('token')}` } }) .then((user) => { let group_data = new FormData(); group_data.append('user', user.data.id); group_data.append('group', group.id); for (var value of group_data.values()) { console.log(value); } axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{ headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json', }, }) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err); }); }) .catch((err) => { console.log(err); }); } Model Serializer class UserGroupSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True, read_only=True,) class Meta: model = UserGroup fields = '__all__' Model Viewset class UserGroupDetail(APIView): def patch(self, request, pk): usergroup = UserGroup.objects.get(pk=pk) serializer = UserGroupSerializer(instance=usergroup, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
AttributeError: 'WindowsPath' object has no attribute 'endswith' when using runmodwsgi Django command
Windows 10, Python 3.8.10, Apache 2.4.51, Django 3.2.8, mod_wsgi 4.9.0 When I try to run the Apache server using python manage.py runmodwsgi, I get this output: Successfully ran command. Server URL : http://localhost:8000/ Server Root : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me Server Conf : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/httpd.conf Error Log File : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/error_log (warn) Operating Mode : daemon Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.cp1252 Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py", line 134, in handle options = mod_wsgi.server._cmd_setup_server( File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 3613, in _cmd_setup_server generate_apache_config(options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 1086, in generate_apache_config if target.endswith('/') and path != '/': AttributeError: 'WindowsPath' object has … -
Django Rest Framework - Cannot POST because username already exists
I am working on a basic rest api with django rest framework. And my database is on MySQL. For one of the functions, when I try to POST, it gives me an error because there is a row with the same username already. I have set the model to have all three of its fields to be unique_together. Please help me understand where i am going wrong, heres snippets of what i have currently: models.py: class VolunteerHours(models.Model): username = models.OneToOneField(Volunteer, models.DO_NOTHING, db_column='Username', primary_key=True) date = models.DateField(db_column='Date') hours = models.IntegerField(db_column='Hours') class Meta: managed = False db_table = 'volunteer_hours' unique_together = (('username', 'date', 'hours'),) urls.py: urlpatterns = [ path('timesheet/', views.TimesheetAPIView.as_view()),] views.py: from . import models from . import serializers from rest_framework import generics from rest_framework import mixins class TimesheetAPIView(generics.GenericAPIView, mixins.CreateModelMixin): serializer_class = serializers.VolunteerTimesheetSerializer def post(self, request): return self.create(request) serializers.py: class VolunteerTimesheetSerializer(serializers.ModelSerializer): class Meta: model = models.VolunteerHours fields = '__all__' The error im getting is: "username": [ "volunteer hours with this username already exists." ] What I want to happen is i can add as many rows with the same username as long as the date and hours are unique. Which are what is submit in my POST requests, but it says username … -
Django - Pymongo list index out of range error
I want to print the _id part of the results by running a query on the mongo db, but I am getting the "list index out of range" error. view; def deleted(request): q1=('XX') q2=('XX') client = MongoClient("XX") database = client["XX"] collection = database["XX"] query = {} query["Marketplace"] = q1 query["$or"] = [ { "Tuyx": q2 } ] cursor = collection.find(query) print(cursor) sonuc= loads(dumps(cursor)) id=sonuc[0]["_id"] print(id) client.close() return render(request, 'deletedlisting.html', {'id':id} ) ti want to print _id value as string; -
Continue uploading the file after connecting to the Internet
If the internet file is disconnected while uploading, how can I continue to upload the file using Django when it is connected? if request.method == 'POST' and request.is_ajax(): if formset.is_valid(): obj = formset.save(commit=False) obj.experience_id = experience_id obj.save() return JsonResponse({'error': False, 'message': 'video is uploaded.'}) else: return JsonResponse({'error': True, 'errors': formset.errors}) -
How to capture webcam input from ReactJS, stream to Django backend and display it back on the React frontend?
I have built a virtual makeover app using python like this one: https://www.maybelline.com/virtual-try-on-makeup-tools. I want to connect this to my React frontend by capturing the webcam input, send it to the Django backend and return the video stream to the frontend so that the virtual makeover happens in real-time i.e. apply lipstick, foundation, etc. Any ideas are welcome, and please let me know if you need anymore details. Thanks in advance!!! -
How to implement a custom renderer in Django REST framework for PDF and Excel export?
I have implemented two custom renderers in django rest framework which export data in Excel or PDF format. The problem is that I'm unable to set the file names when the response is generated. I have the following renderers: # app/renderers.py import os import openpyxl import pdfkit import random from django.template.loader import render_to_string from rest_framework.renderers import BaseRenderer from rest_framework.response import Response # for newer python, do the configuration for pdfkit config = pdfkit.configuration(wkhtmltopdf=r'path_to_bin/wkhtmltopdf') class XLSXRenderer(BaseRenderer): # ... code truncated class PDFRenderer(BaseRenderer): media_type = 'application/pdf' format = 'pdf' charset = 'utf-8' def render(self, data, accepted_media_type=None, renderer_context=None): if hasattr(data, 'items'): for key, value in data.items(): if key == 'results': html_string = render_to_string('user_mbe/EmployeeList.html', {'header': ('first_name', 'last_name', 'id_number', 'phone_number', 'email', 'job_title'), 'data': [tuple(x.values()) for x in value]}) result = pdfkit.from_string(html_string, output_path=False, configuration=config) return result return None # app/views.py from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from .renderers import PDFRenderer, XLSXRenderer from .models import Employee from .serializers.employee import EmployeeSerializer class EmployeeAPIView(ListAPIView): serializer_class = EmployeeSerializer # Are these correct here? renderer_classes = [PDFRenderer, XLSXRenderer, JSONRenderer] def get_queryset(self): return Employee.objects.filter(created_by=self.request.user) def get(self, request, *args, **kwargs): ?? super().get_paginated_response(request, *args, **kwargs) ?? unable to set a file name here return response -
Multi-level access with ManyToMany relationships in Django
I have models, objects from which can be represented as a directed graph: from django.db import models from django.contrib.auth.models import User class Record(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) content = models.TextField() sequels = models.ManyToManyField('self', blank=True, symmetrical=False, through='Extend', related_name='extending') author = models.ForeignKey(User, on_delete=models.CASCADE) class Extend(models.Model): ancestor = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='+') descendant = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='+') class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_relationships", fields=["ancestor", "descendant"], ), models.CheckConstraint( name="%(app_label)s_%(class)s_prevent_self_extend", check=~models.Q(ancestor=models.F("descendant")), ), ] Anytime a new instance of Record is created and it has a relationship with another instance through the Extend model, I would love to calculate author.user.userprofile.income attribute in the User instance. The problem is I don't know how to calculate this attribute for all the ancestors of the newly created Record which follows some rule: if the newly created Record costs 50, the first-level ancestor gets 25 and 25 goes to other ancestors, constanly being divided by 2. I can write the formula for the first-level ancestor, but what for others? # In case of some purchase: class ExtendPurchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(Record) date = models.DateField(auto_now_add=True) cost = models.PositiveIntegerField() def calculate_income(self): for item in self.items.all(): item.author.userprofile.income += self.cost / len(self.items.all()) / 2 # first-level; if one would … -
Post request with an object via serializer many=False
I am trying to make a POST request with an object for example this is how I send my request : { "title": "Haloween", "body": " This is one of the greatest ones", "grade_level": { "id": 2, "country": "UG" }, "tags": [{"name": "Jamming"}] } So I wanted to post an object : "grade_level": { "id": 2, "country": "UG" } and below is my Serializer I use : class GradeClassSerializer(CountryFieldMixin, serializers.ModelSerializer): """GradeClass Serializer.""" class Meta: model = ClassGrade fields = ('id', 'grade', 'country', 'color_code', ) class PostSerializer(serializers.ModelSerializer): """Post Serializer""" owner = UserProfile(read_only=True) tags = TagSerializer(many=True) comments = CommentSerializer(many=True, read_only=True) slug = serializers.SlugField(read_only=True) grade_level = GradeClassSerializer(many=False) When I send the object grade_level , I cant seem to receive it it only receives the the id : def create(self, validated_data): """Create a blog post in a customized way.""" grade_level = validated_data.pop('grade_level', {}) status = validated_data.pop('status', '') post = Post.objects.create(**validated_data, owner=self.context['request'].user) if grade_level: grade = ClassGrade.objects.get(id=grade_level['id']) post.grade_level = grade post.save() return post When I make a request, this is what happens : KeyError: 'id' The object comes with only an country without an id. This is what grade_level = validated_data.pop('grade_level', {}) prints : OrderedDict([('country', 'UG')]) How can get the id from the object. NOTE: … -
Error during template rendering using extra_context django
Hello I'm using extra_context in views and in the HTML I'm passing it, but it seems that I am doing it wrong because I get this error: Error during template rendering Does anyone know why? views.py class InformacionTiendasAdd(CreateView): model=InformacionTiendas form_class=InformacionTiendasForm template_name='InformacionTiendas/informacion-tiendas-agregar.html' success_url=reverse_lazy('InformacionTiendas:list_tiendas') extra_context={'tiendas': InformacionTiendas.objects.all()} models.py class InformacionTiendas(models.Model): nombre=models.CharField(max_length=255) registro_desde=models.DateTimeField(default=datetime.now ) tax_id=models.IntegerField() def __str__(self): return f'{self.nombre} {self.registro_desde} {self.tax_id} informacion-agregar-tiendas.html <form class="needs-validation" novalidate> {% for tienda in tiendas %} <div class="row mb-3"> <div class="col-md-12"> <div> <label class="form-label" for="validationCustom01">Name</label> {{ tienda.nombre }} <div class="invalid-feedback"> Please provide the workshop name. </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom06">Registration</label> {{ tienda.registro_desde }} Please provide workshop`s registration number. </div> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom07">TAX ID</label> {{ tienda.tax_id }} <div class="invalid-feedback"> Please provide workshop`s registration number. </div> </div> </div> </div> {% endfor %} </form> -
why the selected answers is not showing? django
I am trying to make a quiz app using Django and js with using &.ajax jquery function ,, everything runs ok except for selected answers I can see the result and questions everything, why is that happing I had created an input for the answers I can view them on the page. my problem is in the post this selected answer views.py @csrf_exempt def save_quiz_view(request, pk): if request.is_ajax(): questions = [] data = request.POST data_ = dict(data.lists()) # delet the csrf_token data_.pop('csrfmiddlewaretoken') for k in data_.keys(): print('key', k) question = Question.objects.get(text=k) questions.append(question) print(questions) user = request.user quiz = Quiz.objects.get(pk=pk) score = 0 # Get the ratio of user's answers multiplier = 100 / quiz.number_of_questions results = [] correct_answer = None for answer in questions: a_selected = request.POST.get(answer.text) print("selected:", a_selected) if a_selected != "": question_answers = Answer.objects.filter(question=answer) # loop through an answers of praticlar question for a in question_answers: if a_selected == a.text: # question is correct if a.correct: score += 1 correct_answer = a.text else: # both cases display the correct answer if a.correct: correct_answer = a.text results.append({ str(answer): { 'correct_answer': correct_answer, 'answered': a_selected } }) else: results.append({str(answer): 'not answered'}) score_ = score * multiplier Result.objects.create(quiz=quiz, user=user, score=score_) if score_ …