Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translate Dockerfile from python-alpine to python-slim-buster (debian-based)
I am trying to improve the Dockerfile we use for deploying a Django-based app at work and first thing I would like to do is change the base image of python from alpine to slim-buster but I have to translate it to a debian-based image. I would like some suggestions on how I could translate it since I have zero to none experience with alpine. This is the original snippet from Docker. FROM python:3.8.6-alpine3.12 RUN apk update && \ apk add --virtual build-deps gcc g++ musl-dev && \ apk add postgresql-dev vim bash nginx supervisor curl && \ apk add libffi-dev && \ apk add --update npm && \ apk add git make cmake -
Chat message in Django-Channel not broadcasting
I am working with django-channels. I created a consumer to broadcast a message. The strange thing is that after opening 2 windows to see the broadcast, the below happens. The message is displayed on the last refreshed window (the number of message coincides with number of windows opened). But the message never gets to displayed on the other windows. channels==3.0.3 channels-redis==3.2.0 Django==3.2.3 Below is my consumer.py class EchoBroadcastConsumer(SyncConsumer): def websocket_connect(self, event): self.room_name = 'broadcast' self.send({ 'type': 'websocket.accept', }) async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) print(f'[{self.channel_name}] - You are connected!') def websocket_receive(self, event): print(f'[{self.channel_name}]- You are have received {event["text"]}') async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': event.get('text') } ) def websocket_message(self, event): print(f'[{self.channel_name}] - Message Sent {event["text"]}') self.send({ 'type': 'websocket.send', 'text': event.get('text') }) def websocket_disconnect(self, event): print(f'[{self.channel_name}] - You are have Disconnected') async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name) Below is my frontend (JS) const url = 'ws:127.0.0.1:8000/ws' + window.location.pathname; const ws = new WebSocket(url); ws.onopen = function(event){ console.log("Connection is Open"); } ws.onmessage = function(event){ console.log("Message is received"); const ul = document.getElementById('chat_list'); var li = document.createElement('li'); li.append(document.createTextNode(event.data)); ul.append(li); // var data = JSON.parse(event.data) //li.append(document.createTextNode( // '['+ data.username+ ']:' + data.text //)); ul.append(li); } ws.onclose = function(event){ console.log("Connection is Closed"); } ws.onerror = function(event){ console.log("Something went wrong"); } const message_form = document.getElementById('message_form'); … -
Getting Error While Creating Super user in my Django project
I AM USING PHPMYADMIN FOR DATABASE enter image description here -
Django 'NoneType' object is not callable
I try to use BeautifulSoup to clean html from class, id etc. and then save them. Clear html works fine, but when I try save this, I get: File "<console>", line 1, in <module> File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 754, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 792, in save_base force_update, using, update_fields, File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 873, in _save_table forced_update) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_update return filtered._update(values) > 0 File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 799, in _update query.add_update_fields(values) File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/subqueries.py", line 108, in add_update_fields val = val.resolve_expression(self, allow_joins=False, for_save=True) TypeError: 'NoneType' object is not callable ``` My code: @shared_task def clean_article_html(article_id): try: article = Article.objects.get(id=article_id) except ObjectDoesNotExist: pass else: html = BeautifulSoup(article.body, 'html.parser') for tag in html(): for attribute in ['class', 'id', 'name', 'style']: del tag[attribute] article.text = html article.save() Maybe someone have idea what wrong with this code. -
Netbox Plugin Development and Instalation
I am new to Netbox Plugin Development, Please guide me from scratch to create simple blank plugin. I am using Windows system with docker running in it. and Netbox is running in that Docker. I have searched a lot on Google but not found anything on it. Here is one question but i am not getting anything from it. Here is another example but it is also not working for me. Thank You -
Django context processor throw error on redirect
I'm using the following context processor to pass context to all my pages, except when the user is not logged in which case it takes him to the login page : from django.conf import settings from .models import foo from django.shortcuts import redirect def globalVar(request): if not request.session.get('user_id') is None: return {"foo": foo} else: return redirect('login') But the redirect causes an exception for which i didn't find a fix : ValueError: dictionary update sequence element #0 has length 0; 2 is required Am i not looking in the right place, or is there a way to replace redirect by something else ? -
how to add links to sticky navigation bar
I'm developing blog with django.And I add sticky navigation bar to my web site but after that I can't add the url to different menu like "Home","News","Contact".Because there already a "href" tag inside anchor tag.by the way I want load "home.html","News.html","contact.html" pages when I clik "Home","News","Contact".Anyway here is my code. <!DOCTYPE html> <html> <head> <title>Dinindu Theekshana</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background:#3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar { overflow: hidden; background-color: #333; color: #333; z-index: 9999999; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #294bc5; color: white; } .content { padding: 16px; padding-top: 50px; } .sticky { position: fixed; top: 0; left: 0; width: 100%; } .sticky + .content { padding-top: 60px; } </style> <!-- Nav bar --> <nav class="navbar … -
In Django, how to create file field database variable in a query?
I know how to create a simple query variable in views.py But I don't know what it represents. As for an instance there is a CharFiled in models.py (model name being Information) named age. And to store a single row's data in a variable one could use either var1 = Information.objects.order_by('-id')[:1] OR var2 = Information.objects.order_by('-id')[:1].get() From this what I'm understanding is that in var1 stores the queryset list and var2 stores the actual object. Please correct me if I'm wrong. Does it mean the var2 has the actual value of the age parameter from the database? If not, then var2 just point to that location? Moreover, let's say there is a FileFiled called userfile in the models.py along with age and that takes in the any file user wants to store on the DB. Let's assume the file is uploaded through the form and the whole uploading function is working just fine. Now I want to reduce the userfile into half, so for that I need to store the file's data in a variable at first. Can I do file_data = var2.userfile or file_data = var1.userfile? Again, what will be in file_data? Path to the file in DB or the … -
Localization_fields: as per Django Documentation & tutorial still gives error
I am practice on Django documentations on ModelForms and copying it as mentioned in docs still getting error Please advise what is wrong here As per Django Docs By default, the fields in a ModelForm will not localize their data. To enable localization for fields, you can use the localized_fields attribute on the Meta class. Code is as follows >>> from django.forms import ModelForm >>> from myapp.models import Author >>> class AuthorForm(ModelForm): ... class Meta: ... model = Author ... localized_fields = '__all__' If localized_fields is set to the special value '__all__', all fields will be localized. Error is as follows ile "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/forms/models.py", line 250, in __new__ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form AuthorForm needs updating. -
What is the proper way to add authentication to my django-react blog app
I have my blog app using Django in the backend and React on the front. I want that only an authenticated user can do some actions such as delete and edit articles on the front end. The front end is communicating with the backend via Restful APIs My project structure at the moment is this base-project backend blog frontend manage.py db.sqlite3 At a later stage, I plan to move the frontend to make it an independent folder. Do I have to create another Django app to deal with users or there is another way. Please share any reading materials on this that you think can help. The tutorials I see online are either building a blog or a users portal but what is the way to combine the two -
Stripe AttributeError: 'str' object has no attribute 'objects' (custom user model)
I'm trying to configure Django Stripe Subscriptions. And now trying to setup webhook to create a new customer data by below code. views.py import stripe from django.conf import settings from django.contrib.auth.models import User from subscriptions.models import StripeCustomer @csrf_exempt def stripe_webhook(request) ... #Get the user and create a new StripeCustomer user = settings.AUTH_USER_MODEL.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) print(user.username + ' just subscribed.') Traceback and Error message is below. Traceback (most recent call last): File "/home/app_admin/venv_ruling/ruling/subscriptions/views.py", line 125, in stripe_webhook user = settings.AUTH_USER_MODEL.objects.get(id=client_reference_id) AttributeError: 'str' object has no attribute 'objects' I'm following this manual to create this app https://testdriven.io/blog/django-stripe-subscriptions/ The manual specify the code below. user = User.objects.get(id=client_reference_id) but I'm using "custom user model". therefore I changed the above code to below user = settings.AUTH_USER_MODEL.objects.get(id=client_reference_id) Below is other codes. My models.py from django.conf import settings from django.db import models class StripeCustomer(models.Model): user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripeCustomerId = models.CharField(max_length=255) stripeSubscriptionId = models.CharField(max_length=255) def __str__(self): return self.user.username accounts/models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): class Meta: verbose_name_plural = 'CustomUser' My settings.py #used for django-allauth AUTH_USER_MODEL = 'accounts.CustomUser' I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. … -
Can Anyone Explain what keys are in dict of jwt when generating key
Can anyone help regarding this?? I generated a key in python using jwt using below command and stored in a variable key key = jwk.JWK.generate(kty='RSA', size=512) and when i used key.export() it returned the below dict {'d': 'Z1apo6KRMoS0xyqqTu7lEwZ7f_AON_tve42nSUkwXypMF1rDNj_xgIn9J5I4TvAisUaRYq82uZfYf76eMgj8uQ', 'dp': '4k-hSfYmT8H2zdHVFVQpBD-_w5G9ASSADgKn3F08AAs', 'dq': 'E4fXlCY6oT3yPTnOb3LvLxMtKDPmwoI-FLYbNP2L0-k', 'e': 'AQAB', 'kty': 'RSA', 'n': 'wuALgiButVPQy8bCnSkvU-QlBqYB5pk6rfwlcTr-csc8DOvPzekHJYWPjbP_ptAxSW3r5Bnpac1MDgMQKFjOtw', 'p': '8ZI61ugJ3WblKvY-JfkyWXUcdoGAWQB8B9VcfWRvLuM', 'q': 'zoPN8ItkA_0rf_XobRkjhYIdtoXyOLXCqYSU0i8etR0', 'qi': 'JhXuF6EDTrrPysGzsVhco4hpVsSHCXgS7UGZUISc2Ug'} can anyone explain what are the keys in this dict like d, dp, dq, e, n, p, q, qi Thank you in advance -
Django channels and websocket not working
I've checked all the related questions none of them helped me. I'm making a simple application where I will get JSON responses on the websocketking.com site. No matter how many times I make changes none of the tries are working. here every detail asgi.py file import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import path from home.consumers import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') ws_patterns = [ path('ws/test/', TestConsumer), ] application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(ws_patterns)), }) consumers.py file from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class TestConsumer(WebsocketConsumer): def connect(self): self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" async_to_sync(self.channel_layer.group_add)(self.room_name, self.room_group_name) self.accept() self.send(text_data=json.dumps({'status' : 'connected'})) def receive(self): pass def disconnect(self): pass These are the things I added in my settings.py file ASGI_APPLICATION = 'core.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } And here is the error I got in console WebSocket HANDSHAKING /ws/test/ [127.0.0.1:2795] Exception inside application: object.__init__() takes exactly one argument (the instance to initialize) Traceback (most recent call last): File "D:\PythonProjects\channels_project\env\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "D:\PythonProjects\channels_project\env\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "D:\PythonProjects\channels_project\env\lib\site-packages\channels\sessions.py", … -
How to Assign User Permission using action drop-down in Django Admin
I am trying to assign permission for multiple selected users through Admin Action dropdown. So select the multiple user using check box and click on action dropdown and select assign user permission and click on the go button after that it will go to the next page where I am showing all models permission related to the project. But when I selected multiple or single permission and click on the submit button then nothing is happening. admin.py class AssignUserPermissionForm(forms.ModelForm): permission = forms.ModelMultipleChoiceField(queryset= Permission.objects.all()) class Meta: model = Permission fields = ('permission',) def assign_user_permissions(modeladmin, request, queryset): if request.method == "POST": form = AssignUserPermissionForm(request.POST) if form.is_valid(): print('---form valid---------') multi_val = form.changed_data['Permission'] print(multi_val,'-------') else: form = AssignUserPermissionForm() return render(request, "admin/assign_user_permissions.html", context= {'permission_list': form}) assign_user_permissions.short_description = 'Assign User Permissions' class UserProfileAdmin(SimpleHistoryAdmin, ImportExportActionModelAdmin): # form = AssignUserPermissionForm resource_class = UserProfileExport formats = ( base_formats.CSV, base_formats.XLS, ) filter_horizontal = ('skillset',) inlines = [SampleFileAdmin,] # user_first_name() list_display = ('full_name', 'is_approved', 'is_active', 'is_fixed_pricing_fl', 'created', 'updated') list_filter = (('created', DateRangeFilter), ('updated', DateRangeFilter), ContactLinksFilter, 'is_approved', 'is_active', 'skillset') search_fields = ('user__username', 'user__email', 'user__contact_no',) raw_id_fields = ('user',) history_list_display = ["status"] actions = ['send_mail', 'reset_password', assign_user_permissions, get_user_last_work] -
Cannot resolve NoReverseMatch error in Django
I am new in Django and try to make a quick search engine, but I have this error and cannot fix it after reading Django documentation. Could anyone help me? Thanks. This is the error: Reverse for 'search' with no arguments not found. 1 pattern(s) tried: ['(?P<name>[^/]+)$'] My codes are as below: layout.html <form method="POST" action="{% url 'encyclopedia:search' %}"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit" value="Go"> </form> urls.py from django.urls import path from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.entry, name="entry"), path("<str:name>", views.search, name="search") ] views.py def search(request, searched_name): """ Deal with search engine on the left widget """ result = util.get_entry(searched_name) if result: return HttpResponseRedirect(reverse('encyclopedia:entry', args=(result))) return render(request, "encyclopedia/error.html", { "error_name": "Requested page not found" }) -
Django DetailView with custom identifier (not pk): Field 'id' expected a number but got 'XQ1wfrpiLVAkjAUL'
I am using Django 3.2 I have a model and GCBV defined as follows: class Foo(models.Model): identifier = models.CharField(max_length=16, db_index=True) # ... class FooDetailView(DetailView): model = Foo template_name = 'foo_detail.html' pk_url_kwarg = 'identifier' # TODO, need to add logic of flagged items etc. to custom Manager and use that instead queryset = Foo.objects.filter(is_public=True) # # FIXME: This is a hack, just to demo # def get_object(self, queryset=None): # objs = Foo.objects.filter(identifier=self.request.GET.get('identifier', 0)) # if objs: # return objs[0] # else: # obj = Foo() # return obj In urls.py, I have the following statement: path('foo/view/<str:identifier>/', FooDetailView.as_view(), name='foo-detail'), Why is Django expecting a number (even though I have explicitly specified a string - AND also provided a pk_url_kwarg parameter)? How do I fix this? -
Cannot send my output from views.py to template in django
what my application does is capture live images and extract some values using google vision ocr. I get data from an external python script and i want to show the output in html text field. here is my views.py template from django.shortcuts import render, render_to_response from django.http import HttpResponse from django.http import JsonResponse from .models import TemperatureRecordsF, TemperatureRecordC , BloodPressureRecord , SPO2Levels import sys import base64 from PIL import Image from subprocess import run, PIPE def button(request, *args, **kwargs): return render(request,'capturr1.html',) def external(request, *args, **kwargs): request_getdata = request.POST.get('img64',None) selected_radio = request.POST.get('radio_seleect',None) print(selected_radio) # print(request_getdata) headed, encoded = request_getdata.split(",",1) data = base64.b64decode(encoded) with open("D:/dev/django/src/OCR/media/image.png", "wb") as f: f.write(data) path = 'D:/dev/django/src/OCR/media/image.png' out = run([sys.executable,'D://dev//django//src//OCR//detect_text.py',path],shell=False,stdout=PIPE) print(out.stdout) context = { 'output' : out.stdout } return render(request,'capturr1.html',context) Here is my template capturr1.html <form class="contentarea" action="/external" method="POST" id="capture" name="capture"> {% csrf_token %} <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> <label class="form-check-label" for="inlineRadio1">Temperature °F</label> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2"> <label class="form-check-label" for="inlineRadio2">Temperature °C</label> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3"> <label class="form-check-label" for="inlineRadio3">Blood Pressure</label> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio4" value="option4"> <label class="form-check-label" for="inlineRadio4">Oxygen Saturation Levels</label><br> <video id="video">Video stream not available.</video><br> <button id="startbutton">Take photo</button> <input type="submit" value="Save" class="save" name="savebutton"/> <input type="text" />{{ output }} <canvas id="canvas" style="display: none;"><br> … -
Using tailwind with django ckeditor?
So I have a project with Tailwind and Django 3. I needed a syllabus field for the project and went with Django-ckeditor. The package worked great but after uploading the text on the RichTextField, it's rendered as normal HTML and I want it to work with a tailwind. As tailwind uses classes to convert CSS utilities, is there a way I can use the CKEditor and render the file with applied tailwind classes in the HTML? I could not find much in the docs Thanks -
DjangoModelPermissions is not working for view level permission in my API application
I have created an API and I am trying to provide permissions to the views in my API app. I have assigned users to groups with permissions in my admin portal and then I am using DjangoModelPermissions in my views so that the permissions behave according to the admin portal which is not working. When I use IsAdminUser then its working it is preventing other users to read the view. but for DjangoModelPermissions it is not working. Users and Groups in my admin group One super_user assigned to Developers groups with all permissions. One Testuser assigned to Language groups with only access to language view. The code for Model from django.db import models class Paradigm(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name # Create your models here. class Language(models.Model): name = models.CharField(max_length=50) paradigm = models.ForeignKey(Paradigm,on_delete=models.CASCADE) # this method will help us to get the actual Name insted of object name def __str__(self): return self.name class Programmer(models.Model): name = models.CharField(max_length=50) languages = models.ManyToManyField(Language) def __str__(self): return self.name The Code for view from django.shortcuts import render from rest_framework import viewsets, permissions from .models import Language, Programmer, Paradigm from .serializers import LanguageSerializer, ParadigmSerializer, ProgrammerSerializer from rest_framework.permissions import BasePermission, IsAdminUser, DjangoModelPermissions # Create your … -
Error when using elasticsearch with django
I'm trying to use elasticsearch for my django project and following this tutorial with my own model: https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#populate My model: class Product(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ) title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.TextField(max_length=255) price = models.DecimalField(max_digits=12, decimal_places=2,default=0) image=models.ImageField(blank=True) amount=models.IntegerField(default=0) minamount=models.IntegerField(default=3) slug = models.SlugField(null=False, unique=True) status=models.CharField(max_length=10,choices=STATUS) create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) rating = models.IntegerField(default=0) def __str__(self): return self.title my documents.py: # documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Product @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'products' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Product # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'title', 'keywords', 'status', 'description', ] # Ignore auto updating of Elasticsearch when a model is saved # or deleted: # ignore_signals = True # Don't perform an index refresh after every update (overrides global setting): # auto_refresh = False # Paginate the django queryset used to populate the index with the specified size # (by default it uses the database driver's default setting) # queryset_pagination = 5000 … -
Minor trouble installing mod_wsgi into venv
I thought this question would help me understand my file system and how mod_wsgi installs on my macOS (even though i am also stuck). Simply i am experimenting with django and apache. i have two different django projects (very basic tutorials) with venv's and one basic web app in each. I have pip installed mod_wsgi into one and it has added the package to the venv successfully and runs fine. When i tried the other venv it replied: - Requirement already satisfied: mod_wsgi in /Users/mjwallis/opt/anaconda3/lib/python3.7/site-packages (4.8.0) I must have installed mod_wsgi more globally prior in this case (can't remember what i did). Guess this is v basic of me to ask for help but i have been hitting a wall for some reason! Also this my first StackOverflow question! If anyone has time to reply it would be a relief!! -
How to check if an object has more than constant number of many to many field objects
I have 2 tables say "A" and "B" having ManyToMany relationship with one of the field with table "A", I have created a Model Admin from where I am creating both the tables object. I have a constraint that I have to create constant number of "B" object for each fields (relation) I have written below code but it gives an error: ValueError: “needs to have a value for field ”id“ before this many-to-many relationship can be used count = 10 class A(models.Model): field_a = models.CharField(max_length=100) class B(models.Model): field_b = models.CharField(max_length=100) fields = models.ManyToManyField(A, related_name="bs") def save(*args, **kwargs): for item in self.fields.all(): if item.bs.count() > count: raise ValidationError( "item count is exeeded" ) return super(B, self).save(*args, **kwargs) Please suggest how to handle this case. -
How can I make a separate database in django and not use the default database?
Okay, so I am a complete newbie and this might be a silly question but I couldn't find any answer related to this. I have created a login page using google authentication and it works perfectly but the problem it saves the user data directly into default database but I want it to be stored in my own mysql database. I want it to store the information that google authentication gave and store it in mysql database i.e email,name,etc . -
How to use cryptography to get private key of x509 certificate
As title, I have google many different way to get the private key from X509 certificate but unfortunately none of the solutions work for me. I have try solution from https://pyjwt.readthedocs.io/en/latest/faq.html but when I try to retrieve the private key, it give me the error message of '_Certificate' object has no attribute 'private_key' -
Django: Override SimpleListFilter get_queryset method (super(type, obj): obj must be an instance or subtype of type)
I'm trying to make a filter for users to filter them by created drafts. I'm stuck inside overriding the get_queryset. This is the error I get: super(type, obj): obj must be an instance or subtype of type What am I missing? class DraftFilter(SimpleListFilter): title = _('created drafts') parameter_name = 'user_drafts' def lookups(self, request, model_admin): return( ('has_drafts', 'Yes'), ('no_drafts', 'No'), ) def queryset(self, request, queryset): def get_drafts(status): return super().get_queryset(request).annonate( is_draft=Exists(Operation.objects.all().filter( company_id=OuterRef('active_company_id'), is_draft=status)) ) if not self.value(): return queryset if self.value().lower() == 'has_drafts': return get_drafts(True) if self.value().lower() == 'no_drafts': return get_drafts(False)