Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Single-query get_or_create in Django and Postgres
Currently Django performs get_or_create as a series of separate two calls: 1. try get 2. perform create if the DoesNotExist exception was thrown This can lead to IntegrityError exception being raised if the instance was created right after the DoesNotExist exception was thrown. Is there any existing solution that allows to swap current django code for a postgres-specific single-query get_or_create? No problem if the solution only works with postgres as the db backend. Bonus points if it allows async aget_or_create as well. I know this should be possible on posgres as in the accepted answer in this SO question: Write a Postgres Get or Create SQL Query But I want to look for existing solutions before customising the calls in my code one by one. -
Django Ajax Form Upload with Image
I am using Django + Ajax, and i'm trying to send a POST request to upload a form with an image. However, i still get an error KeyError: 'file' HTML form (notice i've added enctype="multipart/form-data"): <form id="addProduct" method="post" enctype="multipart/form-data"> <label class="form-label required-field" for="file">Image</label> <input class='form-control' id='file' name="file" type="file" accept="image/*" required/> </form> Javascript using AJAX requests: $("#addProduct").on("submit", function (e) { e.preventDefault() var data = new FormData(this); $.ajax({ url: '/admin/product/add/', data: data, type: 'post', success: function (response) { var result = response.result console.log(result) if (result == false) { alert("Add product failed") } else { alert("Add product successfully") } }, cache: false, contentType: false, processData: false }) } Django View - views.py: class ProductAddPage(View): def post(self, request): img = request.FILES['file'] try: #further processing except: traceback.print_exc() return JsonResponse({"result":False}, status=200, safe=False) return JsonResponse({"result":True}, status=200, safe=False) Traceback: Internal Server Error: /admin/product/add/ Traceback (most recent call last): File "D:\Codes\Django\env\lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Codes\Django\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Codes\Django\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Codes\Django\env\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "D:\Codes\Django\env\lib\site-packages\django\contrib\auth\mixins.py", line 73, in … -
Django: Object of type QuerySet is not JSON serializable
I am trying to remove items from cart using Jquery and Django, i have written the logic to do this but i keep getting this errror that says Object of type QuerySet is not JSON serializable, i can seem to know what the problem is because i have tried converting the code below to list using list() method in django and also values() but it still does not work as expected. views.py def RemoveWishlist(request): pid = request.GET['id'] wishlist = Wishlist.objects.filter(user=request.user) wishlist_d = Wishlist.objects.get(id=pid) delete_product = wishlist_d.delete() context = { "bool":True, "wishlist":wishlist } t = render_to_string('core/async/wishlist-list.html', context) return JsonResponse({'data':t,'wishlist':wishlist}) function.js $(document).on("click", ".delete-wishlist-product", function(){ let this_val = $(this) let product_id = $(this).attr("data-wishlist-product") console.log(this_val); console.log(product_id); $.ajax({ url: "/remove-wishlist", data: { "id": product_id }, dataType: "json", beforeSend: function(){ console.log("Deleting..."); }, success: function(res){ $("#wishlist-list").html(res.data) } }) }) wishlist-list.html {% for w in wishlist %} {{w.product.title}} {% endfor %} traceback Internal Server Error: /remove-wishlist/ Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Destiny\Desktop\E-commerce\ecomprj\core\views.py", line 453, in RemoveWishlist return JsonResponse({'data':t,'wishlist':wishlist}) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\response.py", line 603, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 234, in dumps return cls( … -
staticfiles.W004 Error, The directory '/app/static' in the STATICFILES_DIRS setting does not exist. Postgres tables are 0,
django project deployment on heroku was successful https://ddesigner.herokuapp.com/ "heroku run python collectstatic" fails with following error ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. 1395 static files copied to '/app/staticfiles'. "heroku run python makemigrations" also gives same error although new migrations are made ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. "heroku run python migrate" also gives same error and I see that migrations are applied (as displayed) but not actually. because postgres tables in heroku are zero. Please help me to fix this issue. I have tried removing STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] and also by changing STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'static') but the error is same. -
How do I prefill django-simple-history HistoricalRecords with pre-existing admin model history?
I have a model with pre-existing history When I switch my admin from the Django default admin.ModelAdmin to django-simple-history simple_history.admin.SimpleHistoryAdmin I lose this history Note that this history is only lost from the user's perspective, switching back to ModelAdmin returns the history. Is it possible to prefill django-simple-history with prior history, or if not, to show the two alongside one another in the admin? -
first product name repeting to all others django eccomerce
hii i am newbie here creating a eccomerce website no errors showing in during template rendering but the problem is my first product name is repeting to all other products views.py def product_view(request,cate_slug,prod_slug): if(Category.objects.filter(slug=cate_slug, status=0)): if(Products.objects.filter(slug=prod_slug, status=0)): product = Products.objects.filter(slug=prod_slug, status=0).first() else: messages.warning(request,"product not found") return redirect("collection") else: messages.error(request,"something went wrong") return redirect("collection") return render(request,"product_view.html",{'product':product}) and i found an error when i remove first() from product its not showing product names but if i am not removing first() its showing first product name to all other remaning products i really stcuked this anyone help me please i want to display coorect name for every products here is repeting same name to all other name because of first() function i stucked this into 5 hours any one help me please -
google_link,google_text = google(result) make cannot unpack non-iterable NoneType object djanog BeautifulSoup
i try to make search google with BeautifulSoup in socialnetwork django site project i download it as open source and when i try to make that i receve a error message cannot unpack non-iterable NoneType object thats search.py import requests from bs4 import BeautifulSoup done def google(s): links = [] text = [] USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' headers = {"user-agent": USER_AGENT} r=None if r is not None : r = requests.get("https://www.google.com/search?q=" + s, headers=headers) soup = BeautifulSoup(r.content, "html.parser") for g in soup.find_all('div', class_='yuRUbf'): a = g.find('a') t = g.find('h3') links.append(a.get('href')) text.append(t.text) return links, text and thats the view.py def results(request): if request.method == "POST": result = request.POST.get('search') google_link,google_text = google(result) google_data = zip(google_link,google_text) if result == '': return redirect('Home') else: return render(request,'results.html',{'google': google_data }) and thats a template {% for i,j in google %} <a href="{{ i }}" class="btn mt-3 w-100 lg-12 md-12">{{ j }}</a><br> {% endfor %} i reseve the message cannot unpack non-iterable NoneType object for google_link,google_text = google(result) -
Django _id in FK Model
I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have 2 tables, Foos and Bars. foo_id 1 2 bar_id | foo_id (FK) 1 |1 2 |2 Bars model: foo = models.ForeignKey('Foos', on_delete=models.CASCADE) The Django Model changes de 'foo_id' FK into 'foo' only. There is a way to keep the FK with the '_id' suffix? -
Why am i getting TemplateDoesNotExist at /rapport/?
i would like to view my home page/ index view but i keep getting this error, what do i need to do to get rid of this error message below? Any help would be appreciated. Here is the error message: TemplateDoesNotExist at /rapport/ rapport/index.html, rapport/description_list.html Request Method: GET Request URL: http://127.0.0.1:8000/rapport/ Django Version: 4.0.4 Exception Type: TemplateDoesNotExist Exception Value: rapport/index.html, rapport/description_list.html Exception Location: C:\Users\sbyeg\anaconda3\envs\new_env\lib\site-packages\django\template\loader.py, line 47, in select_template Python Executable: C:\Users\sbyeg\anaconda3\envs\new_env\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\sbyeg\\django_projects\\rship', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\python38.zip', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\DLLs', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32\\lib', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages\\Pythonwin', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages\\win32', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages\\win32\\lib', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages\\Pythonwin'] Server time: Mon, 07 Nov 2022 12:32:56 +0300 Here is my code: views.py from django.shortcuts import render from django.urls import reverse from django.views import generic from .models import Description # Create your views here. class IndexView(generic.ListView): template_name = 'rapport/index.html' context_object_name = 'description_list' def get_queryset(self): """Return the last five keyed entries""" return Description.objects.order_by('-event_date')[:5] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), index.html template {% extends "base_generic.html" %} {% block content %} <h1>Description List</h1> <ul> {% if description_list %} {% for description in description_list %} <li> <a href="{{ description.get_absolute_url }}">{{ description.title }}</a> </li> {% endfor %} </ul> {% else %} <p>There are no entries in the … -
Can someone please suggest me that how can I print the output in my desired format using nested serializers?
I am trying to send messages using django-rest framework.I have created serializers for both user and message.I am using django default user model for storing user's details. I am pasting my model and serializers here: class MessageModel(models.Model): message = models.CharField(max_length=100) created_at = models.DateTimeField(default=now) updated_at = models.DateTimeField(default=now) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') class UserSerializer(ModelSerializer): class Meta: model = get_user_model() fields = ['id','username','email'] class MessageSerializer(ModelSerializer): created_by = UserSerializer(read_only=True) class Meta: model = MessageModel fields = ['id','message', 'created_at', 'updated_at','user','created_by'] View : class MessageViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] queryset = MessageModel.objects.all() serializer_class = MessageSerializer After creating message,I am getting response like below: { "id": 6, "message": "Lorem ipsum", "created_at": "2022-11-07T09:21:19.492219Z", "updated_at": "2022-11-07T09:21:19.492237Z", "user": 2 } but my output should looks like in below format,everytime when a new message is created : { "id": 102, "message": "Lorem ipsum", "created_at": "created time in UTC", "updated_at": "last updated time in UTC", "created_by": { "id": 3, "username": "testuser", "email": "test@mail.com", } } In case of any error, return the error message. Thank you in advance. -
Change the api's documentation in swagger
I want to use swagger for my python-Django project and I want to documente my api, I'm using the file schema.yml and even if I edit it nothing change in my swagger interface I don't know where's the problem. Any help is highly appreciated. This is my schema.yml : openapi: 3.0.3 info: title: My documentation version: 0.0.0 paths: /add-nlptemplate: post: operationId: add_nlptemplate_create .... And this is my urls.py : from django.contrib import admin from django.urls import path, include from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView urlpatterns = [ path('', include('ocr.urls')), path('api/schema/', SpectacularAPIView.as_view(), name='schema'), path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), ] I think the problem is in the second path because it always return the default schema.yml and not the edited one. -
JS: the use of edatagrid
I have problem in using edatagrid. [] The red area is a select, the yellow area is *table *by edatagrid. I want to refresh the content of the table when I change the selected value of the select. I attempted to separate the table from the whole page. When I change the selected value, send a ajax post request to get new data. But the result was the table's style was not like before, and the content of the table was not get refreshed. Like this, [] Here is the code. The whole page:test_plan.html {% extends 'base.html' %} {% load static %} {% block title %} NRLabLims - 测试管理 {% endblock %} {#控制表格的cs操作#} {% block css %} <link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css"> <link href="{% static 'css/sb-admin-2.min.css'%}" rel="stylesheet"> {% endblock %} {% block js %} <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.edatagrid.js"></script> <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %} "></script> <script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'js/demo/datatables-demo.js' %}"></script> {% endblock %} <div> {% block content %} <div class="container-fluid"> <!-- 页头 --> <h1 class="h3 mb-2 text-gray-800">测试管理</h1> <a class="mb-4">测试管理包含<a href="/lab/test/plan">test plan</a>、<a href="/lab/test/initial">原始记录单</a>、<a href="/lab/test/record">时间记录</a>、<a href="/lab/test/problem">错误记录</a>、<a … -
Checked = true not working together with other events on same element
I'm using Django inline formsets and trying to use the delete checkbox dynamically with Javascript. Everything works as it is supposed to, however the checked = true property (although showing true in the console) won't check the box as long as updateSunForm() and totalForms.setAttribute(...) are present. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <form id="all-add-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> {{ sun_bool.sunday|as_crispy_field }} {{ sunday_formset.management_form }} {% for sun_form in sunday_formset %} {% for hidden in sun_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="sun_time_slot_form"> {{ sun_form }} <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete This Sunday Timeslot </button> </div> {% endfor %} <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/> </form> <script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script> </body> </html> {% endblock content %} const sunForm = document.getElementsByClassName('sun_time_slot_form'); const mainForm = document.querySelector('#all-add-form'); const addSunBtn = document.querySelector("#add-sun-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("#id_id_sunday_formset-TOTAL_FORMS"); let formCount = sunForm.length - 1; addSunBtn.addEventListener('click', function (e) { e.preventDefault(); const newSunForm = sunForm[0].cloneNode(true); const formRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g'); formCount++; newSunForm.innerHTML = newSunForm.innerHTML.replace(formRegex, `id_sunday_formset-${formCount}-`); … -
How does Django channels utilise rooms? is it good practice to always create a room
I have written this code in which a client sends continous messages, could anyone help me understand what does the room do and what happens If I remove the room? class ResrvationEventProducer(AsyncWebsocketConsumer): GROUP_NAME = "rsv_event" async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = self.GROUP_NAME + "_" + self.room_name await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() await self.send_message('connected to producer socket successfully') async def receive(self, text_data): try: json_payload = json.loads(text_data) logging.info(payload) except Exception as e: traceback.print_exc() logging.error('An error occurred while reading text from producer socket') -
products not showing in product view page django
i created a function to view products in products view page i tried so many times but cant find any one help me please here is my code views.py def product_view(request,cate_slug,prod_slug): if (Category.objects.filter(slug=cate_slug, status=0)): if (Products.objects.filter(slug=prod_slug, status=0)): product = Products.objects.filter(slug=prod_slug, status=0) contex = { 'product':product, } else: messages.warning(request,"product not found") return redirect("collection") else: messages.error(request,"something went wrong") return redirect("collection") return render(request,"product_view.html",contex) urls.py path('collection/str:cate_slug/str:prod_slug',views.product_view,name="product"), product view.html {% extends 'auth.html' %} {% load static %} {% block content %} {{ products.name }} {% endblock %} i just want to see product detils in product view html page any one help me because i am new to django -
Django - getting properly formatted decimals in forms (+crispy)?
I have the following model: class Probe(models.Model): name = models.CharField("Probe name", max_length=200, blank=True, null=True) order = models.IntegerField("ordering", default=1) digits = models.IntegerField("trailing zeroes", null=True, blank=True, default=5) class ProbeInst(models.Model): probe = models.ForeignKey(Probe, on_delete=models.CASCADE, null=True, verbose_name="probe") value = models.DecimalField("Value of probe", max_digits=10, decimal_places=5, null=True, blank=True) I am trying to display the entry form with ModelForm and CrispyForms, which will display the necessary number of trailing zeroes according to digits field.. However when i see the actual form - i get something like this.. Basically when i enter "2" - i get "2.00000", but when i enter "81.4" - i get "81,4" for some reason... I have tried overriding the modelform like this class ProbeEntryForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'instance' in kwargs: step = 1 / 10 ** kwargs['instance'].probe.digits super(ProbeEntryForm, self).__init__(*args, **kwargs) self.fields['value'].decimal_places = kwargs['instance'].probe.digits self.fields['value'].widget = forms.NumberInput( attrs={'min': 0, 'placeholder': "Значение", 'step': step, }) self.fields['textvalue'].widget = forms.HiddenInput() But after saving the form - i still have this float styled values displayed like "81,4" I want to show all values with fixed number of tralining zeroes - like "81.40000" and "2.00000 Can someone please elaborate? -
How to get transaction information from etherscan site from a specific address using Django rest framework?
I want to know that how can I connect models views and templates to show the transaction information like "from","to","timestamp","hashaddress" Just want the implementation idea. -
401 error drf django when enable withCredentials in axios
I use NextJs and Axios to request after login, I save the cookie in NextJs : export default function handler( req: CustomeNextApiRequest, res: NextApiResponse<Data> ) { res.setHeader( "Set-Cookie", cookie.serialize("Token", req.body?.access_token, { httpOnly: true, maxAge: 60 * 60 * 24, sameSite: "lax", path: "/" // domain : '.' // secure : }) ) res.status(200).json({ status: 'success' }) } When I enable "withCredentials" in Axios: export const callApi = (url?: string) => { const instanse = axios.create({ baseURL: url || "/api/v1/", timeout: 20000, withCredentials:true }); return instanse; } After, When I request something API on another page, I receive 401 from drf Django. My Config Django: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'JWT_AUTH_HEADER_PREFIX': 'Token', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=60), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ], 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 2, 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } CORS_ALLOW_ALL_ORIGINS = … -
RTSP on Django using OpenCV
I need to stream a surveillance camera onto a Django based website. I found a tutorial on Youtube but it is very simple. Down below is my code: from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 # Create your views here. @gzip.gzip_page def Home(request): try: cam = videoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, 'index.html') # Video Capture class videoCamera(object): video = cv2.VideoCapture("[user]:[password]@rtsp://[ip-address]:554/sub") while True: _, frame = video.read() cv2.imshow("RTSP", frame) k = cv2.waitKey(10) if k == ord('q'): break video.release() cv2.destroyAllWindows() However, I encounter an error: cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow' Can somebody help me out? -
How to "save and continue editing" a task in django-viewflow
I'm building an approval workflow using django-viewflow and django-material. A key component of the workflow is for the end user to fill in a lengthy form and eventually submit it for review and approval. What I want My users will expect to be able to save and continue editing, so that they can fill in the form half way, save their progress, and come back later to complete the form filling. Only then they'll want to submit the form. This is a standard feature in the Django admin. What I've found In the default task.html template, django-viewflow offers two submit buttons (source): <button type="submit" name="_continue" class="btn btn-flat">{% trans 'Done and continue on this process' %}</button> <button type="submit" name="_done" class="btn primary white-text">{% trans 'Done' %}</button> The official docs are pretty slim on the difference between these two tasks. "Done and continue" marks the current task as done and activates the next task (which as a user I want to do by default, other than "save and continue editing"). "Done" seems to mark the current task as done, but doesn't proceed to the next task, which requires some awkward self-assigning to proceed. I can see how a user can get confused here. … -
Python Django Livereload Module
Whenever I start the Django development server, I would get this issue LiveReload exception: <urlopen error [Errno 61] Connection refused> The server would still run and render my site but I cannot use the livereload module. I tried uninstalling and reinstalling django-livereload but it does not help. In addition, when I try to run this command: python3 manage.py livereload. It said unknown command:'livereload' -
How to setup nginx config .well-known/acme-challenge with a proxy to Django?
I am very confused with the Nginx .well-known/acme-challenge configuration and how it works with a proxy for Django. Here is my frontend config with is working: server { listen 80; server_name myserve.com; root /var/www/html/myapp_frontend/myapp/; index index.html; location / { try_files $uri$args $uri$args/ /index.html; } location /.well-known/acme-challenge { allow all; root /root/.acme.sh/; } return 301 https://myserver.com$request_uri; } server { listen 443 ssl; server_name myserver.com; location / { root /var/www/html/myapp_frontend/myapp/; index index.html index.htm; try_files $uri$args $uri$args/ /index.html; } ssl_certificate /root/.acme.sh/myserver.com/fullchain.pem; ssl_certificate_key /root/.acme.sh/myserver.com/privkey.pem; } So, on the frontend I have no problem to define: root /var/www/html/myapp_frontend/myapp/; Now I can run the acme script like this: /root/.acme.sh/acme.sh --issue -d myserver.com -w /var/www/html/myapp_frontend/myapp/ It is working fine. But I have issues with my Django backend because the nginx config uses a proxy: upstream myapp { server backend:8000; } server { listen 80; server_name api.myserver.com; location / { proxy_pass http://myapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /.well-known/acme-challenge { allow all; root /root/.acme.sh/; } return 301 https://api.myserver.com$request_uri; } server { listen 443 ssl; server_name api.myserver.com; location / { proxy_pass http://myapp; } ssl_certificate /root/.acme.sh/api.myserver.com/fullchain.pem; ssl_certificate_key /root/.acme.sh/api.myserver.com/privkey.pem; } Notice that I do not have a configuration for the folder "/var/www/html/myapp_backend/myapp/" as I have on the … -
whats wrong with capturing username in url? Like: mysite.com/username [closed]
I want to create directory something like mysite.com/user models.py class TwitterUser(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) urls.py urlpatterns = [ path('<str:user>/', views.user_profile, name='user_profile'), ] views.py for that user_profile def user_profile(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/user_home.html', {'user':user}) -
How many create FCM topics in a server
My team was in trouble in push alarm with FCM token in IOS, So we decided to push alarm to each user with topics. I know that "One app instance can be subscribed to no more than 2000 topics." Firebase But i confused about "One app instance". Is that mean each android or ios application user can subscribe 2000 topics? or Each FCM Server can create up to 2000 topics? I wonder about One app instance's meaning in "One app instance can be subscribed to no more than 2000 topics" -
Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is
Writing a Django app which has a post table that has a recursive relationship to itself. This means that post CAN have a parent post (allows for replies). I want to ensure that a post can have a null for the parent post attribute - this would denote the "root" post. However, when I implement the views, model and serializer for the posts, I get the following error (stack trace): Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Post.objects.create()`. You may need to make the field read-only, or override the PostSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 564, in __init__ _setattr(self, field.attname, val) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 606, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_post_id.set() instead. Here's my model: class PostObjects(models.Manager): """ Return the Post object and all children posts """ def get_queryset(self): …