Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Session Variables Don't Work In Stripe Webhook?
I am trying to use data saved in django session variables to run a function once the webhook has confirmed that 'checkout.session.completed' but I always get a key error. I am 100% sure the keys exist in the session variables. Here is my webhook: @csrf_exempt def stripe_webhook(request): # You can find your endpoint's secret in your webhook settings endpoint_secret = 'secret' payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] fulfull_order(session) return HttpResponse(status=200) Here is my fulfill order function: def fulfull_order(session): generator = PlanMaker(goal=request.session['goal'], gender=request.session['gender']) /// send email code. This line generator = PlanMaker(goal=request.session['goal'], gender=request.session['gender']) Always gives a key error on request.session['goal'] The key definitely exists, it just seems it is inaccessible from the webhook view. How to solve? -
How to map graphene.InputObjectType fields to kwargs?
Let's say we have InputObjectType: class OfficeInput(graphene.InputObjectType): orderNumber = graphene.Int(required=True) name = graphene.String() streetAddress = graphene.String() postalCode = graphene.String() city = graphene.String() And python class which take similar arguments, in this case we have mongoengine EmbeddedDocument: class Office(EmbeddedDocument): orderNumber = fields.IntField(required=True) name = fields.StringField(default="", required=True) streetAddress = fields.StringField(default="", required=True) postalCode = fields.StringField(default="", required=True) city = fields.StringField(default="", required=True) I would want to create Office instance by assigning OfficeInput fields to Office constructor, i.e. map OfficeInput fields to dict and pass them to constructor using python **kwargs -
Django admin, relationships [closed]
I want to get related positions after choosing random Department element. enter image description here -
How can I get a value from other model, based in other value from that same other model?
How can I get the proper "sumvalue" in the example? (which I only know how to represent in SQL): class Addition(models.Model): location = models.ForeignKey(Place, ...) a = models.DecimalField(...) b = models.DecimalField(...) @property def c(self): return self.a + self.b class Result(models.Model): place = models.ForeignKey(Place, ...) # I only know how to represent in SQL sumvalue = SELECT c FROM Addition WHERE location = place -
how to use paypal instead of razorpay - django
how to use paypal instead of razorpay in this code .. my code https://gofile.io/d/wV8btv I want to use paypal and save the rest of the codes -
How to make query to postgresql database from Django
This is my request for postgresql: SELECT date, COUNT(*) FROM main_like GROUP BY date; How can i do this request from Django?