Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to update a field without change auto-now field?
In a loop and automatically, that is, I always check all users once every 10 minutes, and I may need to update a boll field from them How can I not change my current field when I update that bool field ? class Client(models.Model): user = models.ForeignKey ... last_activity = models.DateTimeField(_("Last Activity"), auto_now=True) joined = models.BooleanField(_("Joined in Default Channel"), default = False) ... ... i want to update joined field without change last_activity. how can i do? -
Is there a Django manage.py command for running Celery worker?
I created a short Python script to launch the Celery worker for the current Django via: from celery.bin import worker worker.worker(app=my_app).run() This works great and utilizes all the correct settings so there's no need to specify all the myriad command-line arguments of celery (and I can launch it via debugpy and remote debug it from a container in VS Code). My question is whether there is a manage.py command I can run to achieve the same thing? -
Drag and Drop File Input Require Validation
I have a file input from Django forms that renders to <input type="file" name="file" required id="id_file" accept="application/pdf"> <label for="id_file" id="labelFile"><i class="fa fa-upload"></i> <span>Upload File...</span> </label> I wanted to add a drop and drop to this file input so I did const dropHandler = function(ev){ ev.preventDefault() if(ev.dataTransfer.items){ for(const i of ev.dataTransfer.items){ if(i.kind === 'file'){ const file = i.getAsFile() console.log(file); const fileIn = document.querySelector('#id_file') fileIn.file = file console.log(fileIn.file.name); $('#labelFile span').html(fileIn.file.name) } } } } The problem is it doesn't let me submit the form because the input file field is required. Is doing fileIn.file = file incorrect for setting the input file field so it satisfies the required? -
Debuggin django log on NGINX - DigitalOcean
I have a Django application (droplet) on DigitalOcean but I have an issue showing information in a table. Everything works on my local server but when I deploy to the server on DigitalOcean I don't know where I can see the activity of the server like print outputs. I can see the gunicorn and nginx logs but none of those logs show the Django activity. What should I do? -
Error message: "'NoneType' object is not callable". - received from zappa deployed django application on AWS Lambda
I'm running into an error after deploying my django app to lambda using zappa. This is the error: {'message': 'An uncaught exception happened while servicing this request. You can investigate this with the `zappa tail` command.', 'traceback': ['Traceback (most recent call last):', ' File /var/task/handler.py, line 540, in handler with Response.from_app(self.wsgi_app, environ) as response:', ' File /var/task/werkzeug/wrappers/base_response.py, line 287, in from_app return cls(*_run_wsgi_app(app, environ, buffered))', ' File /var/task/werkzeug/wrappers/base_response.py, line 26, in _run_wsgi_app return _run_wsgi_app(*args)', ' File /var/task/werkzeug/test.py, line 1119, in run_wsgi_app app_rv = app(environ, start_response)', TypeError: 'NoneType' object is not callable]} These are my zappa settings: { "production": { "aws_region": "eu-west-2", "django_settings": "app.settings", "profile_name": "deployment", "project_name": "app", "runtime": "python3.6", "s3_bucket": "zappa-deployment-uploads", "slim_handler": true, "exclude": [".ebextensions/", ".elasticbeanstalk/", "webpack/", "app/static/"], "vpc_config" : { "SubnetIds": [ "..."], "SecurityGroupIds": ["..."] } } I've ensured that my API Gateway hostname has been added to my allowed hosts setting and redeployed. I've called zappa tail, but it gives me an even shorter error respons "'NoneType' object is not callable". Can anyone understand why I would be getting this? -
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