Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save data in UserProfile while doing registeration in Django?
I make the SignUpForm for registeration. The fields of the SignupForm are 'username', 'first_name', 'last_name', 'email', 'student_ID', 'CBNU_PW',. I want to get these data on the registration page and save 'student_ID', 'CBNU_PW', in UserProfile. How can I get all the data on the registration page and save 'student_ID', 'CBNU_PW', data in UserProfile? I don't know how to make this in my code. This is my code. This is view.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm from django.urls import reverse_lazy from .models import * from django.contrib import messages class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('login') # class SignUpView(CreateView): # form_class = SignUpForm # success_url = reverse_lazy('home') # template_name = 'common/register.html' def register(request): form = SignUpForm() if request.method=='POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('login') context = {'form': form} return render(request, 'common/register.html', context) from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'}) else: … -
WebSocket connection failed (Django channels)
I'm trying to establish a websocket connection, however, I'm getting this error: WebSocket connection to 'wss://oasis.yiaap.com/ws/question/aaass-bc6f6f2e-4a96-4174-a8dd-a3b8f03645a7/' failed: I think everything is set up correctly. #routes.py websocket_urlpatterns = [ #re_path(r"ws/questions/", consumers.QuestionsConsumer.as_asgi()), path("ws/question/<question_slug>/", consumers.QuestionConsumer.as_asgi()) ] #consumers.py class QuestionConsumer(AsyncJsonWebsocketConsumer): async def connect(self): #print("DEBUG") self.question_slug = self.scope['url_route']['kwargs']['question_slug'] self.room_name = self.question_slug self.room_group_name = 'question_%s' % self.room_name # In order to detect who is the owner of the room # We'll setup the user # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Check if the question exists in the database otherwise close the connection # and send a message says 'question not found' so client can act on it is_questions_exists = await questions_exists(question_slug=self.question_slug) if is_questions_exists == False: await self.send_json({"message": "question_not_found"}) await self.close() await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def disconnect(self, close_code): user_id = self.scope["client"][1] owner_user_id = cache.get(f"{self.room_name}_owner") if user_id == owner_user_id: # Check if the user is the question owner then delete the question from database await delete_question(self.question_slug) cache.delete_pattern(f"{self.room_name}_owner") # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive answer from WebSocket async def receive_json(self, content): answer = content.get('answer', None) is_owner = content.get("is_owner", None) if answer: # Send answer to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'question_answer', 'answer': answer } … -
Tagulous - Displaying Posts based on filtering of self assigned tags
I have created a posts list where users can simply create a post, upload a photo and similar to StackOverflow, they can assign "Tags" to their post to categorise their post (I am using Tagulous library to power the tags feature of my application) At the moment users can assign tags to their Post. However, what I am wanting to achieve is the following: When a user creates a Post in a specific tag, I want to filter the overall Posts view, based on the past tags they have assigned to their previous posts. E.g. If User A assigns a tag called "Winter" to their Post, after submitting their post, they will see any other Posts on their Post Feed which are relevant to the "Winter" tag. If in the future, they decide to assign one or more other tags to any future posts they create, those posts sharing the same tag name will also appear on their Post Feed. In a nutshell, for every one tag which the user self assigns to any future post, they will begin to see Posts of other users who are using the same tag within their posts. Where I am at, at the … -
unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'
I am trying to calculate the subtotal, VAT and Total for creating an invoice. I`ve got an error unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' models.py class InvoiceLine(models.Model): TAX_RATE = ( (0, '20% (VAT on Expenses)'), (1, '5% (VAT on Expenses)'), (2, 'EC Aquisitions (20%)'), (3, 'EC Aquisitions (Zero Rated)'), (4, 'Exempt Expenses'), (5, 'No VAT'), (6, 'Reverse Charge Expenses (20%)'), (7, 'Zero Rated Expenses'), ) invoice = models.ForeignKey(Invoice,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False) invoice_item = models.CharField(max_length=100, verbose_name="Line") tax_rate = models.IntegerField(choices=TAX_RATE,default=0, blank=True, null=True) total = models.CharField(max_length=250, null=True, blank=True) description = models.CharField(max_length=100, blank=True, null=True) unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, null=True, blank=True) quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, null=True, blank=True) unit_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) vat = models.CharField(max_length=250, null=True, blank=True) def subtotal(self): subtotal = Decimal(str(self.unit_price * self.quantity)) return subtotal.quantize(Decimal('0.01')) def __unicode__(self): return self.description subtotal will calculate the unit price X quantity but give me an unsupported operand type error. Then, I`ll have the total_lines and VAT by adding 20%. Can I just calculate them using? def total(self): total = Decimal(str(self.subtotal * (self.tax_rate/100)+ (self.tax_rate/100))) return total.quantize(Decimal('0.01')) -
OSError at / SavedModel file does not exist at: model.h5/{saved_model.pbtxt|saved_model.pb}
model=load_model("cat_dog_model.h5") Anybody help to overcome this error while adding a saved neural network model in Django. -
django clean field model form
it is necessary to clean the fields in views or just in forms.py? how does the clean method work in modelform? class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class BookForm(ModelForm): class Meta: model = Book fields = ['name', 'authors'] def clean_name(self): pass def create(request): if request.method == 'post': form = Bookform(request.POST) if form.is_valid(): #clean field -
__init__() takes 1 positional argument but 2 were given type error
I am currently using Django and python to create a web app to take meter readings for my company. I am receiving this error (Title) and I don't know what is causing it. I have Urls.py: urlpatterns = [ #Operational URLS path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path("",include("accounts.urls")), path('home/' , views.home, name='home'), #Complexes #AVONLEA path('avn', views.AvonleaView, name='Avonlea'), path('cavn', views.currentavonleas, name='currentAvonleas'), path('Avonleacsv', views.Avonleacsv, name='Avonleacsv'), path('meter_readings/avonlea/<int:avonleas_pk>', views.viewavonlea, name='viewavonlea' ), path('meter_readings/avonlea/<int:avonleas_pk>/delete', views.deleteavonlea, name='deleteavonlea' ), Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .forms import AvonleaForm from .models import AvonleaClass from django.contrib import messages from django.views import View #Operational def home(request): return render(request, 'meter_readings/home.html' ) # Complexes #AVONLEA # # # class AvonleaView( View): def get(self,request): created_nums= AvonleaClass.objects.all().values('unitNumber') Aprev = AvonleaClass.objects.all().order_by('-unitDateEntered') previousReading = Aprev[1].newReading # created_nums= AvonleaClass.objects.all() print(created_nums , previousReading) created_nums =[int(i['unitNumber']) for i in created_nums] print(created_nums , previousReading) form = AvonleaForm() return render(request,"meter_readings/avonlea.html",{'form':form , 'created_nums':created_nums , 'name':name, 'previousReading' : previousReading }) def post(self,request): created_nums= AvonleaClass.objects.all().values_list('unitNumber') print(created_nums) form = AvonleaForm(request.POST) if form.is_valid(): form.save() return redirect('unt-url' , name ) messages.success(request , 'creates successfully ') else: return render(request, 'meter_readings/avonlea.html', {'form': form , created_nums:created_nums }) def currentavonleas(request): avonleas = AvonleaClass.objects.all() return render(request, 'meter_readings/currentavonleas.html', {'avonleas':avonleas}) def viewavonlea(request, avonleas_pk): avonlea = get_object_or_404(AvonleaClass, pk=avonleas_pk) if request.method == 'GET': … -
Wrong STATIC_URL when trying to deploy Django React app to Heroku with AWS S3
I have set up an S3 bucket for static files. Everything is working locally, but when I try to deploy the app the STATIC_URL is always overwritten and using the static path on the same page. production.py import os from dotenv import load_dotenv from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent # Load dotenv load_dotenv() DEBUG = os.getenv('DEBUG_VALUE') SECRET_KEY = os.getenv("SECRET_KEY") USE_S3 = os.getenv('USE_S3') BUCKET_URL = os.getenv('REACT_APP_BUCKET_URL') # Server is running in production if DEBUG == 'FALSE': # HTTPS settings CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # S3 bucket config if USE_S3 == 'TRUE': MEDIA_URL = '/media/' STATIC_URL = BUCKET_URL + '/static/' MEDIA_ROOT = BUCKET_URL + '/static/images/' AWS_ACCESS_KEY_ID = os.getenv('ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = os.getenv('CUSTOM_DOMAIN') AWS_LOCATION = 'static' #AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' else: MEDIA_URL = '/media/' STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR / 'public' / 'static' / 'images') -
django formtools initial data via GET parameter
I'm using django-formtools to create a form wizard. I want to pre-fill the first part of the form using get-parameter. First I validate the GET data with a regular django form. form.py class MiniConfiguratorForm(forms.Form): width = forms.IntegerField(min_value=MIN_WIDTH, max_value=MAX_WIDTH, initial=25, label=_('width')) height = forms.IntegerField(min_value=MIN_HEIGHT, max_value=MAX_HEIGHT, initial=25, label=_('height')) amount = forms.IntegerField(min_value=MIN_QUANTITY, max_value=MAX_QUANTITY, initial=1, label=_('amount')) class ConfiguratorStep1(forms.Form): # ... width = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_WIDTH, max_value=MAX_WIDTH, initial=25, label=_('width')) height = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_HEIGHT, max_value=MAX_HEIGHT, initial=25, label=_('height')) amount = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_QUANTITY, max_value=MAX_QUANTITY, initial=1, label=_('amount')) class ConfiguratorStep2(forms.Form): name = forms.CharField(max_length=100, required=True) phone = forms.CharField(max_length=100) email = forms.EmailField(required=True) views.py class ConfiguratorWizardView(SessionWizardView): template_name = "www/configurator/configurator.html" form_list = [ConfiguratorStep1, ConfiguratorStep2] def done(self, form_list, **kwargs): return render(self.request, 'www/configurator/done.html', { 'form_data': [form.cleaned_data for form in form_list] }) def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be reset before rendering the first step """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first mini_configurator = MiniConfiguratorForm(data=request.GET) init_data = None if mini_configurator.is_valid(): init_data = { 'width': '35', 'height': '33', 'amount': '17', } print("valid") else: print("invalid haxx0r") return … -
OSError: cannot load library 'C:\Program Files\R\R-4.1.ind\R.dll': error 0x7e
I am getting an error when using openrlib.py from rpy2. The specific thing I am trying to use it to import R, but it always throws an error when trying to open R.dll. rlib = ffi.dlopen('C:\Program Files\R\R-4.1.0\bin\x64\R.dll') OSError: cannot load library 'C:\Program Files\R\R-4.1.ind\R.dll': error 0x7e Above is my VSC terminal output. I do not understand why its changing "4.1.0" to "4.1.ind" but that is definitely part of the problem. Ill link a screenshot of the code. Things I have tried: Reinstalling R Reinstalling rpy2 setting the variable that used in ffi.dlopen() to the exact path my computer stores R.dll in following some other stack overflow solutions Any help would be appreciated! Image of code segment Image of terminal output -
I want a detailed explanation of each line in Django
from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func -
User account delete in django's rest
I want create view which can deactivation user's account. when i create view and send delete request i have error - > "detail": "You do not have permission to perform this action.". i have authenticated permissionn but i am login in my account. this is code -> class DeleteAccount(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] def delete(self, request, *args, **kwargs): user=self.request.user user.delete() return Response({"result":"user delete"}) -
switching to postgresql causes "django.contrib.auth.models.User.DoesNotExist: User matching query does not exist."
I checked similar questions but I could not find a solution. I am using django-rest-framework in my project and when it was connected to sqlitedb I had no issue. But when I switched to postgresql db I am getting that error. I successfully connected to databse and I created a super user. "is_superuser" and "is_staff" are true. I am sending a delete request, which was working before. Here is its view: @api_view(['DELETE']) @permission_classes([IsAdminUser]) def deleteProduct(request,pk): user = request.user print("userrrrrr",user) product=Product.objects.get(id=pk) print("product",product) product.delete() return Response("Product deleted") print(user) and print(product) are not printing anything, I think @permission_classes([IsAdminUser]) validation is not passing. I cannot figure out why it was working before. Here is the error message: File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/home/my_desk/Documents/projects/next.js/django-server-bingology/bingologyserver/base/views/user_views.py", line 98, … -
Why widget EmailInput style doesn't apply
I'm trying to style the django forms, I could apply the class to the TextInputs with widget but for the email and password it doesn't apply. Any idea why? Also, how can I delete the text above password? The password requisites, it isn't help_text forms.py class SignupForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['email', 'first_name', 'last_name', 'password1', 'password2'] widgets = { 'email': forms.EmailInput(attrs={'class': 'forms-group__input'}), 'first_name': forms.TextInput(attrs={'class': 'forms-group__input'}), 'last_name': forms.TextInput(attrs={'class': 'forms-group__input'}), 'password1': forms.PasswordInput(attrs={'class': 'forms-group__input'}), 'password2': forms.PasswordInput(attrs={'class': 'forms-group__input'}), } forms.html <form class="forms-group__form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{ field.errors }} <br> <div class="forms-group__input-field"> <label class="forms-group__label">{{ field.label_tag }}</label><br> {{ field }}<br> {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} <div class="forms-group__button-div"><input class="button submit-button forms-group__button" type="submit" value="Update Profile"></div> </form> -
Overwrite and style Django default message
I created a form in order to change the user's password. There are messages displayed when there are errors on the form. But I would like to overwrite this. For what I found online is that I can overwrite message in 5 categories (debug, info, success, warning, error). But I think that we lose informations for example : First error example when I make a mistake on the current password. Second error example when I choose a common password. So if I change the message in the case of an error I would loose a lot of information (what is the error the current password or the new password). My question is how can I a change specific error message in django ? PS : How can I a change the language now the text is in english despite the fact that in settings there is USE_I18N = TRUE -
Why form.is_valid() is always false in UserCreationForm, Django
I'm making registration in Django. When I access to register/ page, everything shows fine and there isn't any error message. But, the user that I register doesn't save in database in Django (can't find the user on the admin page). Also, the redirect doesn't work. So, I think 'form.is_valid() is always false' is the problem. What is the problem? How can I solve this? This is view.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm from django.urls import reverse_lazy from .models import * from django.contrib import messages class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('login') # class SignUpView(CreateView): # form_class = SignUpForm # success_url = reverse_lazy('home') # template_name = 'common/register.html' def register(request): form = SignUpForm() if request.method=='POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('login') context = {'form': form} return render(request, 'common/register.html', context) from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'}) else: return render(request, … -
Django admin/ return 404
Starting development server at http://127.0.0.1:8000/ Not Found: /admin/ [30/May/2021 20:33:56] "GET /admin/ HTTP/1.1" 404 2097 project/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('marketability.mkbl_urls')), path('admin/', admin.site.urls), path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] variants path(r'admin/', admin.site.urls), and path(r'^admin/', admin.site.urls), don't works too. project/marketability/mkbl_urls.py from django.urls import path from django.views.generic.base import RedirectView, TemplateView from . import views app_name = 'marketability' handler404 = 'marketability.views.handler404' urlpatterns = [ path('', views.home, name="home"), path('<slug:cat_>/', views.page_Category_Main, name='cat'), path('<slug:cat_>/<slug:product_>', views.page_Product, name='product'), path('al_about.html', views.about, name="about"), path('al_home.html', views.home, name="home"), path('search_all.html', views.search_all, name="doorway"), path('robots.txt', TemplateView.as_view(template_name="robots.txt", content_type="text/plain")), path('sitemap.xml', TemplateView.as_view(template_name="sitemap.xml", content_type="text/xml")), path('favicon.ico', RedirectView.as_view(url='/static/marketability/favicon.ico', permanent=True)), ] project/marketability/admin.py from django.contrib import admin from .models import TxtHow, TxtRatings # Register your models here. admin.site.register(TxtHow) admin.site.register(TxtRatings) project/settings.py .... NSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'marketability', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR + '/marketability/patterns'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] .... superuser has created So, i don't see any deviations from Django Documentation. How to solve it? thks -
Django middleware to time page load speed computations
I'm trying to define a middleware to time page load speed and inject it into the context to display on my homepage. I've written this middleware and it gives me the page load time in milliseconds but I don't think it's accurate. Is there a better way of doing this? Heres the code: import time class StatsMiddleware: def __init__(self, get_response): self.get_response = get_response self.start_time = time.time() def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): duration = time.time() - self.start_time response.context_data['pageload'] = round(duration * 1000, 2) return response -
haarcascade_frontalface_deflult.xml not working properly on live Django website on cPanel
I get the haarcascade_frontalface_deflult.xml file from cPanel the file are present there but it cannot detect the face its working locally fine but when I upload it on cPanel it did not detect faces properly face_detector = cv2.CascadeClassifier('/home/khblpkn3ru9o/public_html/media/haarcascade_frontalface_default.xml') i also try this cv2.CascadeClassifier('http://theangrynerds.com/media/haarcascade_frontalface_default.xml') you can check file http://www.theangrynerds.com/media/haarcascade_frontalface_default.xml my complete module code here def hello(request): if request.method == "POST": F_name = request.POST['name'] user_video = request.FILES['vide'] videoSave = videoStore.objects.create(User=User.objects.get(id=request.user.pk) , videoFile = user_video) get_path_video = videoStore.objects.get(pk = videoSave.pk) accurate_path = "http://theangrynerds.com/media/" + str(get_path_video.videoFile) faceCount = FaceName.objects.all().count() face_id = faceCount + 1 count =0 video = cv2.VideoCapture(accurate_path) # Detect object in video stream using Haarcascade Frontal Face face_detector = cv2.CascadeClassifier('/home/khblpkn3ru9o/public_html/media/haarcascade_frontalface_default.xml') while True: # Capture video frame cc, image_frame = video.read() if cc == False: break # Convert frame to grayscale gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY) # Detect frames of different sizes, list of faces rectangles faces = face_detector.detectMultiScale(gray, 1.3, 5) # Loops for each faces for (x,y,w,h) in faces: # Crop the image frame into rectangle FaceName.objects.create(User=User.objects.get(id=request.user.pk) , name = F_name , ids = face_id) # cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2) count += 1 has = cv2.imwrite("/home/khblpkn3ru9o/public_html/media/" + str(request.user.username) + "." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w]) c = str(request.user.username)+"." … -
How can exculde the data in Django
I am trying to exclude that orders which in my orderRequest table, but it show only that orders which is in orderRequest table and exclude the others.Function get the right id's of orders but it not exclude that orders. It exclude the other orders and show that orders which already in orderRequest table View.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): allOrder = OrderProduct.objects.all() allOrd = Order.objects.all() categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') product = Product.objects.filter(category_id=categoryId) def filter_order(order): try: orderReq = order.orderRequest return orderReq except: return True filteredOrders = list(filter(filter_order, allOrd)) args = {'categories': categories, 'product': product, 'filteredOrders': filteredOrders} return render(request, self.template_name, args) Model.py class Order(models.Model): orderProduct = models.ForeignKey(OrderProduct, on_delete=models.CASCADE) created_by = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) destination = models.CharField(max_length=30) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) shipping_cost = models.IntegerField() class OrderRequest(models.Model): order_status = models.CharField(max_length=10) order = models.OneToOneField(Order, related_name='orderRequest', on_delete=models.CASCADE) HTML {% for allOrders in filteredOrders%} {{ allOrders.orderProduct.id }} {{ allOrders.orderProduct.product.name }} {{ allOrders.orderProduct.quantity }} <button><a href="{% url 'allVendor' %}?product_id={{ allOrders.orderProduct.product.id }}&orderProducts_id={{ allOrders.orderProduct.id }}">Place Order</a></button> {% endfor %} -
Wanted to eliminate the repetition in the classes created to reduce duplication
Can some one help me on how to eliminate repetition to reduce duplication score on the below classes created in the code. I needed to reduce the code to improve the coding standards no idea on how to go about it please someone help me. Wanted to eliminate the repetition in the classes created to reduce duplication class SubmissionFieldsSerializer(serializers.ModelSerializer): class Meta: model = submissionfields fields = '__all__' def update(self, instance, validated_data): for key, value in validated_data.items(): if hasattr(instance, key): if key == "email_embedd": # special case instance.email_embedd = json.dumps(value) else: setattr(instance, key, value) # instance.ef_underwriter_decision = validated_data.get('ef_underwriter_decision', # instance.ef_underwriter_decision) # instance.ef_feedback = validated_data.get('ef_feedback', instance.ef_feedback) # NBI USE CASE if instance.ef_underwriter_decision == configur.get('decisions', 'non_binding_indication'): # enquiry Log dict_obj = temp_dict() # Update Submission table based on underwriter decision submission.objects.filter(email_id=instance.email_id).update(email_status='active') submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'nbi_mail_type')) instance.email_today_mail = configur.get('mailstatus', 'nbi_mail_type') # setting email_today maio to 0 for submission fields # CR7.1 Changes (FROM COMPLETED TAB TO PROCESSED TAB) submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'nbi_mail_type')) temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_sender', 'email_subject', 'email_broker', 'email_outlook_date', 'email_today_mail', 'email_assigned_user', 'email_deleted') for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', not_avbl) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == 0: dict_obj.add('ef_obligor_name', not_avbl) else: dict_obj.add('ef_obligor_name', … -
Deadlock with concurrent Celery workers in Django
I have dozens of concurrent Celery workers creating, updating, and deleting data from various models in my Django application. I'm running into the following error: deadlock detected DETAIL: Process 3285070 waits for ShareLock on transaction 559341801; blocked by process 3285058. Process 3285058 waits for ShareLock on transaction 559341803; blocked by process 3285070. HINT: See server log for query details. And these are the blocks of code where it's throwing the error: with transaction.atomic(): for score in list_of_scores_to_update: score.save() time_delta = timezone.now() - timezone.timedelta(minutes=2) with transaction.atomic(): Score.objects.select_for_update(of=('self'), skip_locked=True).filter(checked_date__lte=time_delta).delete() How can I prevent these deadlocks by acquiring a write lock on all of the rows prior to updating them? -
post save signal only when update called
hello i have two models and a post_save signal, but my signal only when object is updated is work and when i create a new object it not work my code : class Attendance(models.Model): classroom = models.ForeignKey('Class', on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) is_present = models.BooleanField(default=False) present_time = models.DateTimeField(null=True, blank=True) def __str__(self): return self.student.username class Class(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(User) quantity = models.PositiveSmallIntegerField() start_time = models.DateTimeField() end_time = models.DateTimeField() class Meta: unique_together = ['quantity', 'course'] def __str__(self): return f'{self.quantity} / {self.course}' @receiver(post_save, sender=Class) def create_attendance(sender, instance, **kwargs): for student in instance.students.all(): try: Attendance.objects.get(classroom=instance, student=student) except Attendance.DoesNotExist: Attendance.objects.create(classroom=instance, student=student) -
sessions in django showing None
I have to use variable defined in a function in views.py in another function. For that I am making a session but when I use it in another function it is showing value as None. Views.py def foo(request): mySession = request.session.get('mySession') color = "blue" request.session['mySession'] = color def anotherfoo(request): myColor = request.session.get('mySesssion') print(myColor) as I print it always shows `"None" rather it should print "blue" -
how to use angular 12 as front end with django rest framework as backend? I want to deploy it on heroku. I am using virtual environment
I want to create search api and use Django rest framework as backend and Angular as frontend. I havent tried anything yet I am beginner in both technologies. I know how to setup angular and django separately but dont know how to use them together