Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search Django logic
I have written the following code on my web app for searching the form. Now, I want to show error if the searched object if not found. I added the else statement at the last but it shows error. def search(request): qs = Post.objects.all() location_query= request.GET.get('location') details_query= request.GET.get('details') user_query= request.GET.get('user') days_query= request.GET.get('days') people_query= request.GET.get('people') date_query= request.GET.get('date') gender_query= request.GET.get('gender') if location_query !='' and location_query is not None: qs=qs.filter(location__icontains=location_query) elif details_query !='' and details_query is not None: qs=qs.filter(detail__icontains=details_query) elif user_query !='' and user_query is not None: qs=qs.filter(author__icontains=user_query) elif days_query !='' and days_query is not None: qs=qs.filter(no_days__icontains=days_query) elif people_query !='' and people_query is not None: qs=qs.filter(no_people__icontains=people_query) elif date_query !='' and date_query is not None: qs=qs.filter(tour_date__icontains=date_query) elif gender_query !='' and gender_query is not None: qs=qs.filter(Gender_prefer__icontains=gender_query) context = { 'qs':qs, } return render(request, 'posts/search.html',context) I am trying to add this at the end: return render(request, 'posts/search.html', {'error':'The keyword you entered not found!}) -
how do i generate Django site-map without model
i have searched google a lot and read many articles and docs. but all shows how to create sitemap in django useing from django.contrib.sitemaps.views import sitemap but the problem is they all generate sitemaps on top of model(table). i have a database of images( 20,000 images ) they all have different pages and their link generated manually like... path('image/<str:name>/<str:size>/', views.image, name="image"), also my site have many static pages like about us and contact us. also many image gallery pages. so the site have thousands of urls. the image database changes frequently so url changes too how do i generate xml sitemap for this situation. or maybe there is a way around with 3rd party plug in? -
Error when adding DateField in Django "function missing required argument 'month' (pos 2)
I'm a newbie with Django, and today when I used DateField to make time value in my DB, I have got this error "function missing required argument 'month' (pos 2)" I have tried to solve this, but it can not help me. Django documentation Same question in StackOverflow but not affect to me Here is my code: class History(models.Model): code = models.OneToOneField( Passport, on_delete=models.CASCADE, primary_key=True, default=1, ) origin = models.CharField(max_length=64) originTime = models.DateField(auto_now=True) destination = models.CharField(max_length=64) destinationTime = models.DateField(auto_now=True) def __str__(self): return f"{self.code}" And this is my screen error: my db application Thank you. I'm so grateful. -
On submit a Django ChoiceField form only returns the first dictionary in the formset
I have defined a formset that has 3 forms in the following order. Type Number (Student ID) Type Text (Course Name) View.py for form in formset: if form.has_changed(): print(form.cleaned_data) When a post request is submitted the formset.cleaned_data returns [{'student_id': 1, 'course_name': 'English'}, {'student_id': 2, 'course_name': 'Math'}, {'student_id': 3, 'course_name': 'PE'}] I have also added a check if a form.has_changed(), so if I submit 'History' instead of 'English' where id is equal to 1 my form.cleaned_data returns the expected dictionary. {'student_id': 1, 'course_name': 'History'} My issue: When I had a type text form for 'course_name' everything was working as intended. I only faced an issue when I changed the text form to be single-select instead, so the formset is as follows: Type Number (Student ID) Type ChoiceField (Course Name) The formset.cleaned_data returns the same list of dictionaries. [{'student_id': 1, 'course_name': 'English'}, {'student_id': 2, 'course_name': 'Math'}, {'student_id': 3, 'course_name': 'PE'}] However, if I submit 'History' to change the 'PE' course where id is equal to 3 the form.cleaned_data always returns the first dictionary in the list. {'student_id': 1, 'course_name': 'English'} Why is this happening? Is there any issue with using ChoiceField in the formset? -
Capture images from RTSP Stream without displaying the feed
I want to capture images every 30 seconds from RTSP feed from an IP camera. I don't want to display the feed, I just want to capture images from the feed store them and them upload them to a django server for image recognition. Is it possible to this with react native? if so can you please kindly suggest me how. Thank you -
NoReverseMatch at /accounts/login/ in django ()
strong textenter image description here Reverse for 'auth_password_reset' not found. 'auth_password_reset' is not a valid view function or pattern name. Please Tell me how to solve this error -
how to use / add paypal instead of razorpay in django
how to use paypal instead of razorpay in this code .. my code checkout.py : @login_required(login_url= '/login') def checkout(request,slug): course = Course.objects.get(slug = slug) user = request.user action = request.GET.get('action') order = None payment = None error = None if action == 'create_payment': try: user_course = UserCourse.objects.get(user = user , course = course) error = "Your are alrady enrolled in this course" except: pass if error is None: amount = int((course.price - ( course.price * course.discount * 0.01 )) *100) currency = "INR" notes = { "email":user.email, "user":f"{user.first_name} {user.last_name}" } reciept = f"creativecoders{int(time())}" order = client.order.create( {'receipt' :reciept , 'notes' : notes , 'amount' : amount , 'currency' : currency } ) payment = Payment() payment.user = user payment.course = course payment.order_id = order.get('id') payment.save() data = { "course":course, "order":order, "payment":payment, "user":user, "error":error, } return render(request,'courses\checkout.html',data) # function for verify payment @csrf_exempt def verifypayment(request): if request.method == 'POST': data = request.POST context = {} try: client.utility.verify_payment_signature(data) razorpay_order_id = data['razorpay_order_id'] razorpay_payment_id = data['razorpay_payment_id'] payment = Payment.objects.get(order_id = razorpay_order_id) payment.payment_id = razorpay_payment_id payment.status = True userCourse = UserCourse(user = payment.user , course = payment.course) userCourse.save() payment.user_course = userCourse payment.save() return redirect('mycourse') except: return HttpResponse("Invalid Payment Details") I want to use pay-pal and … -
Serve a django specific url on a different domain on GKE
I have a django application deployed on GKE. I use drf-spectacular to generate an open api documentation. The documentation is available under a specific path and I would like to serve this documentation to a specific domain. To be more specific, my app is under api.my-domain.io, I reserved another domain as docs.my-domain.io, what I want is docs.my-domain.io to 'redirect' to api.my-domain.io/my-open-api-doc. The application is on an GKE Ingress. The service associated looks like this: apiVersion: v1 kind: Service metadata: name: service-name namespace: my-ns annotations: cloud.google.com/neg: '{"ingress": true}' cloud.google.com/backend-config: '{"default": "default-backend"}' spec: ports: - port: 80 targetPort: 8082 protocol: TCP name: http selector: app: service-name type: ClusterIP and my ingress is defined as follow: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress namespace: my-ns annotations: kubernetes.io/ingress.global-static-ip-name: server-ip kubernetes.io/ingress.allow-http: "false" kubernetes.io/ingress.class: gce ingress.kubernetes.io/proxy-body-size: 500M ingress.kubernetes.io/enable-cors: "true" ingress.gcp.kubernetes.io/pre-shared-cert: "my-cert" spec: backend: serviceName: service-name servicePort: 80 I thought about adding a section to my ingress like this: - host: docs.my-domain.io http: paths: - path: /my-open-api-doc backend: serviceName: bilberry-api servicePort: 80 But this is not working, I get an error from IAP ( My backend is protected under GCIP ). And moreover the url would be: docs.my-domain.io/my-open-api-doc and not just docs.my-domain.io. I feel like I am … -
Pagination not working with dynamic column in serverside datatable
I'm creating a data table that renders data from the server. There are some constraints that are why I'm setting headers of the data table dynamically. But I'm getting errors while pagination. It's only showing 1st pagination page. My response data from API as follows : {'data': [{'Name': 'Test', 'mode': '--', '': '--','status': '--', 'remark': 'OK'}, {'Name': 'Test', 'mode': '--', '': '--','status': '--', 'remark': 'Green'}, { 'Name': 'Test', 'mode': '--', '': '--','status': '--', 'remark': 'Red'}, { 'Name': 'Test', 'mode': '--', '': '--','status': '--', 'remark': '--'}, { 'Name': 'Test', 'mode': '--', '': '--','status': '--', 'remark': '--'},], 'recordsTotal': 5, 'recordsFiltered': 5} my AJAX code is as follow : function getColumns(signal_id){ filter_values.selected_value = signal_id, filter_values.csrfmiddlewaretoken = getCookie('csrftoken') $.ajax({ type:"GET", data:{"signal_id":signal_id}, url:"/get/colums/", success:function(data){ /*Here data format as follow [{'data': 'name', 'title': 'Name'}, {'data': 'mode', 'title': 'mode'}, {'data': 'status', 'title': 'status'}, {'data': 'remark', 'title': 'remakr'}, ] */ $('#signal_table').DataTable({ "bDestroy":true, "aaSorting": [], "processing": true, "serverSide": true, "scrollX": true, "columns": data, "ajax":{ type: "POST", url:"/api/signal/list/", data :filter_values, error:function(data){ } }, destroy: true, lengthChange: true, }) }, error:function(data){ console.log(data,'Error') } }) } I'm not getting any errors on the console. But still, my pagination is stuck on 1st number. How to solve this? I'm stuck on this, my … -
Django-Pwa - Page refresh
I build a pwa out of my web-app and it seems to work fine, but as I reload the page, I see the service-worker and not the app. index.html {% load pwa %} <head> {% progressive_web_app_meta %} urls.py urlpatterns = [ path('', index), path('', include('pwa.urls')), ... How can I prevent this behavior for situations where somebody doesn't want to install the app but reloads the page? Thank you for any suggestions -
Wagtail: How to expose wagtail snippets on REST API v2
I created a bunch of wagtail snippets and I already set up the REST API V2 that wagtail has. But I'm not sure how to expose each snippet on an endpoint. I don't want to use pages, because I don't need them. I just need to be able to expose this snippets in the API. Is that possible? I want to archive something like this: http://localhost:8000/api/v2/my-snippet-model/ And also be able to add filters. Thanks! -
django-storage: How to store media files using sftp to a folder in aws instance
I have a requirements, I want my media files to be stored at an ubuntu aws instance I have the IP address and the .pem file to access the instance via ssh I have installed django-storages package I am not sure how to setutp this package to store files on an aws instance. I have to add the following settings into settings.py file for django-storages DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_HOST = 'AWS elastic ip' SFTP_STORAGE_ROOT = 'folder on AWS' SFTP_STORAGE_PARAMS = { .... HOW TO PASS KEY HERE } SFTP_KNOWN_HOST_FILE = '~/.ssh/known_hosts' SFTP_STORAGE_INTERACTIVE = False and use in models as from storages.backends.sftpstorage import SFTPStorage SFS = SFTPStorage() class Configurations(BaseModel): name = models.CharField(max_length=150, unique=True) file = models.FileField(upload_to='configurations', storage=SFS) descriptions = models.TextField(null=True, blank=True) So how to do this -
time data '2021-06-10T18:39:41 10:00' does not match format '%Y-%m-%dT%H:%M:%S %z'
I'm attempting to pass a datetime string with a timezone offset into a Django url as a query param as follows: http://0.0.0.0:8080/coordinates/12.231/34.322/?obstime=2021-06-10T18:39:41+1000 I'm attempting to parse this in the view as follows: datetime.datetime.strptime( self.request.query_params.get('obstime'), "%Y-%m-%dT%H:%M:%S %z" ).isoformat() So I'm utilising the format "%Y-%m-%dT%H:%M:%S %z". I thought this would work, however I am seeing the following error: time data '2021-06-10T18:39:41 10:00' does not match format '%Y-%m-%dT%H:%M:%S %z' I've tried to search for potential fixes for this error, but so far everything has come up dry. Does anyone know the correct format I need to pass in to either the url endpoint or to the datetime.datetime.strptime() function... -
How do I reach a data that is on my Django website's url
I am developing a Python-Django website and want to take input from the user and use it. So i could use this code in my HTML page: <form method="get"> <fieldset><legend>Form</legend> <table> <tr><td>Name </td><td><input type="text" name="name"> </td></tr> <tr><td></td><td><input type="submit" value="Submit"></td></tr> </table> </fieldset> </form> Thus, could get a link ending with the input. But how do I use that input on my tag.py or even other HTML pages? Would be glad if someone helps. -
The current path, login/, didn’t match any of these
I have one app on my project which named "bookstore". http://127.0.0.1:8000/login/ is rising an error that the current path, login/, didn't match any of these. In addition that the urls were working properly the last time I was working on my project and I didn't do any changes to my code. I'm using Django version 3.2.2 The bookstore/urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home), path('login/', views.login), path('about/', views.about) ] The main urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('bookstore.urls')) ] The views.py file from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, "bookstore/dashboard.html") def login(request): return render(request, "bookstore/login.html") def about(request): return HttpResponse("About Us") The settings.py file DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bookstore' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' -
fcm-django: device_id field has no more than 150 characters
I can't override or change fcm django model.Frontend sends me post request (device_id is more than 150). But it gives me an error. Because in fcm-django max length of device_id is 150. -
Reactjs frontend with PasswordResetView
I am currently working on a reset password feature (sends email) for a project that's written in Django backend, Reactjs frontend. I am using Django's own PasswordResetView to implement this feature and it works as intended. However I want a page on my frontend sending a POST request to "reset_password/", but I'm getting a "POST http://localhost:8000/user/reset_password/ 403 (Forbidden)" error message. I don't want to use a template to implement this feature, but a Form (component) written in Reactjs running on localhost:3000. How can I do this? Or should I try another approach to the reset password feature? This is the function that tries to post to backend: async resetPassword(email) { const resetPasswordResponse = await client.post("reset_password/", { email: email, }); return resetPasswordResponse;} -
Firestore document does not contain any data
I have a Django app that recognizes the medicines from their boxes with OCR pytesseract. After getting the name I scrap the data from this website http://www.dpm.tn/dpm_pharm/medicament/listmedicspec.php. Finally, after getting all the necessary data with that name of medicine I store it in Firestore but it says "This document does not contain any data" this is the code of the OCR: def ocr_title(im): image = cv2.imread(im, 0) img = cv2.resize(image, (500, 500)) img = cv2.GaussianBlur(img, (5, 5), 0) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 4) himg, wimg = img.shape maxw = 0 text = '' title = pytesseract.image_to_data(img, config='--psm 6 --oem 3') for x, b in enumerate(title.splitlines()): if x != 0: b = b.split() if len(b) == 12 and len(b[11]) >= 4: if (int(b[8]) > maxw): maxh = int(b[9]) maxx = int(b[6]) maxy = int(b[7]) maxw = int(b[8]) text = b[11] text = re.sub(r'[^\w]', '', text) text = str(text) return (text) and this is the code where I store the data after scraping (ps: it's in Beautifulsoup) : for i in range(1, len(names)): try: name = names[i] dosage = dosages[i] url_product = links[i-1] response = requests.post(url_product) soup = BeautifulSoup(response.content, 'lxml') detail_table = soup.find("table") trs = detail_table.find_all('tr') detail = soup.find("font", … -
Show tables already created in database on django admin
How to show tables which are already created using database commands ( not created by models ) on django admin ? -
how to post foreign key with name of user other than id in django rest framework
hello everything is working fine, but if i want to post any dat in rest framework i need to pass the id of user , which is impractical how can i make it to accept the name of the user and post the the request, find my code below serializers.py class Authserializers(serializers.ModelSerializer): class Meta: model = Unique fields = '__all__' views.py @api_view(['POST']) def auth_post_data(request): serializer = Authserializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) when i type the name of the user as string it does not accept the input, plz help me in this situation -
How can i get checkbutton input in template? django
I try to get this checkbox from bd but i dont know why always is checked. I want to get if is on on bd checked on template but if is not on not checked how can i do? thanks. <input type="checkbox" name="retirar_tr" value="off" {% if request.GET.retirar_tr is on %}checked {% endif %} disabled/> Retirar<br> <input type="checkbox" name="colocar_tr" {% if request.GET.colocar_tr is on %}checked {% endif %} disabled/> Colocar img bd fields -
Error when opening a table through the admin panel of a Django site
Into the Django project imported a SQLite database containing records. When opening tables containing fields with the Date type through the admin panel, an error occurs (see below); when opening other tables of this database, no errors occur. ERROR return datetime.date(*map(int, val.split(b"-"))) ValueError: invalid literal for int() with base 10: b'19 00:00:00' models.py file class Contract(models.Model): registry_number = models.TextField(primary_key=True, blank=True, null=False) link_to_contract = models.TextField(blank=True, null=True) date_conclusion_of_a_contract = models.DateField(blank=True, null=True) class Meta: managed = True db_table = 'Contract' -
how to update each div element with Ajax function using Jquary
I am new to J query and I have an Ajax function to update the select options. The Ajax is working fine on my first Div. But when I clone the div and run the Ajax call it again update the first Div element only not the element of cloned one. I new to closet... etc. Please help me so when I call the Ajax it will update the cloned div(current div) element. this is my ajax function: function acct_dbox() { {#var that = $(this)#} $.ajax( { type: "GET", url: "/waccounts/getaccounts", dataType: "json", data: { {#'acctlevel': $(this).val(),#} 'csrfmiddlewaretoken': '{{csrf_token}}' }, success: function (data) { $.each(data, function(index, item) { if (item.length > 0){ console.log('test', item[0].AcctCode); console.log('test', item[0].AcctName); {#$("#id_accountcode option").remove();#} $.each(item, function(index1, item1) { console.log(item1.id); console.log(item1.AcctCode); console.log(item1.AcctName); $("#id_accountcode").append($('<option/>',{ {#$("#id_accountcode").append($('<option/>', {#} value: item1.AcctCode, text: item1.AcctName })); }) $( document ).ready(function() { acct_dbox(); var original_external_int_div = document.getElementById('account_list'); //Div to Clone var clone = original_external_int_div.cloneNode(true); // "deep" clone original_external_int_div.parentNode.append(clone); acct_dbox(); # (it is updating the first div again - not cloned one) }); -
Ajax, refresh table rows on new additions
I'm working on a Django project that runs a background task every time a form is submitted. It takes roughly 2sec to complete each task, when completed, the results are saved, ajax is supposed to perform page refresh but not the whole page, and what I have so far is: $.ajax({ success: function(){ setInterval('location.reload()', 10000); } }) It works as intended, but it's wrong. I have rather limited experience with js. However, I'd like to refresh only the newly added row(s) in the table. I came across jquery .load() but I've been staring for a while now, please any help? -
Can you suggest good alternative of vemio for uploading videos in my python django project
For my python django project i tried vimeo for video uploading, but it doesn't work properly, when i try to upload it shows server time out error every time, I tried multiple way to handle the error but can't,for that any one can suggest good alternative of vimeio, or any other solutions