Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The best way to connect and deploy Next.js CSR React app, Django and PostgreSQL
On the frontend, I have a Next.js React app. I want to render it on the client-side and probably use SWR. On the backend, I have a Django app with a PostgreSQL database. What is the most optimal solution when it comes to connecting all of these together? How would you approach deployment of such a project (e.g. as a single app, separate apps, Docker containers)? -
Django sql error in view but not via admin
I'm getting an unsupported operand type(s) for +: 'float' and 'decimal.Decimal' error. When I debug my code in my update_account function I can see that instance.amount is <class 'float'> and a.balance is <class 'decimal.Decimal'> so the error makes sense. Now if I were to add Transaction(user=id, type='deposit', description='Venmo inc', amount=200.00) manually in my Admin page the code does not throw an error. Both types are <class 'decimal.Decimal'>. Why does adding a transaction via my Admin work but adding a transaction through my view throw an error? And how can I handle this error? Models: class Account(models.Model): user = models.CharField(max_length=30) balance = models.DecimalField(max_digits=500, decimal_places=2) class Transaction(models.Model): user = models.CharField(max_length=30) type = models.CharField(max_length=10) description = models.CharField(max_length=30) amount = models.DecimalField(max_digits=5, decimal_places=2) @receiver(post_save, sender=Transaction) def update_account(sender, instance, created, **kwargs): if created: user = instance.user a = Account.objects.get(user=user) #error occurs here a.balance = instance.amount + a.balance a.save() View: def transaction(request): id = request.user.id t = Transaction(user=id, type='deposit', description='Venmo inc', amount=200.00) t.save() return HttpResponse('Transaction Complete') -
What is the best method for overriding a nested DRF serializer so it creates an object if it doesn't exist?
I have a Django Rest Framework project that uses a nested UserSerializer throughout the app. An example would be a TicketSerializer with a nested UserSerializer for owner. I would like for any time User data is serialized that it get_or_create the User without having to explicitly do this as part of the TicketSerializer create method. I know there are probably a lot of ways to do this, so I’m trying to understand the most “correct” way. Currently, I’m think about overriding the UserSerializer init method or create a custom Validator that would handle the logic. -
how to fetch related items in django many to many relation
In the list l , I need the departments list associated with a particular employee , but it throws 'User' object has no attribute 'dep__department' class Dep(models.Model): department = models.CharField(max_length=255, blank=True, null=True) class EMP(models.Model): id = ShortUUIDField(primary_key=True, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) phone = models.CharField(max_length=50, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) dep = models.ManyToManyField(Dep) views.py l=[] users=User.objects.filter(some filter condition) for d in users: l.append(d.dep__department) -
Django - Add products to favorite list
I am building a supermarket store, using Django. I have to give user the possibility to add/remove items to/from the Favourite list. So far i have done the following models.py class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=1, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) favourites = models.ManyToManyField(User, related_name='favourites', blank=True) def __str__(self): return self.name i created favourites folder and in the folder i have: views.py def favourites(request, product_id): product = get_object_or_404(Product, pk=product_id) if product.favourites.filter(id=request.user.ide).exist(): product.favourites.remove(request.user) else: product.favourites.add(request.user) return render(request, 'favourites/product_favourite_list.html') def product_favourite_list(request): user=request.user favourite_products = user.favourites.all() context = { 'favourite_products': favourite_products } return render(request, 'favourites/product_favourite_list.html', context) urls.py urlpatterns = [ path('', views.favourites, name='favourites'), path('favourites/', views.product_favourite_list, name='product_favourite_list'), ] in product_details i have def product_detail(request, product_id): """ A view to show individual product details """ product = get_object_or_404(Product, pk=product_id) is_favourite = False if product.favourites.filter(id=request.user.id).exists(): is_favourite = True context = { 'product': product, 'is_favourite': is_favourite, } return render(request, 'products/product_detail.html', context) product_details HTML has the following links {% if is_favourite%} <a href="{% url 'product_favourite_list' id=product.id %}"> <i class="fas fa-heart fa-lg"></i> </a> {% else %} <a href="{% url 'product_favourite_list' id=product.id %}"> <i … -
Get django model query data while passing them to javascript
I'm working on a social network. I want to load the comments of each post so I make an API call to the server to fetch all the comments of the required posts. The code will make everything clear: urls.py path("comments/<int:post_id>", views.load_comments) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py def load_comments(request, post_id): """Returns the comments to index.js""" try: # Filter comments returned based on post id post = Post.objects.get(pk=post_id) comments = list(Comment.objects.filter(post=post).values()) return JsonResponse({"comments": comments}) except: return JsonResponse({"error": "Post not found", "status": 404}) index.js fetch(`/comments/${post_id}`) .then(res => res.json()) .then(res => { // Appoints the number of comments in the Modal title document.querySelector("#exampleModalLongTitle").textContent = `${res.comments.length} Comments`; res.comments.forEach(comment => { modal_body = document.querySelector(".modal-body") b = document.createElement("b"); span = document.createElement("span"); br = document.createElement("br"); span.classList.add("gray") b.textContent = comment.commented_by_id + " "; span.textContent = comment.comment; modal_body.appendChild(b); modal_body.appendChild(span); modal_body.appendChild(br); }) I can get the comment value using comment.comment in js. However, the problem arises when I convert the comments objects to list.values so now I lose the ability to get the user who posted the comment (commented_by) Any help to get the comment and commented_by values is appreciated. -
Django-Python CORS Error: Redirect is not allowed for a preflight request
estoy teniendo un error con Django a la hora de enviar una peticion desde Ajax.. Les dejo el codigo: ENVIO DESDE AJAX: $.ajax({ type: 'POST', url: urlTotal, data: data, success: function (data) { console.log(data); }, }) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] -
Matchin query does not exist Django
I'm trying to get user info from form, and show it in user profile, like real name and age and description, I did make it happen but there is a problem that if user try to update info again, old tables in database will not be removed, (maybe because i didn't make it to recognize user, i don't know how) anyway i did try to make it that with every update info old queries will be updated, but there is one problem for now, that is: UpdateInfo matching query does not exist. and this is because there is no query in database so system can't find anything for it, but i want to make it if query does not exist > create if query is exist > update here is my code: Models.py class UpdateInfo(models.Model): realname = models.CharField(max_length=100) age = models.CharField(max_length=1000) desc = models.TextField() id= models.AutoField(primary_key=True, null=False) forms.py class Info(forms.ModelForm): class Meta: model = UpdateInfo fields = ['realname' , 'age', 'desc'] and views.py def information(request): if request.POST: uinfo = Info(request.POST) b = UpdateInfo.objects.get(pk=1) if uinfo.is_valid(): form = Info.objects.filter(pk=b).update(realname=realname,age=age,desc=desc) form2 = Info(request.POST, isinstance=form) form2.save() return redirect('profiles:userprof') else: form = forms.Info() return render(request, 'info.html', {'form': form}) I've tried using try like this: … -
Django Rest Framework asking for authentication after sign in
I am able to successfully login via Token Authentication. However, when getting another API, its asking for authentication. {"detail":"Authentication credentials were not provided."} views.py class CreateQuiz(generics.ListCreateAPIView): serializer_class = QuizSerializer authentication_classes = (TokenAuthentication,) permission_classes =(IsAuthenticated,) def get_queryset(self): return somequeryset settings.py REST_FRAMEWORK ={ 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), } from datetime import timedelta REST_KNOX ={ 'USER_SERIALZIER' :'api.serializer.UserSerializer', 'TOKEN_TTL': timedelta(hours=24*7), } when I test http://127.0.0.0.1:8000/apis/v1/login/?username=xxxx.com&password=xxxx on postman, I get succcessfully authenticated and returns { "expiry": "2021-05-18T19:46:33.841420Z", "token": "f07a35897b070eabfcf1439c4495b8cede5fd9908135692e2c516127a926f2ab" } -
why mu user model throws an error like filter_horizontal
below is my django user model . as you can see i created two diffrent models and sync them on a foreign keys but cant migrate my project # accounts/models.py from django.db import models class MyUser(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) username = models.CharField(max_length=50) password = models.CharField(max_length=50) NationalID=models.IntegerField(unique=True,max_length=10) def __str__(self): return self.username class Mykeys(models.Model): userid = models.ForeignKey(MyUser,on_delete=models.CASCADE) public_key = models.TextField(unique=False) private_key = models.TextField(unique=True) def __str__(self): return self.public_key -
How to Implement Django Case Insensitive Model Field?
Django do not come with case insensitive model field so how do I make a model field case insensitive without breaking my existing codes? For example: I have a username field on my UserModel but I noticed that despite making the field unique it would still allow me to use the case variant of the same word: Example below: from django.db import models class UserModel(models.Model): username = models.CharField(max_length=16, unique=True) user1 = UserModel(username='user1') # will go through user1.save() user2 = UserModel(username='User1') # will still go through user2.save() -
What is wrong with my javascript fetch API call?
I have a javascript fetch API call made to a Django backend server const res = fetch(url, { credentials: 'include', method: 'POST', mode: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify(requestBody), }) .then((response) => response.json()) .then((responseJson) => { return responseJson.movies; }) .catch((error) => { console.error(error); }); If I output the requestBody on the console before using it in the request, it looks like follows {"add-Choice":["L"],"add-Left":["1"],"add-Right":["1"],"add-Value":["100"],"add-match":["8"],"user":["siteuser1"],"csrfmiddlewaretoken":["3K89ZvofjhIL2nZQoCcxphjmXborujsaLPn2FzlYiVmiBLODWhQQiAB5BhSXkQcF"],"add":["Submit"]} Here string "add-" is used as a form prefix on the Django side view post methode. However, on the server view side, if I print the request.POST as follow def post(self, request, *args, **kwargs): print('Post request: ', request.POST) I get the output as an empty QueryDict as follow Post request: <QueryDict: {}> Internal Server Error: /matchoffers/8 The request is being sent to the correct URL and is picked up the correct view-post methode. But it fails because the request is empty. -
Django file object always 0 bytes when uploaded from python requests
I have been trying to upload a file to django using python requests. I create the file object and verify the length, which is not 0 testfile.seek(0, os.SEEK_END) filesize = testfile.tell() I create the files object test_files = { "file": ("testsave.zip", test_save_file, "application/zip") } I put the file, and some other data r = self.session.put( f"{hello_url}/shadow_pbem/savefile_api/", files=test_files, data={"hash": test_save_file_hash, 'leader': 78}, headers=good_token_header, ) I get a 200 response, the model saves all the data correctly as expected, including a correctly named save file in /media, except the save file in /media is always 0 bytes. I put some code in the view to verify, and the file object in the view is there, but it is 0 bytes. here is the relevent part of the view. It seems to work fine, but all files are 0 bytes. class SaveFileUploadView(APIView): parser_class = (FileUploadParser,) # permission_classes = (IsAuthenticated,) def put(self, request): if "file" not in request.data: raise ParseError("Empty content") f = request.data["file"] print(f"file {f} size:{f.size}") # prints file testsave.zip size:0 # rest of view works fine... I have tried with various files and formats, also using post. Files are always 0 bytes. Any help appreciated I am going crazy.... -
Django displays twice the same message
Django displays twice the same message, even when the messages are not passed in the views.py. #login.html {% extends 'login_system/base.html' %} {% block body %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% endif %} {% endfor %} <form method="POST"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %} # views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegisterForm, LoginForm # Create your views here. def login(request): if request.method == 'POST': form = LoginForm(data=request.POST) print(request.POST) if form.is_valid(): messages.success(request, 'Successfully Logged In!') print('ok') return redirect('home_page') else: #print(form.errors.get_json_data()) if form.errors: for error in form.errors.get_json_data()['__all__']: messages.error(request, error['message']) else: messages.error(request, 'Something went wrong. Please try again.') print('nie ok') else: form = LoginForm() return render(request, 'login_system/login.html', {'form': form}) This code renders error message twice for me. One is from the views.py, Second I do not know. The base.html file can look like this <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block body %} {% endblock %} </body>[![enter image description here][1]][1] </html> And I can delete sending message from the views.py and the nonstyled version still is rendered. Why … -
Python-Django: How to list what is the specific database used of a specific application
I'm currently handling a existing project and just want to have an enhance on one of its specific application. There is a list of Databases in the settings and currently hard to find what application 1 database use. For example I have 5 Application and in the settings I have 10 Databases. I just want application 1 to be enhance/developed and the rest of the app not included when I migrate. Is there anyway that I just going to list what application 1 database used? So that the listed databases that application 1 use is the only databases that I'm going to include to the settings. Since I just going to have the databases limitedly copy to a dev server not the whole prod server. -
Deploy ML Model GCP / Django at scale, how to manage session?
I have build my model (dump file), but I need to deploy it for some users (maybe 10 for the first time). This is a chatbot, but: Every message linking to the previous message (Hello how can I help you?....I need tips for that.... Ok which tips??...) This is a web app, the first architecture that I think is to use: Flask Rest / FastAPI to deploy model as an API in cloud run (GCP) I'am using Django REST for the web back-end side, so, I would like to call the ML Model rest api in the django part. So, the ideal pattern is every users can access to a dedicated chatbot (ML Model). from fastapi import FastAPI app = FastAPI() MODEL="./model/mdel.dump" ... -
How django drop column in SQLite
Don't be confused. I am not asking how to drop column in Django. My question is what Django actually does to drop a column from a SQLite database. Recently i came across an article that says you can't drop columns in SQLite database. So you have to drop the table and recreate it. And its quite strange that if SQLite doesn't support that then how Django is doing that? Is it doing this? -
Handling multiple GET variables with Django
I have a view template that has multiple forms that can be handled by get data. Such as a search function, a number of entries per page dropdown, and a pagination. I was wondering how I could go about having all of these work together without overwriting the other, for example: www.website.com/account/?entries_per_page=5 This could be the url the user is currently on but lets say they search for "pineapple", I would like for it to goto: www.website.com/account/?entries_per_page=5&search=pineapple instead of, www.website.com/account/?search=pineapple but also we have to keep in mind the page the user is on unless they do a new search: www.website.com/account/?entries_per_page=5&search=pineapple&page=2 or www.website.com/account/?search=pineapple&page=2 I hope this isn't confusing, I really have been stuck on this and have not been able to figure out what to do. -
AttributeError at /cars/add_car 'int' object has no attribute 'get'
I want to add a Car to my database by using html inputs instead of forms. But when I run the code I get this error. I am new to django so I couldn't understand the similar problems that people had. AttributeError at /cars/add_car 'int' object has no attribute 'get' My full Traceback output Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cars/add_car Django Version: 3.1.7 Python Version: 3.9.0 Installed Applications: ['cars.apps.CarsConfig', 'pages.apps.PagesConfig', 'accounts.apps.AccountsConfig', 'contact.apps.ContactConfig', 'houses.apps.HousesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'django.contrib.humanize', 'django.contrib.sites'] Installed 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'] Traceback (most recent call last): File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /cars/add_car Exception Value: 'int' object has no attribute 'get' My views.py def add_car(request): if request.method == 'POST': user_id = request.POST['user_id'] brand = request.POST['brand'] status_of_car = request.POST['status_of_car'] city = request.POST['city'] ilce = request.POST['ilce'] e_mail = request.POST['e_mail'] phone_number = request.POST['phone_number'] car_title = request.POST['car_title'] description = request.POST['description'] price = request.POST['price'] serial = request.POST['serial'] color = request.POST['color'] model = request.POST['model'] year = request.POST['year'] condition = request.POST['condition'] body_style = request.POST['body_style'] engine = request.POST['engine'] transmission … -
Why my Django 3.2 admin CSS is not working
I am really really frustrated being failed to find the issue. My django 3.2 admin is looking like without CSS only HTML. I am new to django. I don't know what happened. I have collected static files(CSS, Js, etc.) into the static folder of the project by this command: python manage.py collectstatic I also used whitenoise package to manage this stuff. But failed to do as a beginner. I need help please with the 3.2 version. Any help is really really appreciated. enter image description here enter image description here Here is my settings.py of the project """ Django settings for mac project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6r-t8omh%(8(lxk1divtd2vb(f7@r&vq7n4#v9wx%4g+z9&6v3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'shop.apps.ShopConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Django serializing json
I'm building an API using django and I have come across a problem. I have a UserDetail model that has a foreing key to a User model. class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=200, default="", blank=True) I want to serialize the information of User and the information of UserDetails in one json and this is what I'm currently doing: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') class DetailSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = UserDetail fields = ('user', 'about',) Right now I obtain this: { "user": { "username": "julia", "first_name": "antonia", "last_name": "uri", "email": "as¡¡test@test.test" }, "about": "" } But I want to obtain the information of UserDetail from User, not the other way around (like I'm currently doing) so that I get the information like this: { "username": "julia", "first_name": "antonia", "last_name": "uri", "email": "test@test.test", "details": { "about": "" } } I would really appreciate if someone could tell me what I'm doing wrong. Thank you! -
type object '...' has no attribute 'objects'
In models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Espresso(models.Model): employee = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_esp_log") time = models.DateTimeField(auto_now_add=True, blank=True) water_temp = models.DecimalField(max_digits=3, decimal_places=1) water_TDS = models.DecimalField(max_digits=3, decimal_places=2) name = models.CharField(max_length=2, choices=ESPRESSO_TYPES, default= ESPRESSO_TYPES[0][1]) batch_number = models.DecimalField(max_digits=4, decimal_places=0) dry = models.DecimalField(max_digits=4, decimal_places=2) wet = models.IntegerField() def __str__(self): return f"Log added on {self.time} by {self.employee}" In views.py the 'create_espresso' route attempts to create a new log as follows: def create_espresso(request): if request.method == "GET": return render(request, "score_sheet/espresso.html", {"form": Espresso()}) else: form = Espresso(request.POST) user = User.objects.get(username=request.user) if form.is_valid(): espresso = form.save(commit=False) espresso.employee = user espresso.save() espressos = Espresso.objects.all() return render(request, "score_sheet/index.html", { "espressos": espressos, "message": "Log added" }) else: return render(request, "score_sheet/espresso.html", {"form": form}) Also, here's the form POSTING to the view: {% block body %} <form action="{% url 'create_espresso' %}" method="POST"> {% csrf_token %} {{ form.as_table }} <button class="btn btn-success">Log</button> </form> {% endblock %} On submitting the form Django returns the following: type object 'Espresso' has no attribute 'objects' Here's the stacktrace in case it's needed: Internal Server Error: /create_espresso Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
Is there anyway to reduce the bitrate of cv2.VideoWriter live camera record video?
I have a python project that reads frames from a ip_camera and writes it in a .avi video, but its size is becomes too large for example a 1 min record has a size about 200 MB. I want to reduce the video bitrate to reduce the size at same time that the video is being written. I tried so many ways but none of them worked out. Here is my code: import os from threading import Thread import cv2 class VideoCamera(object): def __init__(self, src=''): self.capture = cv2.VideoCapture(src) self.status = False self.frame = self.capture.read() self.frame_width = int(self.capture.get(3)) self.frame_height = int(self.capture.get(4)) self.record_date = record_date self.camera_id = camera_id self.codec = cv2.VideoWriter_fourcc(*'MJPG') self.video_name = "video.avi" self.output_video = cv2.VideoWriter( self.video_name, self.codec, 5, (self.frame_width, self.frame_height)) self.stream_thread = Thread(target=self.update, args=()) self.record_thread = Thread(target=self.record, args=()) self.stream_thread.daemon = True self.stream_thread.start() def update(self): while True: if self.capture.isOpened(): (self.status, self.frame) = self.capture.read() def record(self): print('schedule') while True: print('stop recording') self.capture.release() self.output_video.release() cv2.destroyAllWindows() break try: if self.status: self.output_video.write(self.frame) frame_count += 1 except AttributeError: pass def start_recording(self): self.record_thread.start() if __name__ == '__main__': cam = VideoCamera('rtsp://<username>:<password>@<camera_ip>:<camera_port>') cam.start_recording() -
In Django I want to retrieve the selected file name the file is in my media folder i want to fetch it and display it in html
This is my html code for update the form I have the uploaded file through a html form and the pdf file is getting stored in my media folder and the file name in database, so like the text fields I also want to retrieve the selected file from the media folder the value ="{{i.cv}}" is not working like I did it in text fields so basically I have two html one is for filling up where there is also file field am uploading pdf files in it and it is storing in media folder another html for updating the data in there the upload cv does not select any file what's the solution for this. this is my html <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black">Upload CV</label></br> <input type="file" name="cv" id="cv1" value ="{{i.cv}}"> </div> </div> here is models.py class ApplyForm(models.Model): cv = models.FileField(upload_to='') this is views.py def update(request, id): i.cv = request.FILES['cv'] I just want the file to be selected during edit I am uploading pdf files -
How to organize Caching in Django?
I'm trying to figure out how to properly organize caching. There are actually two questions. Is it okay to implement caching like this? Perhaps there is a better option? class PostsListView(ListView): template_name = 'pages/post_list.html' def get_queryset(self): posts_list_qs = cache.get('posts_list_qs') if not posts_list_qs: posts_list_qs = get_all_posts() cache.set('posts_list_qs', posts_list_qs) return posts_list_qs What is the best way to invalidate this cache? What if I have a dozen of views / asynchronous functions, etc that require data from Posts. Just listing all the keys in signals like this? Should be a better way I think...And what if I need to use 'prefetch related'(inner join) for some request to database? I even need to repeat cache.delete(key) in signals for some other models. @receiver(post_save, sender=Post) def post_post_save(sender, instance, created, *args, **kwargs): cache.delete('posts_list_qs') cache.delete('posts_data_for_api_qs') cache.delete('posts_data_for_views_qs') cache.delete('posts_data_for_email_sending_qs') Please, advise me about how to organize work with the cache in the best way!?