Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: Order by dates and weekdays
I have a table that stores courses and one that stores their dates and weekdays: Course: ID, CourseDates (M2M) CourseDate: ID, Date (Date), Weekday (0-6), Full (Boolean) If its a date, weekday is NULL If its a weekday, date is NULL Only dates can be set to full (full=True) Use case: I want to order by the next occurence (date or weekday) that is not full. Challenge: Weekdays should only be considered if there is no date that is full for that day. Example: Course 1 1, Date=2021-02-12, Weekday=NULL, Full=True 2, Date=NULL, Weekday=4 (Friday), Full=False Course 2 3, Date=2021-02-13, Weekday=NULL, Full=False Expected Result: Course 2 Course 1 Explanation: Next date for Course 2: 2021-02-13 Next date for Course 1: 2021-02-19 (because 2021-02-12 is full) Question: Can this be done using SQL/Django ORM only? Does it even make sense? My current attempt (this wont work in the above example): """ The subquery annotates all CourseDates with the difference to today, orders them by days left, and in the main query we only use the first entry, which is the closest CourseDate for this course """ subquery = ( CourseDate .objects .exclude(full=True) .filter(course=OuterRef('id')) .filter(Q(date__gt=today_date) | Q(date__isnull=True)) .annotate(today=Value(today_date, output_field=DateField())) .annotate( days_until_next=Case( When(weekday__lt=today_weekday, then=6 … -
how to copy the tables of influx db ( free versione ) into postgres
project-schema As you see in the pictures I have this kind of schema, I'll have many "measurements" (tables) into influxdb, that I need to copy into Postgresdb, so my django app will query the local copy instead of influxdb. i really don't know how to start, I found a lot of mirroring setup for sql-sql db , but I don't find nothing for "timeserie db" and "relational db" -
Only allow a certain domain to access my Django backend
I'm currently developing an application which consists of a React frontend, which makes frequent requests to a Django backend. Both the React and Django applications are running on the same server. My problem is I wish to hide my Django backend from the world, so it only accepts requests from my React application. To do so, I've been trying several configurations of ALLOWED_HOSTS in my Django settings.py, but so far none of them seem to be successful. An example route that I wish to hide is the following: https://api.jobot.es/auth/user/1 At first I tried the following configuration: ALLOWED_HOSTS=['jobot.es'] but while this hid the Django backend from the world, it also blocked the petitions coming from the React app (at jobot.es). Changing the configuration to: ALLOWED_HOSTS=['127.0.0.1'] enabled my React app to access the backend but so could do the rest of the world. When the Django backend is inaccessible from the outside world, a get request from https://api.jobot.es/auth/user/1 should return a 400 "Bad Request" status. The error I get when the React app fails to request data from the Django backend is the following: Access to XMLHttpRequest at 'https://api.jobot.es/auth/login' from origin 'https://jobot.es' has been blocked by CORS policy: Response to preflight request … -
What is Causing Encrypted Nginx Log Lines and ERR_SSL_PROTOCOL_ERROR in Docker Compose?
I am running three docker containers in a django production environment on a google cloud VM with firewall settings open to https traffic. I am using a chained cert that I obtained from godaddy and concatenated the certs as per nginx docs. My containers are a django app, postgres, and nginx acting as a proxy in order to serve static files. I am orchestrating them using docker-compose. I also have a public URL pointing to the public IP of the google vm. When going to the endpoint in a browser I get an "ERR_SSL_PROTOCOL_ERROR" If I tail the nginx logs on the vm I get encoded log lines, like: nginx_1 | 93.173.8.110 - - [09/Feb/2021:09:02:12 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03C\x08!\xB3d\xC76P\xE5\x I confirmed that the nginx container is up and running and started with no errors. Is there something obvious I am doing wrong? And specifically a reason my nginx log entries are encrypted and non-readable? Here is the Dockerfile: ########### # BUILDER # # First build step in order to make final image smaller. # This is referenced in second build step. ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory #WORKDIR /usr/src/app WORKDIR /code # set environment … -
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Django
I'm getting this error whenever I'm trying to run python manage.py runserver in Django. The error: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Why can that be? I think it is because my settings.py it is called base.py instead of settings.py and that's why Django doesn't detect that file as my settings file. If that's the case, how can I assign the settigns file to that base.py fiile? this is the base.py file: import os from pathlib import Path from django.urls import reverse_lazy # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ######################################## # APPS ######################################## INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'allauth', 'allauth.account', 'djstripe', 'captcha', 'users', ] ######################################## # MIDDLEWARE ######################################## 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', ] ######################################## # SECURITY ######################################## SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = bool(os.getenv("DJANGO_DEBUG", "False").lower() in ["true", "1"]) ALLOWED_HOSTS = [] ######################################## # OTHER ######################################## ROOT_URLCONF = 'urls' WSGI_APPLICATION = 'wsgi.application' SITE_ID = 1 ######################################## # TEMPLATES ######################################## TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates", ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Insert database table name in raw sql in Django
I'm trying to pass the database table name into my raw sql query in Django like this: instance = Nutrient.objects.raw( ''' select * from %(table)s # <-- error here for system_time as of timestamp %(time)s where id=%(id)s; ''', params={'table': self.dbTable, 'time': timestamp, 'id': instance.id})[0] It works fine when I insert the timestamp or the instance id but it gives me an error on the table name: Error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) The above exception ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' 'foods_nutrient'\n for system_time as of timestamp '2021-0...' at line 1")) was the direct cause of the following exception: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, … -
Django webserver falis after sending a password reset request email
I have asked this question multiple times now, and it is definitely my fault for not explaining the problem properly, so I have made a short screen-recording that showcases the problem. The URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), Settings setup: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*******@gmail.com' EMAIL_HOST_PASSWORD = *******' Here are the logs, I tried to read them but I got no idea how to fix this error. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 850, in resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_nav_sidebar_enabled] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf..get_val at 0x00000285F295D488>>, 'request': <WSGIRequest: GET '/reset_password/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.. at 0x00000285F2B482F0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x00000285F2A4EE10>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000285F2B200F0>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': , 'view': <django.contrib.auth.views.PasswordResetView object at 0x00000285F2B201D0>, 'title': 'Password reset', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] "GET /reset_password/ HTTP/1.1" 200 1903 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en\formats.py first seen with mtime 1603131647.8355522 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en_init.py first seen with mtime 1603131647.8345575 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\staticfiles\storage.py first seen with mtime 1603131653.6030731 … -
using django project as a standalone file
i need to use my django project in a standalone system where i can't install python, so i try to use pyinstaller on my manage.py file and i added function that opens the browser so when i click on the icon- the project will open automatically in the browser. my manage.py code is: import os import sys import webbrowser import django def open_in_browser(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedback.settings') django.setup() from django.core.management import call_command from django.core.wsgi import get_wsgi_application application = get_wsgi_application() webbrowser.open('http://127.0.0.1:8000', new=1) call_command('runserver', '127.0.0.1:8000') def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedback.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) open_in_browser() if __name__ == '__main__': main() the code work before pyinstaller but when i try to use pyinstaller the file manage to open the browser but the server stop running so the browser cannot find the page. how can i keep the server running? -
How to run Django APScheduler on a view function
I want to run a Django view every day preferably at a specific time that calls an API and saves the data in a ForeignKey relational model. I can't use the schedule package in python because it requires infinite loop which can't run alongside a web server. Django APScheduler looks like an elegant solution though the problem is view functions take request as an argument which can't be passed to APScheduler which I need to save the data with the user's id thus I'm getting a Name error views.py def sync_data(): api_url = "" access_token = RefreshToken.response headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json;encoding=utf-8', } user_id = request.user.id response = requests.post(api_url, data=json.dumps(body), headers=headers) r = response.json() s = Model(user=request.user, starttime = startdate , endtime = endate, field = i['value'][0]) s.save() return redirect('app:dash') scheduler.py from .views import sync_data def start(): scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") # run this job every 24 hours scheduler.add_job(sync_data, 'interval', hours=24, name='sync_daily_data', jobstore='default') register_events(scheduler) scheduler.start() print("Scheduler started...", file=sys.stdout) How do I go about this? Appreciate any help I'll get -
Default regex django uses to validate email
recently, I started playing with Django and created a custom form for user registration. In that form to create the field for email I use something like email = forms.EmailField() I observed that address such as a@a.a is considered invalid by the form. Of course this is a nonsense email address. Nonetheless, I wonder how does Django checks for validity. I found some topics on the net discussing how to check for validity of an email address but all of them were providing some custom ways. Couldn't find something talking about the django default validator. In their docs on the email filed they specify Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression. However that's not very specific so I decided to ask here. -
xmlhttprequest post not posting to view in django
I am having a login page like this which gets data authenticated from google sign-in successfully and after that I need to post the data to the login view function onSignIn(googleUser) { // Useful data for your client-side scripts: var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); var id_token = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); alert("Token*"+id_token); //this gets executed var xhr = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; request.open('POST', '/login'); //i tried this also 'login' but not working xhr.open('POST', 'http://localhost:8000/login'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { console.log('Signed in as: ' + xhr.responseText); alert("*******Token*"+id_token) xhr.send('idtoken=' + id_token); }; views def login(request): //does not get called if request.method=='POST': print("in login") print(request.body.decode()) ---more code urls.py path('/login', views.login, name="login"), path('',views.login,name="login"), I am getting no response on the view, i am not getting any error on the console also. Can anyone please help here? Thanks. Starting development server at http://localhost:8000/ Quit the server with CONTROL-C. [09/Feb/2021 07:44:13] "GET / HTTP/1.1" 200 3048 [09/Feb/2021 07:45:15] "GET / HTTP/1.1" 200 … -
Distance between two coordinates in swift does not match geodjango query
I am in the process of developing a mobile application in Swift that is connected to a Python/Django backend. I have a group of objects that need to be sorted by location. Each object has a Point representing the coordinate pair. I connect to the backend from the frontend by passing in the source_latitude and source_longitude into the url parameters. I then use geodjangos with geospatial indexing for two different queries: latitude = request.query_params.get('source_latitude', None) longitude = request.query_params.get('source_longitude', None) if latitude is None or longitude is None: return queryset ref_location = Point(float(latitude), float(longitude), srid=4326) return queryset.annotate(distance=Distance('location', ref_location, spheroid=False)).order_by('distance').distinct() In my second query, I need to organize by within a certain range, which includes a radius URL parameter: return Store.objects.filter(location__distance_lte=(ref_location, D(mi=[radius input into from url parameter]))) Since the distance calculated is different for each object on each phone. I calculate the distance to display to the user on the frontend. However, there seems to be a discrepancy with the distance calculated between the frontend and the backend. For some objects that are close in distance, say 1-3 miles, the ordering of the objects is wrong. This is the frontend swift Code let currentLocation = CLLocation(latitude: Double(latitude)!, longitude: Double(longitude)!) let storeLocation = … -
Is there a way to pass in variable to <div> id in django template?
I am new to the Django template language and I am playing around with bootstrap collapses to display my items. Below is my code: {% for item in items %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{item.item_name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> {{item.description}} </div> </div> </div> </div> {% endfor %} This is taken from the Bootstrap documentation for collapse, here. In this implementation, all of the items passed in would have the same id, collapseOne. So whenever I click on an item, any item, it would collapse/uncollapse every item on the page. I've tried id="collapse{{item.item_name}}" but that doesn't seem to work. Is there a way to pass in variables in <div> id? -
how to show the name of uploaded file as download link in Django
In my Django project, I want to show the download link as the name of the uploaded file. Here is my models.py class QuoteList(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) attached_file = models.FileField(upload_to='documents/QuoteList/%s/'%owner, blank=True) def __str__(self): return self.owner.email In views.py, I just query an object and send it to the template: def quote_details(request, quote_id): quote = get_object_or_404(QuoteList, id=quote_id) quote.is_opened = True quote.save(update_fields=['is_opened', ]) context = { 'quote': quote, } return render(request, 'basket/quote_details.html', context) In the template I use the following code to generate download link: {% if quote.attached_file %} <div class=""> <a role="button" href="{{ quote.attached_file.url }}" download="{{ quote.attached_file.url }}" class="btn btn-light text-dark ml-0"> Download attachment <========== the name which is showing to the user </a> </div> {% endif %} how to change the Download attachment to the name of uploaded file? -
Flask API access through headers token from a Django app
I'm a web dev beginner and I am trying to implement the following solution for my problem. I have several public Flask APIs, that I need to access from a Django App. These APIs is for back-end use, with the objective to provide data from the database to the Django app access and display the data (in graphics) for the user. This strategy was build in order to separate the database from the web app for protection purpouses. I want to limit Flask APIs public access in a way that just my Django app access it. The simplest solution I came up with was creating a JWT token with SECRET_KEY information shared between applications, Flask API and Django app, and pass the token through headers request: Django request: token = jwt.encode({'user_name' : 'admin_user'}, app.config['SECRET_KEY']) url = "http://website.com/api-flask" requesturl = Request(url) requesturl.add_header('Token', '%s' % token) response = urlopen(requesturl) Flask token check: def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.headers.get('Token') token_b = tokenurl.encode('UTF-8') if not tokenurl: return jsonify({'message' : 'No token!'}), 401 try: dataurl = jwt.decode(token_b, app.config['SECRET_KEY']) except: return jsonify({'message' : 'Token is invalid!'}), 401 return f(message, *args, **kwargs) return decorated @app.route("/api-flask") @token_required def apiflask: conn = db_connect.connect() query = conn.execute("SELECT … -
ValueError: Field 'id' expected a number but got 'kumarsingha922@gmail.com'
I made a django projects in which i made a test i assign email to email but it was taking it as a Id solve thi problem It was a django project in which i am making a receipe api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . , , . . . Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager,PermissionsMixin # Create your models here. class UserManager(BaseUserManager): def create_user(self,email, password, **extra_fields): user = self.model(email, **extra_fields) user.set_password(password) user.save(using= self._db) return user class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(max_length=255,unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" test_models.py from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_sucessfully(self): email = "kumarsingha922@gmail.com" password = "Singh@922" user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email,email) self.assertTrue(user.check_password(password)) Error WARNING: Found orphan containers (recipe-api_db_1) for this project. If you removed or renamed this service in your compose file, you can run this command … -
how to get Category in Django Serializer
i have hierarchical category in Django 3.1.5 class Categories(models.Model): category_name = models.CharField(max_length=250, unique=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='parent') slug = models.CharField(max_length=250, blank=True, null=True) data like - [{ "id": 1, "category_name": "1", "parent": null}, { "id": 2, "category_name": "1.1", "parent": 1}, { "id": 3, "category_name": "1.1.1", "parent": 2}, { "id": 4, "category_name": "1.2", "parent": 1}, { "id": 5, "category_name": "1.1.1.1", "parent": 3}] i using django Serializer. so how can we get category hierarchical data like- { "id": 1, "category_name": "1", "parent": null, "SubCategories": [{ "id": 2, "category_name": "1.1", "parent": 1, "SubCategories": [{ "id": 3, "category_name": "1.1.1", "parent": 2, "SubCategories": [{ "id": 4, "category_name": "1.1.1.1", "parent": 3, "SubCategories": [...] },] },] }, { "id": 5, "category_name": "1.2", "parent": 1, "SubCategories": [...] },] } -
How to receive SMS and store it to a local database in Twilio?
I'm starting an SMS project. One of the features is that people can respond to a form through SMS. Is it possible to receive an SMS and store the information in a local database? How do I that with Twilio? For example, the user sends a message with a request to fill-up a form. It then replies the needed information to fill in and the format for responding. After the user replies with the proper format, the collected data would then be written into the database. For a clearer example: User: I want to fill the form APP: Answer the following: [1] First Name, [2] Middle Name, [3] Last Name, [4] Age, [5] City To respond, follow the format: (First Name) (Middle Name) (Last Name) (Age) (Street) (City) User: (replies with proper format) APP: Thanks your response has been recorded! These variables of each info (First name, Last name, Age, City) would then be stored in a database. How do I make a GET and POST method? I would like to use Python, and use Django and connect it with a MySQL database. I've been searching for ways, but I tend to get lost. I'm having a hard time learning … -
Serve files in django
I am using React with Django. And I want to serve react public files from Django. but django static and media files are served with a prefix url, like this /static/favicon.ico /static/manifest.json /media/image.png but I want to serve files like this, without any prefix /favicon.ico /manifest.json So how do I do it? -
hosting my Django website on the internet with SSL certification overseas
I have completed my django project and I intend to host it online. I do not want to host it through Heroku or PythonAnywhere and I also require an SSL certificate. I come from Singapore, and after some research, I realised they only offer support to Wordpress, PHP websites. As such, I am wondering if it is possible for me to host it in another country such as USA/UK instead of in my own country. Will it be very difficult to manage my website hosted in another country? Also, do you guys have any recommended hosting providers in those countries that I can reach out to for a good deal? Sorry that this isn't a coding question. Advises will be super appreciated! -
Django premailer - Removes responsiveness from email template
I am trying to send an email using Django. The email template was made by someone else with a ton of CSS and it will take a lot of hours just to "inline" it. So I used premailer to inline the CSS automatically. It worked pretty well till I saw that it also inlined the media queries that were responsible for the responsiveness of the templates. One solution I saw was to put media queries in a separate style tag and put data-premailer="ignore" but unfortunately, I think this solution does not work anymore. I also tried using django_inlinecss, but that didn't work for me also. Please let me know how to fix premailer or if there any other package available that can inline CSS. -
JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in POST request
I'm working on a project where I integrated a payment gateway, where I created a JSON string and pass URL, when all information is correct, then it generates a payment link. When I used demo URL and demo data it worked perfectly but when I use real URL it says this error. here is view.py: def payment(request): jsonObj={ "name": "name" } json_string = json.dumps(jsonObj) print(json_string) url = "https://url.something" headers = {'Content-type': 'application/json', 'Accept': 'application/json'} r = requests.post(url, data=json_string, headers=headers) print(r.json()) j = r.json()['status'] k = r.json()['data'] if j == "200": payment_id = k['payment_id'] redirect_url = k['redirect_url'] payment_link = str(redirect_url) + "?" + str(payment_id) print(payment_link) context = { 'payment_link': payment_link, } return render(request, 'users_dashboard/payment.html', context) return render(request, 'users_dashboard/product_rashid.html') -
Deployed two versions of same code (Django) on App engine standard but they are working differently
I am working on a Django project and deployed two versions of it on Google cloud app engine standard. And it is working perfectly fine locally but when tested with the version URL on the app engine, one version is working fine but another was not. Actually, I am using the fpdf module in python to write pdf files whenever a user writes a text. But only one version was able to do that another one giving me a blank pdf. When I checked the size of both the version there was a difference of 0.1MB.This image shows you the size of both the version: I went through the source code of both versions, and I don't have seen any difference between them, and no file is deleted. I have also checked the requiements.txt and app.yaml file but there was no difference at all.This image shows the files I used Till 4th Feb 2021, every version I have deployed is working perfectly but it was not working now Thanks in Advance -
How to use Django Qml and Javascript to create a Desktop App
I want to use qml, pyside and django to create a desktop app that will be connecting to the internet. I know it makes sense to use php but because i am an intermediate with qt and python, I would like to use my strongest suite. How possible is it to create this app which will be full of report generation and user activity monitering. If not how do u suggest I go about solving the problem. -
Update changes on React + Django without running "npm run build" everytime
My Django + React app is integrated fine at least for most parts. Because every time I have to make changes on my React code, in order to apply those changes I have to stop django from running then run npm run build everytime. I've already read this is there any way to run React + Django in same project without running npm run build again and again? and tried to apply it to my problem but it didn't work. Still new in React but with a few experiences with Django. Would appreciate your help