Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to use whois in python but getting file not found error in windows
I am trying to use whois but getting this error: I have also installed https://docs.microsoft.com/en-us/sysinternals/downloads/whois and it is working fine in my cmd but when I try it with python it shows the above error. I have installed both python-whois and whois using the below commands but still getting the same error. pip install python-whois pip install whois -
i wanted to create a Private Route but error arose
PrivateRoute.js import { Route, Navigate } from "react-router-dom"; const PrivateRoute = ({children, ...rest})=>{ const authenticated =false; console.log('it works');//it is not showing return( <Route {...rest}>{!authenticated ? <Navigate to="/"/>: children}</Route> ) } export default PrivateRoute; App.js import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Add from './Pages/Add'; import EmployeeList from './Pages/EmployeeListAdmin/EmployeeList' import EmployeeForm from "./Pages/EmployeeListAdmin/EmployeeForm" import SharedEmployeeLayout from "./Pages/EmployeeListAdmin/SharedEmployeeLayout" import Index from './Pages/Index' import Error from './Pages/Error' import MyProfile from './Pages/MyProfile' import OrderList from './Pages/OrderList' import Cart from './Pages/CartAdmin/Carts' import SingleCart from './Pages/CartAdmin/SingleCart' import SharedCartLayout from './Pages/CartAdmin/SharedCartLayout' import Producer from './Pages/ProducerListAdmin/Producer' import ProducerForm from './Pages/ProducerListAdmin/ProducerForm' import SharedProducerLayout from './Pages/ProducerListAdmin/SharedProducerLayout' import SharedLayout from './Pages/SharedLayout' import NoPage from './Pages/NoPage' import Supplier from "./Pages/SupplierAdmin/Supplier" import SupplierForm from "./Pages/SupplierAdmin/SupplierForm" import SharedSupplierLayout from "./Pages/SupplierAdmin/SharedSupplierLayout" import Delivery from "./Pages/DeliveryAdmin/Delivery" import DeliveryForm from "./Pages/DeliveryAdmin/DeliveryForm" import SharedDeliveryLayout from "./Pages/DeliveryAdmin/SharedDeliveryLayout" import '../src/Assets/styles/App.css'; import PrivateRoute from './Helpers/PrivateRoute' // import {AuthProvider} from './Auth/AuthContect' function App() { return ( <BrowserRouter> <Routes> {/* <AuthProvider> */} <Route path="/" element={<SharedLayout />}> <Route index element={<Index />} /> <PrivateRoute path="Delivery" element={<SharedDeliveryLayout />} > <PrivateRoute index element={<Delivery />} /> <PrivateRoute path='DeliveryForm' element={<DeliveryForm />} /> </PrivateRoute> <PrivateRoute path="Supplier" element={<SharedSupplierLayout />}> <PrivateRoute index element={<Supplier />} /> <PrivateRoute path='SupplierForm' element={<SupplierForm />} /> </PrivateRoute> <PrivateRoute path="EmployeeList" element={<SharedEmployeeLayout />}> <PrivateRoute index element={<EmployeeList />} /> … -
Dimensional Models in Django
Django typically uses CRUD tables for it's data modelling. Is it possible to create a dimensional model in django? Example data for a given dimensional table could be: id start_date end_date value 1 1999-02-28 2022-01-01 VALUE1 1 2022-01-01 2022-08-18 VALUE2 1 2022-08-18 9999-12-31 VALUE3 -
How to use django_select2 with django 'choices' field option for selecting option in second dropdown based on first dropdown?
I've already looked at this answer, but it did not help since it does not feature choices option. from django.db import models class SelectCar(models.Model): BRAND= ( ('BMW','BMW') ('Mercedes','MR') ) brand = models.CharField(max_length=10, choices=BRAND, default="BMW") CAR_MODELS = ( ('X1','X1') ) -
multiple model objects saved to db even though view screens out MyModel.DoesNotExist breaking application
I am getting the following error trying to retrieve a user profile from the mongodb: New searches for user 555555555 [{'search_term': 'ibm'}, {'search_term': 'ry'}] Internal Server Error: /users/555555555 Traceback (most recent call last): File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/cchilders/projects/stocks_backend/users/views.py", line 50, in get_user_profile user = UserProfile.objects.get(user_id=user_id) File "/home/cchilders/.local/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/db/models/query.py", line 433, in get raise self.model.MultipleObjectsReturned( users.models.UserProfile.MultipleObjectsReturned: get() returned more than one UserProfile -- it returned 2! [21/Aug/2022 09:45:31] "POST /users/555555555 HTTP/1.1" 500 76920 Having multiple user profiles is application breaking and there should only be one for each user. I am also getting duplicates in another model StockInfo. my view appears to only save a new user when none exists for that user id so I'm confused users/views.py: from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json from helpers.view_functions import parse_request_body from .models import UserProfile @csrf_exempt def get_user_profile(request, user_id): if request.method == 'GET': try: user = UserProfile.objects.get(user_id=user_id) print("user found") except UserProfile.DoesNotExist: print("user does not exist exception") profile = UserProfile() profile.user_id = … -
Django app on Digitalocean takes ages to old - worker always times out -- how ti investigate and fix?
I recently deployd a small Django app on Digitalocean's app platform but for some reason the app is super slow. This is the network debug when hitting a small, static site (the view take some ms in development to execute) which doesn't even hit the db. This is the log from Digitalocean server which is basically the same for all pages I'm trying - the worker always times out. [cherry] [2022-08-21 09:53:58] 10.244.17.174 - - [21/Aug/2022:09:53:58 +0000] "GET /search/ HTTP/1.1" 200 5591 "https://cherry.trading/search/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" [cherry] [2022-08-21 09:54:29] [2022-08-21 09:54:29 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:169) [cherry] [2022-08-21 09:54:29] [2022-08-21 09:54:29 +0000] [169] [INFO] Worker exiting (pid: 169) [cherry] [2022-08-21 09:54:30] [2022-08-21 09:54:30 +0000] [177] [INFO] Booting worker with pid: 177 I'm on basic subscription with some 512 mb ram (1 CPU) -
Nginx not serving static files for Django website when using with gunicorn
I have made my first Django website and I want to deploy it on Digital ocean. I am using a $4 server option. I followed this tutorial step by step as it is. But, in the end, no CSS is being applied to the admin login page, and as they have mentioned in their tutorial, it means that static files are not being served by Nginx. I did not upload my project files as I first wanted to see if I can get the server running properly with the bare minimum. I have read almost all the answers that I can find on the internet, but just can't get Nginx to serve the static files. I am stuck on this problem for weeks now. Can someone help me, please? -
restrict django choice field on django admin per user
I have an exam like this: class Exam(BaseModel): ... STATE_CHOICES = ( (PASS, PASS), (FAILED, FAILED), (GREAT, GREAT), state = models.CharField(max_length=15, choices=STATE_CHOICES, default=PASS) ... Inside Django admin, I want the user with group X to be able to only change the state only from FAILED to PASS. and users with group Y be able to change the state from FAILED to PASS and PASS to GREAT. here is my admin.py: @admin.register(Exam) class ExamAdmin(NestedModelAdmin): list_display = ('state',) Does anyone know a solution for it? -
Why the payload is not valid. serializers.ModelSerializer | Where is problem ? | Django | views
I was writing the api for booking section. I am trying to make a management ptoject. The registration have feilds and i have to make rest api. When I am passing values from postman it is showing these error Models.py class BookingRegister(models.Model): STATUS = [('Booked','Booked'), ('InTransit','InTransit'), ('AtDestination','AtDestination'), ('Delivered','Delivered'), ('Return','Return')] PAYMENT_TYPE = [('Paid','Paid'), ('ToPay','ToPay'), ('ToBeBilled','ToBeBilled')] TRANSPORT_MODE = [('AIR','AIR'), ('ROAD','ROAD'), ('WATER','WATER')] PACKAGE_TYPE = [('TIN','TIN'), ('BOX','BOX'), ('BUNDLE','BUNDLE'), ('CARTOON','CARTOON')] TAX_PERCENTAGES = [(5,'5%'), (8,'8%'), (10,'10%'), (15,'15%'), (18,'18%')] RATE_AS_PER = [('QTY','QTY'), ('WT','WT')] id = models.AutoField(primary_key=True) #bookingDetails=models.OneToOneField(BookingRegisterDetails, on_delete=models.CASCADE) status = models.CharField(max_length=15, choices=STATUS) paymentType = models.CharField(max_length=10, choices=PAYMENT_TYPE) consignor = models.ForeignKey(Party, on_delete=models.CASCADE, related_name='consignor') consignee = models.ForeignKey(Party, on_delete=models.CASCADE, related_name='consignee') origin = models.ForeignKey(City, on_delete=models.CASCADE, related_name='origin') destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name='destination') bookingPoint = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name='bookingPoint') deliveryPoint = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name='deliveryPoint') bookingDate = models.DateField() transportMode = models.CharField(choices=TRANSPORT_MODE, default='ROAD', max_length=15) createdTime = models.DateTimeField(editable=False, default=datetime.now) updatedTime = models.DateTimeField(editable=False, default=datetime.now) packageType = models.CharField(choices=PACKAGE_TYPE, default='CARTOON', max_length=15) itemName = models.CharField(max_length=30) quantity = models.IntegerField() actualWeight = models.FloatField(default=0) grossWeight = models.FloatField(default=actualWeight) taxPercentage = models.IntegerField(choices=TAX_PERCENTAGES) rateAsPer = models.CharField(choices=RATE_AS_PER, max_length=5) rate = models.FloatField() serviceCharge = models.FloatField(default=0) bookingCharge = models.FloatField(default=0) loadingCharge = models.FloatField(default=0) unloadingCharge = models.FloatField(default=0) total = models.FloatField(default=0) def __str__(self) -> str: return str(self.id)+" "+self.status+" "+self.paymentType+" "+self.consignor+" "+self.consignee <br> views.py class BookingRegisterAPI(APIView): def get(self, request, id=None, format=None): if id: try: booking=BookingRegister.objects.get(pk=id) … -
How to avoid repeating a queryset in Django views.py
what is the best way to avoid repeating a chunk of code that is being used in more than one class view? I'm repeating these 2 lines in couple of classes moderator = ServerModerator.objects.get(user=request.user) server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag)) I've tried to create a function inside models.py like this: class Server(models.Model): ... creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='user_servers') moderators = models.ManyToManyField('ServerModerator', related_name='server') def moderator_checker(self, current_user): moderator = ServerModerator.objects.get(user=current_user) server = Server.objects.get(Q(creator=current_user) | Q(moderators=moderator),Q(tag=self.tag)) return server but this doesn't work views.py: class TagsAndFlairsView(LoginRequiredMixin, View): form_class = CreatePostTagForm form_class_2 = CreateUserTagForm def get(self, request, server_tag): ... # moderator = ServerModerator.objects.get(user=request.user) # server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag)) check = Server.moderator_checker(request.user) server_post_tags = check.post_tags.all() server_user_tags = check.user_tags.all() return render(request, 'servers/tags-flairs.html', {"server":check, "server_post_tags":server_post_tags, "server_user_tags":server_user_tags, "create_post_tag_form":create_post_tag_form, "create_user_tag_form":create_user_tag_form}) -
How can I isolate a function within a view to make it run in the background in Django?
So I deployed my very first app to Digitalocean which is super exciting but also comes with some differences to a development environment. I do have a view that calls a function to update data requested from an API that takes some 2-3 minutes. Digitalocean however terminates the worker - for good reasons - after 30 seconds, so the process is aborted. [2022-08-21 08:40:10 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:25) How can I isolate run_post_publisher() in my view such as the view is finished and the "background" process can take the time it needs? This is the view and the mentioned function run_post_publisher() def execute_post_publisher(request): company = run_post_publisher() return HttpResponse(f'New post about {company} was published') I'm not sure if there is any Django built-in tools to make this happen? -
Boolean Field Django Can't Migrate to Postgresql
Django Version 4.1 I have created migration in SQLite3 and want to change to Postgresql when i connect to Postgresql i've this error django.db.utils.ProgrammingError: cannot cast type smallint to boolean LINE 1: ...R COLUMN "isProduct" TYPE boolean USING "isProduct"::boolean this is my model from django.db import models class Item(models.Model): name = models.CharField(max_length = 150) slug = models.SlugField(unique = True, db_index=True, null=True) pic = models.URLField(max_length = 400) address = models.CharField(max_length = 150) phone = models.CharField(max_length = 15) price = models.IntegerField() original_link = models.URLField(max_length = 400) description = models.TextField(max_length = 1500) additional_desc = models.TextField(max_length = 1500,default='') material = models.TextField(max_length = 200, default = '') weight = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) weight_unit = models.CharField(max_length = 4, default = '') color = models.CharField(max_length = 50, default = '') dimension_length = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) dimension_width = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) dimension_height = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) dimension_unit = models.CharField(max_length = 4, default='') isProduct = models.BooleanField(default = True) furniture_location = models.CharField(max_length = 100, default='') def __str__(self): return self.name i've tried to change BooleanField to SmallIntegerField, PositiveSmallIntegerField, and IntegerField and the error still says the same … -
How to get different querysets in Django templates from Django views
In my blog app I want to allow unkown users to see articles, but I also want to allow logged users to see in the same page (somewhere else) their own articles; something like: YOUR ARTICLES: list (only if user is logged) ALL ARTICLES: list Note that I need to show articles based on the user logged in because the url must be this: path('<int:user_id>/', views.IndexView.as_view(), name='index'), index.html: {% if user.is_authenticated %} Your articles: <div class="container py-5"> {% if article_list %} {% for article in article_list %} <div class="container"> <div class="row"> <div class="col"> {{article.author}} </div> <div class="col"> {{article.title}} </div> <div class="col"> {{article.pub_date}} </div> <a href=" {% url 'blog_app:detail' user_id = user.id %} "> <div class="col"> Open article </div> </a> </div> </div> {% endfor %} {% else %} <b>No articles!</b> {% endif %} </div> {% endif %} views.py: class IndexView(ListView): model = Article template_name = 'blog_app/index.html' context_object_name = 'article_list' #return articles of a particular author def get_queryset(self): self.article = get_object_or_404(Article, author_id=self.kwargs['user_id']) return Article.objects.filter( author = self.article.author ) My question is: How can I get from IndexView two different querysets? One with all articles and one with articles filtered by author? Bonus question: Can I allow unkown users to reach the articles … -
Django ORM - Filter by Multiple Columns Ranges
I have a requirement to fetch the data (both i_week and i_year) for the last one year from current date. The table has the following columns. Let us call the table as temp. i_week - The week number [1,52] i_year - The year Other columns I know how to fetch the data using SQL (Postgres). This is the query: SELCT "i_week", "i_year" FROM "temp" WHERE ("i_week", "i_year") BETWEEN (1, 2021) AND (52, 2022); What I have tried so far is this: temp.objects.filter(i_week__range=(previous_week, current_week), i_year__range=(previous_year, current_year)) But this is not giving me the desired result. How can I achieve the above SQL query using Django ORM ? How can I filter the ranges of i_week and i_year at once in ORM ? -
I have to add a column permissions which is determined by columns roles and access. I'm trying to nest the if loops but there is error
The code i'm using is like this CREATE TABLE EMPLOYEE ( empId INTEGER PRIMARY KEY, username TEXT NOT NULL, userrole TEXT NOT NULL, roles TEXT NOT NULL, accesses TEXT NOT NULL ); INSERT INTO EMPLOYEE VALUES (0001, 'Clark','President', 'Admin','privileged'); INSERT INTO EMPLOYEE VALUES (0002, 'Dave','sales rep', 'Operational role','not privileged'); INSERT INTO EMPLOYEE VALUES (0003, 'Ava','finance manager', 'Managerial role','privileged'); SELECT * FROM EMPLOYEE; ALTER TABLE EMPLOYEE ADD COLUMN permissions VARCHAR; DO $do$ BEGIN IF EMPLOYEE.roles='Admin' THEN IF EMPLOYEE.accesses='privileged' THEN SET permissions = 'GRANTED'; else IF EMPLOYEE.roles='Operational role' THEN IF EMPLOYEE.accesses='not privileged' THEN SET permissions = 'GRANTED'; else IF EMPLOYEE.roles='Managerial role' THEN IF EMPLOYEE.accesses='not privileged' THEN SET permissions = 'GRANTED'; else SET permissions = 'REVOKED'; END IF; END $do$; SELECT * FROM EMPLOYEE; -
how to put the item id on console.log using add to cart button using javascript?
this is my html button for add to cart and below that is the javascript i am using to display the itemdetails id into the browser console of google chrome. {% for detail in tonerdetails %} <tr> <td>{{detail.toner_model.toner_model}}</td> <td>{{detail.issued_to.name}}</td> <td>{{detail.employee_name}}</td> <td>{{detail.employee_designation}}</td> <td>{{detail.status}}</td> <td><a href="{% url 'print_toner_issue_vouchers' detail.id %}" target="_blank" rel="noopener noreferrer" class="btn btn-info">Print Issue Voucher</a> <a href="{% url 'print_toner_sent_invoice' detail.id %}" target="_blank" rel="noopener noreferrer" class="btn btn-info">Print Invoice</a> <a data-detail="{{detail.id}}" data-action="add" class="btn btn-outline-secondary addtocart">Add to Cart</a> <a href="{% url 'edit_tonerdetails_form' detail.id %}" class="btn btn-warning">Edit</a> <a data-toggle="modal" data-target="#delete-modal{{ toner.pk }}" class="btn btn-danger">Delete</a></td> </tr> let butns=document.getElementsByClassName('addtocart') for (let i =0;i<butns.length;i++){ butns.addEventListener('click', function(){ let detailid=this.dataset.detail let action=this.dataser.action console.log(detailid) }) } -
Django all auth microsoft graph profile picture
I use django-allauth about user registration/login using user's Microsoft Graph profile. Now, I can take some standard information from Microsoft (default for all auth). Is possible to retrieve also list of profile-pictures? How can make it in allAuth? -
django orm , django models and F
I have models Class Invoice(): Class Entry(): Class InternalEntry(): invoice = models.ForeignKey(InternalInvoice) entry = models.ForeignKey(Entry) I need queryset to find entries which are not recorded as internal entry -
Django render page with context does not work
I like to re-render my page, after a document was uploaded using Djanog. I like to change context['FileName'] = 'Test' to context['FileName'] = 'Test2' in the HTML page. But it does not work and I am at a loss as to what I am doing wrong here. views.py def UploadView (request): context = {} #Generate Language Selection **context['FileName'] = 'Test'** if request.method == "POST": if not(request.FILES=={}): date_time = datetime.datetime.now() date_time = date_time.strftime('%Y%m%d_%H_%M') #uploaded_file = request.FILES["uploaded_file"] uploaded_file = request.FILES.get('file') document = Document( file_title = request.user.user_unique_key, uploaded_file = uploaded_file, date_time = date_time, ) document.save() file_path = document.uploaded_file.file.name file_name = uploaded_file.name **context['FileName']='Test2';** return render(request,"UPLOAD.html",context) return render(request, "UPLOAD.html", context) HTML <h6><font color="red">{{FileName}}</font></h6> -
Not able to construct innnerhtml in django html templates using ( for loop ) from file static/javascript/main.js
This HTML template I had code in Django templates and linked javascript from static files I am not able to use (for loop) of javascript to insert innerhtml in django html templates to add table i had written. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Split Webapp</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> </head> <body> <div class="mb-3 row"> <label for="pass1" class="col-sm-2 col-form-label">SPLIT IN:</label> <div class="col-sm-2"> <input id="payees" type="number" min=0 max=100> <button type="button" class="btn btn-info" onclick="myfunction()" id="payeesbtn">ADD</button> <div class="container my-3" id="addpayees"> </div> </div> </div> <script src="{% static 'javascript/main.js' %}" type="text/javascript"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"> </script> </body> </html> **This is javascript in static folder ** console.log("javascript is working"); function myfunction() { let add_payee = document.getElementById("payees").value; let add_payee_column = document.getElementById("addpayees"); for (let i = 0; i < add_payee; i++) { console.log("working"); add_payee_column.innerHTML += ` <div class="container my-3"> <h5>payee ${add_payee} </h5> <table> <tr> <th>Name:</th> <td><input type="text"></td> </tr> <tr> <th>Mobile:</th> <td><input type="text"></td> </tr> </table> </div>`; }; }; -
foreign key error While submitting the forms
I had created a model and it contain foreign key fields also , but while I try to submit it shows error by saying like number cannot assign to the field where foriegn key is assigned. How can I upload as name . Error picture like below picture model.py class UserReg(models.Model): username=models.ForeignKey(settings.AUTH_USER_MODEL,default=1,null=True,on_delete=models.CASCADE) Name=models.CharField(max_length=200) Date_of_Birth=models.DateField() Age=models.IntegerField() Gender=models.CharField(max_length=200, choices=GenderChoice) Phone_no=models.IntegerField() Mail=models.EmailField(unique=True) Address=models.TextField(max_length=700) District=models.ForeignKey(District,on_delete=models.CASCADE) Branch=models.ForeignKey(Branch,on_delete=models.CASCADE) Account_Type=models.CharField(max_length=200,choices=AccType) Materials=models.ManyToManyField(Materials) class District(models.Model): name=models.CharField(max_length=200) Views.py def reg(request): form = Userform(request.POST or None) if request.method == 'POST': username=request.POST.get('username') Name=request.POST.get('Name') Date_of_Birth = request.POST.get('Date_of_Birth') Age = request.POST.get('Age') Gender = request.POST.get('Gender') Phone_no = request.POST.get('Phone_no') Mail = request.POST.get('Mail') Address = request.POST.get('Address') District = request.POST.get('District') Branch = request.POST.get('Branch') Account_Type = request.POST.get('Account_Type') Materials = request.POST.get('Materials') obj=UserReg(username=username,Name=Name,Date_of_Birth=Date_of_Birth,Age=Age,Gender=Gender, Phone_no=Phone_no,Mail=Mail,Address=Address,District=District,Branch=Branch,Account_Type=Account_Type,Materials=Materials) obj.save() return redirect('/') return render(request,'registration.html',{'form':form}) -
Python Websockets handles one time use only
I want to make a python code that browsers can connect to get a video stream. Problem is that my python code handles only one time use, meaning if you open the browser it will connect to that websocket correctly, but if you refresh the page, or another client want to access a stream from in parallel it won't happen saying the port is being used (this error is server side) My code: import asyncio import websockets import cv2 import os import signal async def time1(websocket, path): while True: vid = cv2.VideoCapture('V_DRONE_097.mp4') vid.set(cv2.CAP_PROP_FPS,24) try: #v = VideoStreamWidget() #v.ops() while(vid.isOpened()): img, frame = vid.read() #frame = cv2.resize(frame, (640, 480)) encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 65] man = cv2.imencode('.jpg', frame, encode_param)[1] #sender(man) #print(len(man.tobytes())) #cv2.imshow('img',man) await websocket.send(man.tobytes()) except : pass async def main(): loop = asyncio.get_running_loop() stop = loop.create_future() #loop.add_signal_handler(signal.SIGTERM, stop.set_result, None) port = int(os.environ.get("PORT", "8585")) global stop1 async with websockets.serve(time1, "", port): await stop stop1 = False ''' async def main(): async with websockets.serve(time1, "localhost", 8585): await asyncio.Future() # run forever asyncio.run(main()) ''' if __name__ == "__main__": while True: asyncio.run(main()) I want the server to keep working even if the client (browser) refreshes the page or close it and comeback later. This is the … -
Django create user Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
I am using the Django default User model to do user registration. When I was trying to create a user I got this error message. Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. # views.py from django.contrib.auth.models import User from rest_framework import viewsets from app.serializers import UserSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' extra_kwargs = {'password': {'write_only': True, 'required': False}} def create(self, validated_data): print(validated_data) user = User.objects.create_user(**validated_data) return user # urls.py from django.urls import path, include from rest_framework import routers from app import views from rest_framework.authtoken.views import obtain_auth_token router = routers.SimpleRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('auth/', obtain_auth_token), ] urlpatterns += router.urls I only insert the user record, there is no foreign table or many-to-many relationship. Not sure why the system throws this error. Attached with the postman screenshot. -
Cross-database relationships in Django with MySQL
Is there a primer on how to develop systems that segregate auth information from other information across multiple databases using Django without foregoing FK to User in another db? Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database. Django - Cross-database relations -
Merging Django-CMS Edit and Publish Mode created two different Database entries with the same values
My CTO asked me to fix an "issue." Apparently, whenever I add any plugin in the locally run DRF-based Django CMS project, it creates two database entries. One for edit mode, and the other when I hit publish. My CTO asked to find if there were any way to dynamically merge the edit mode entry with the merge mode and vice versa when switching between those modes. Our website is very heavy. But is doing this even necessary for Django-CMS? Here is the model.py code for an example plugin. Models.py: class TechnologyVideo(ck_CMSPlugin): Video_thumb = models.ImageField(upload_to="technology_video", null=True, blank=True) video_url = models.URLField(help_text='Please enter your video url', validators=[URLValidator], null=True) # video_title = models.CharField(max_length=100, blank=True, null=True, ) # video_description = HTMLField(null=True, blank=True, configuration="VIDEO_POST_TEXT_CKEDITOR") class Meta: verbose_name = "Technology Video Model" def __unicode__(self): return f'{self.Video_thumb}' cms_plugins.py: class TechnologyVideoPlugin(CMSPluginBase): model = TechnologyVideo name = 'Technology Video Plugin' render_template = 'technology_video.html' def render(self, context, instance, placeholder): context.update({ 'Video_thumb': instance.Video_thumb, 'video_url': instance.video_url, }) context = super(TechnologyVideoPlugin, self).render(context, instance, placeholder) return context plugin_pool.register_plugin(TechnologyVideoPlugin)