Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'float' object has no attribute 'quantize' using django-firebird
I'm using: Django 2.2.24 django-firebird 2.2a1 fdb 2.02 my model: class MyModel(models.Model): ... total = models.DecimalField(max_digits=10, decimal_places=2, null=True) ... When i run a simple query: ml = MyModel.objects.values('id', 'total').last() I got this error: AttributeError: 'float' object has no attribute 'quantize' could someone help me please ? -
Can we loop through django channel layers?
I'm using django channels. I have encountered a problem. I'm trying to loop through different room names to send messages. but I'm getting type error. I don't know if this is possible with django-channels or is it fine to use loop for sending messages in sockets my code. consummers.ProjectConsumer Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) sender = text_data_json['sender'] receiver = text_data_json['receiver'] message = text_data_json['message'] # Send message to room group username = ["admin","main"] for user in username: object = { 'sender':sender, 'receiver': user, 'message':message, } username = user self.room_name = username print("here", self.room_name) self.channel_layer.group_send( self.room_name, { 'type': 'sent', #function name as an event type 'object': object #function parameters as an event object } ) async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) error: File "/home/aa/gitCodes/clone-beru/4-multiuser_handler/backend/notifications/sockets/consumers.py", line 117, in receive await self.channel_layer.group_send(... TypeError: can not serialize 'type' object -
Failed in connecting to remote sql database using domain name instead of hardcoded remote ip adress
ALLOWED_HOSTS = ['http://xxx.xxxx.com/'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxDB', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', } tried replacing the remote ip to domain name which is in working state,django stops connecting doesnt show any error.please help. -
owl Carousel is not working after ajax success in python Django
I want to get the parent category list on the slider by clicking the main category's slider list. the second category's sider is not working when I click the main category. $('.maincategory').owlCarousel({ }); $(".box").on("click", function(){ var value= this.id.toString(); var csr =$("input[name=csrfmiddlewaretoken]").val(); debugger $.ajax({ url: 'getParentCategory', type: 'POST', data: { id: value, csrfmiddlewaretoken: csr }, success: function (response) { data = response.results AppendData(data); } }); }); function AppendData(data){ $(".secondCategory").empty(); debugger; var htmls = ''; if(data.length != 0){ for (var i = 0; i < data.length; i++) { htmls += '<div class="item eight-card-single text-center">' htmls += '<a id="{{value.id}}" class="second-category category">' htmls +='<img src="/media/uploads/products/logo.jpg">' htmls +='<h5 id="'+ data[i].name +'" class="card-title">'+ data[i].name +'</h5>' htmls +='</a>' htmls +='</div>' } $(".secondCategory").append(htmls); $('.secondCategory').owlCarousel({ }); } else { $(".secondCategory").append("No data"); } }; -
how to assign a value to new user in django
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and right now, i don't know what to do neither do i know how to implement maybe becuase i don't have much experince with django. views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') # error is showing "instance" is not access using visual studio code instance = UserMembership.objects.create(user=obj, membership=get_membership) messages.success(request, f'Account Successfully created for {username}! You can Login In Now') return redirect('userauths:login') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File … -
"return self.title</pre>" returns a syntax error django
Please bear with my ineptitude. I'm trying upgrade my skillset from simple python scripts to something closer to resembling a full stack developer. RN I am creating a simple Django todo app and am going through a basic tutorial here. https://www.geeksforgeeks.org/python-todo-webapp-using-django/ Env is setup with the following... Python==3.8.9 Django==3.2.9 django-crispy-forms==1.13.0 my models.py looks like this: from django.db import models from django.utils import timezone class Todo(models.Model): title = models.CharField(max_length=100) details = models.TextField() date = models.DateTimeField(default=timezone.now) , if I am correct in assuming this is related to CSS. I am not sure where to go from here. Can anyone help me? def __str__(self): return self.title</pre> and my forms.py looks like this from django import forms from .models import Todo class TodoForm(forms.ModelForm): class Meta: model = Todo fields = "__all__"</pre> When I execute python3 manage.py makemigrations or runserver I get the following error and am clearly unable to figure out why. File "/home/ezurel/Coding/AppleTree/AppleTree/urls.py", line 19, in <module> from todone import views File "/home/ezurel/Coding/AppleTree/todone/views.py", line 7, in <module> from .forms import TodoForm File "/home/ezurel/Coding/AppleTree/todone/forms.py", line 8 fields = "__all__"</pre> ^ SyntaxError: invalid syntax I'm stumped as to the need for the </pre> tag and to why it needs to be there and not as … -
AttributeError at / type object 'Form' has no attribute 'objects', how to fix?
AttributeError at / type object 'Form' has no attribute 'objects', I'm new to django, I'd appreciate a brief explanation views.py from django.shortcuts import render,redirect from django.contrib import messages from .forms import * def main(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): Form.objects.get_or_create( name=form.cleaned_data['name'], email=form.cleaned_data['email'], phone=form.cleaned_data['phone'] ) messages.success(request, 'Form has been submitted') return redirect('/') else: return HttpResponse("Invalid data") else: form = Form() return render(request, 'app/main.html', {'form': form}) models.py class ModelsForm(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) objects = models.Manager() forms.py from .models import ModelsForm class Form(ModelForm): class Meta: model = ModelsForm fields = '__all__'``` -
how to make multiple select checkbox with ajax and no button submit
Python 3.9 Django 3.2 I have categories and product , and through a simple form in the template I choose 1 or 2-3 checkboxes and I get the result. How to do it now via ajax and without button 'submit'. I select several product categories and each click on the checkbox is ajax and the next click on the checkbox adds the parameter to the request. it is similar to how you select several parameters in online stores. You have selected 2 parameters and received a filtered list of products I suppose that you need to intercept the sending, store one request in the cache and add a new one to this request <form method="post" id="category-box"> {% csrf_token %} <div class="form-check"> <input class="form-check-input" type="checkbox" name='category' value="{{c.name}}" > <label class="form-check-label" for="{{c.name}}"><a href="{{ c.get_absolute_url }}">{{ c.name }}</a></label> </div> {% endfor %} <button type="submit">Submit</button> </form> -
Will Django always consider an Emoji as 1 character long?
I'm making a Post Reaction model that uses emojis as reactions, and at this point I'm not mapping them to Choices, but instead inserting the utf-8 value (e.g. 😀) directly to the Database (Postgres) as a CharField instance. This made me think which value should I use to the max_length of this field. I know Rust will take emojis as 1 char long, but I'm not sure about how python or Postgres will react. -
Django Forms: How do I use a selected object from dropdown menu?
I have a functioning dropdown menu filled with some objects from a database. When a user selects one, they should be directed to the objects appropriate page. Each object is a "Workout" and each workout has "Exercises". It is working, however, I am struggling to get the appropriate 'id' from the object that has been selected by the user. Below I will provide the view, template, url, and form. view.py @login_required def routines(request): """This view will provide a dropdown list of all of the workouts of a specific user. Once one is selected, the user will hit a submit button. After submitted, a new page will show all the exercises for that workout""" if request.method == "GET": #if we have a GET response, provide a form with filled data form = RoutineForm(request.GET, user=request.user) #data needs to equal the object that was selected from the GET form data = 1 if form.is_valid(): data=form.cleaned_data("workout") form.instance.owner = request.user #make sure we have the right user form.save() return HttpResponseRedirect('routine_workouts_app:routines') context = {'form':form, 'data':data} return render(request, 'routine_workouts_app/routines.html', context) @login_required def routine(request, data): """I think this is the view that will display the information of a workout as of now. Should be similar to the workout … -
how do I create a javascript function that changes the html when a form submit button is pushed in django
I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send. I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below: <p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p> <form action="\send\" method="post"> <input type="text" name="userMessage" /> <input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" /> </form> <script> var btn = document.getElementById("sendButt"); btn.addEventListener("click", updateChat); function createMenuItem(name) { let li = document.createElement('p'); li.textContent = name; return li; } const td = document.getElementById('chatGoesHere'); td.appendChild(createMenuItem("TEST2")) function updateChat(){ const td = document.getElementById('chatGoesHere'); td.appendChild(createMenuItem("TEST3")) } </script> I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading. Thank you -
Django window.location not replacing string
I have a javascript function in a django view that is supposed to redirect the user to a different URL that contains a query parameter. When I print out the url before assigning it to window.location, it matches the url pattern as expected. However once I assign the URL to window.location, it seems to append the url to the already existing one instead of replacing it, and thus cannot find the matching url pattern. Javascript function: function downloadEvidence() { var product_review_ids = getProductReviewIDs(); if (product_review_ids === '') { window.alert("Please select at least one deployment.") return; } var url = window.location.href + "download_evidence?productReviewIDs=" + product_review_ids console.log(url); //prints: http://127.0.0.1:8000/access-review-owner/configure/new%20test%20product/download_evidence?productReviewIDs=14 window.location = url; } The url pattern it is supposed to match: urlpatterns = [ path('access-review-owner/configure/<str:product_name>/download_evidence/',views.download_evidence_view, name='download_evidence_view'), ] The view it's supposed to navigate to: @require_http_methods(['GET']) def download_evidence_view(request, product_name): product_id = request.GET.get('productReviewIDs', None) print(product_id) ''' NOTE: Package up evidence here ''' return HttpResponseRedirect(os.environ['BASE_URL']+f'access-review-owner/configure/{product_name}/download_evidence/') The url it's attempting to find when I assign the correct one to window.location: GET http://127.0.0.1:8000/access-review-owner/configure/new%20test%20product/download_evidence/access-review-owner/configure/new%20test%20product/download_evidence/ -
Proper way to construct classes - Django dartCounter project
I was recently starting to do some programming. I figured out how to use Django a couple of days ago. And now I'm trying to integrate some old Python code with it. I created a simple dartCounter. Which is quite easy in a while-loop. However for the new version I want some graphical interface, so I figured I should make some proper classes to interact with without the usage of while loops for the count mechanism. Those classes should be used in the views.py section in Django. The thing is, I think I already made it overcomplex using this method. First I created a class dart_player() class dart_player(): def __init__(self, name): self.name = name self.score = None self.leg = 0 self.thrown_scores = [] def set_start_score(self, start_score): self.score = start_score self.thrown_scores = [] def update_score(self, score): if self.score != None: self.score = self.score - score self.thrown_scores.append(score) else: print("Error score equals 'None' \n") def reverse_score(self, score): if self.score != None: self.score = self.score + score self.thrown_scores = self.thrown_scores[:-1] else: print("Error score equals 'None' \n") def update_leg(self, leg): self.leg = self.leg + leg Next I ended up creating a class dart_match() and within it, the class leg() since the leg is part of … -
Can you access variable attributes in the django template language with other variables?
Let's say I have two variables - User and Fruitlist. User is a model instance, while fruitlist is a list. {% for user in users %} <tr> <td>{{ user.title }} </td> <td>{{ user.text }} </td> {% for fruit in fruitlist %} <td>{{ user.fruit }} </td> {% endfor %} {% endfor %} I'm trying to create a table with the code above where a column is created for each fruit in fruitlist, and that column is filled with the value of an attribute user.fruit (the user model has a field for every fruit which contains a value). Why doesn't the above code work? -
"extends" and "load" in one template (django project) , is this possible . Thanks in advance
I m trying to extend from the base template the navigation and the footer and also to load the static files ,but it doesnt show me any changes when im doing it (When i remove {% extends 'index.html' %} the css is working). I tried with include and it works but its broken - the body is under the footer etc. I tried also with {% block css %} and a lot of other things , but i dont think that is the way of fixing this one.. register_user.html {% extends 'index.html' %} <head> {% load static %} <link rel="stylesheet" href="{% static 'css/register/register.css' %}"> <title>Register - Audi Our Love</title> </head> {% block content %} <h1>Register User</h1> <form method="post">{% csrf_token %} {% for field in register_form %} <p> {{ field.label_tag }} {{ field }} {% if field.help_text %} {{ field.help_text }} {% endif %} {% for error in field.errors %} <p style="color:red;">{{ error }}</p> {% endfor %} {% endfor %} <button type="submit" class="register-button">Register</button> </form> <div> <p>Already have an account ? | <a href="{% url 'login' %}">Login</a></p> </div> {% endblock %} -
Django slow admin change view with autocomplete
To speed up the admin change view I did the following: class CaseAdmin(admin.ModelAdmin): ... autocomplete_fields = ('client', ) But if I look in de source code I see there are still 1000's of options loaded. Does anyone know how to solve this? -
Stream chat room with Django
i wanted to build a chat room with Django and i've built it so far but i'm stock in one particular area, i wanted the chat room to have realtime chatting room. Currently with my code i have to refresh the page each time before the message show up if i'm logged in the another user. This is my code in model class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.body[0:50] and this is the code in my views.py def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all() participants = room.participants.all() if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room': room, 'room_messages': room_messages, 'participants': participants} return render(request, 'base/room.html', context) -
CSRF cookie not set - possibly blocked by kubernetes ingress
I use Axios in React and Django Rest Framework with dj-rest-auth. After migrating from GCP to Azure and removing the unmaintained django-rest-auth, I got some new CSRF issues. Initially I removed django-rest-auth and created my own LoginView from Django.contrib.auth.views. Noticed that this also gave the CSRF error in development. So I added dj-rest-auth, which solved my issue locally. Pushed to the AKS, but there the cookie still does not appear. I'm suspecting my ingress to be the problem, which is able to set INGRESSCOOKIE for both my backend and frontend, but no CSRF. I know there's a million tickets about this topic, my Django settings are fine, the set-cookie resopnse header is set. Also use the right axios settings to make sure that if the cookie is there, it's used for requests. The problem is really with the fact that the set-cookie is not coming through, as it is being created in Django. I use an Nginx controller with TLS on a static IP with and have my ingress defined as follows: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: basic-ingress annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubernetes.io/rewrite-target: / kubernetes.io/ingress.allow-http: "true" spec: tls: - hosts: - XXXXX secretName: tls-secret rules: - host: XXXXXXXX … -
Making Model fields for Aligner Tracking that automatically fill other fields by it's total amount and time they need to wear it
I'm trying to build a website for Aligner Tracking. In my Model file, I have length, aligner_number, and time. I want to set it up where let's say I put length (total of aligners) is 10 then my other aligner_number field would generate 10 fields going from 1-10 where each aligner that patient completes we can check off one of the aligner_numbers as complete which is also in the class Treatment. Also, time is the amount of time the patient wears the aligner so let's say they have to change it every 2 weeks. From the length and treatment_number I want it to automatically generate the same number of fields for total aligner numbers with the date being 2 weeks apart. So let's say length is 10 and the aligner_number has a list of aligner numbers 1, 2 , 3, and etc, I want each aligner_number to have a corresponding time_date 2 weeks apart for delivery. So, let's say patient start aligner 1 on November 1st, I want it to automatically generate the time fields to November 14th for Aligner 2, and November 28th for Aligner 3 and etc, so we know the patient needs to start wearing Aligner number … -
Access model field with two keys in template
I am a bit lost. It is been a while since I did some Django and I almost forgot everything about querysets and template. The app is a questionaire for comparing different vendors - hence their products. It is a questionaire with a scoring (best match) to each product. I want to access a specific element in a for loop which has two foreign keys to other classes. Here my model: Model: class Question(models.Model): questionText = models.CharField(max_length=500) class Vendor(models.Model): vendorName = models.CharField(max_length=30, unique=True) class Scoring(models.Model): score = models.IntegerField(default='0', blank=True) questionScoreForKey = models.ForeignKey(Question, null=True, related_name='scorequestion', on_delete=models.SET_NULL) vendorForKey = models.ForeignKey(Vendor, null=True, related_name='scorevendor', on_delete=models.SET_NULL) views.py def index(request): questions = Question.objects.all() vendors = Vendor.objects.all() return render(request, 'compare/index.html', {'questions': questions, 'vendors': vendors}) Template {% for ask in questions %} <tr> <td>{{ ask.questionText }} </td> {% for vend in vendors %} <td id="Vendor_{{ ask.pk }}_{{ vend.pk }}" style> {{ HERE THE SCORE OF THE QUESTION AND VENDOR }} </td> {% endfor %} </tr> {% endfor %} Both keys are existing but I have no clue how to access the score of e. g. the first question for the first vendors. Any hint appreciated. -
How to fix a mkdir error on a dockerized ap on ec2?
I have a django app based on django-cookiecutter running on an aws-ec2. The application itself built and is running ok. This application uses the django-cities-light library. When I run docker-compose -f production.yml run --rm django python manage.py cities_light which is the command to populate the database with countries/cities I get this error: INFO 2021-11-30 15:17:36,780 cities_light 1 140562076800832 Creating /usr/local/lib/python3.9/site-packages/cities_light/data Traceback (most recent call last): File "/app/manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/cities_light/management/commands/cities_light.py", line 145, in handle os.mkdir(DATA_DIR) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.9/site-packages/cities_light/data' ERROR: 1 As '/usr/local/lib/python3.9/site-packages/cities_light/data' is inside the docker I am very confused regarding what permissions I should set and to whom. If anyone could shed some light it will be much appreciated. Thank you! -
I cannot install pywallet in Ubuntu
I enter this in terminal : $ sudo pip3 install pywallet And these errors are displayed : ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-8qataqqd/sha256_e76f1676b6c24b1da2acf05fb844c2d4/setup.py'"'"'; file='"'"'/tmp/pip-install-8qataqqd/sha256_e76f1676b6c24b1da2acf05fb844c2d4/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-xidjadbh cwd: /tmp/pip-install-8qataqqd/sha256_e76f1676b6c24b1da2acf05fb844c2d4/ Complete output (121 lines): running bdist_wheel running build running build_ext building 'sha256' extension creating build creating build/temp.linux-x86_64-3.9 x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.9 -c sha256.c -o build/temp.linux-x86_64-3.9/sha256.o sha256.c: In function ‘PyInit_sha256’: sha256.c:2823:28: error: ‘PyTypeObject’ {aka ‘struct _typeobject’} has no member named ‘tp_print’ 2823 | __pyx_type_6sha256_sha256.tp_print = 0; | ^ sha256.c: In function ‘__Pyx_ParseOptionalKeywords’: sha256.c:3061:21: warning: ‘_PyUnicode_get_wstr_length’ is deprecated [-Wdeprecated-declarations] 3061 | (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : | ^ In file included from /usr/include/python3.9/unicodeobject.h:1026, from /usr/include/python3.9/Python.h:106, from sha256.c:24: /usr/include/python3.9/cpython/unicodeobject.h:446:26: note: declared here 446 | static inline Py_ssize_t _PyUnicode_get_wstr_length(PyObject *op) { | ^~~~~~~~~~~~~~~~~~~~~~~~~~ sha256.c:3061:21: warning: ‘PyUnicode_AsUnicode’ is deprecated [-Wdeprecated-declarations] 3061 | (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : | ^ In file included from /usr/include/python3.9/unicodeobject.h:1026, from /usr/include/python3.9/Python.h:106, from sha256.c:24: /usr/include/python3.9/cpython/unicodeobject.h:580:45: note: declared here 580 | Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( | ^~~~~~~~~~~~~~~~~~~ sha256.c:3061:21: warning: ‘_PyUnicode_get_wstr_length’ is deprecated [-Wdeprecated-declarations] 3061 … -
Django making tons of duplicate queries
Im working with on an ecommerce project where django is making tons of tons of duplicate queries while fetching products from database using django ORM. please find the below codes for your reference help to resolve. Thanks in advance. Product model class Product(models.Model): variations = ( ('None', 'None'), ('Size', 'Size'), ) name = models.CharField(max_length=200, unique=True) store = models.ManyToManyField(Store) slug = models.SlugField(null=True, blank=True, unique=True, max_length=500) sku = models.CharField(max_length=30, null=True) tax = models.IntegerField(null=True, blank=True) stock = models.CharField(max_length=10, null=True) variations = models.CharField(choices=variations, max_length=20) short_description = models.CharField(max_length=500, null=True) details = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) delivery_time = models.CharField(max_length=5, null=True, blank=True, verbose_name="Delivery Time") returnable = models.BooleanField(max_length=5, null=True, blank=True, verbose_name="Returnable") emi = models.BooleanField(max_length=5, null=True, blank=True, verbose_name="EMI available") image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='products') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) # This is used only for filtration color = models.ManyToManyField(Colors) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Product, self).save(*args, … -
Django with LDAP user authentication
I'm working in a Django and LDAP project. For now, with my basic code, a user can login after establishing a Connection with ldap (I'm using ldap3 library) @csrf_exempt def login_view(request): if request.method == "POST": data = json.loads(request.body.decode('utf-8')) cn = data["cn"] password = data["password"] user = Connection(server, 'cn='+cn+',ou=users,dc=syneika,dc=com', password, auto_bind=True) if user is not None: return HttpResponse('authenticated') else: return HttpResponseForbidden('wrong username or password') I am facing a problem when wanting to implement Tokens (JWT), I should Customize authentication backend in Django so I can use the authenticate() function and add tokens. I have a problem understanding the logic there, Django will save a authenticated user in the database but if we change the user password in LDAP? we can always login with the user in the database which is not convenient! Also, how can we customize Django authentication backend to login correctly using LDAP? Thank you -
Python/Django - multiple choice for ForeingKey
I am designing the models for the database that will consist of several apps. It has been decided to add a simple Document Management System to allow infinite documents to be attached to different models. This is the solution that I have thought but I don't know if it there is a better way to do it. Let's say for simplicity 3 models models.py class Contract(models.Model): .... class Invoice(models.Model): .... class Personal_record(models.Model): .... Each model can have multiple documents associated at user discretion for example: "Contract" can have 1 contract_file.pdf and 'n' amendments_to_the_contract.pdf "Invoice" is the only model that can have, in theory, an invoice.pdf per record "Personal_record" is free to the user to attach/upload any file he desires, therefore 'n' records.pdf The solution I thought of is to create another model called Documents that will store all the documents uploaded from any upload form. I would list all the links to the other models and make them blank and use a simple if/else to which type of ForeignKey update. class Documents(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE,blank=True, null=True) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE,blank=True, null=True) p_records = models.ForeignKey(Personal_record, on_delete=models.CASCADE,blank=True, null=True) .... Is there a better way to do it? Maybe having only one …