Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display python function result in html django
I made a web application with django that execute a python function . this function runs every 5 second and prints results in console and I want to show the result in html page and the results extend to prior results in html file . the problem is when I press the button to start service, the function starts but the page is always in reloading and doesn't redirect to new page to show the function results in new page : this is my code : def index(request): login_form = LoginForm(request.POST, request.FILES) context = { "form": login_form, } if login_form.is_valid(): ip = login_form.cleaned_data.get('IP') port = login_form.cleaned_data.get('port') username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') handle_uploaded_file(request.FILES["certificate"]) request.session['ip'] = ip request.session['port'] = port request.session['username'] = username request.session['password'] = password return redirect('monitor/', request.session) return render(request, "index.html", context) def monitor(request): ip = request.session['ip'] port = request.session['port'] username = request.session['username'] password = request.session['password'] p = sp.Popen(monitoring(ip, port, username, password), stdout=sp.PIPE, stderr=sp.PIPE) output, errors = p.communicate() return render(request, "monitor.html",{'output':output}) this is my html : html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <h3>{{ output }}</h3> </body> </html> -
Heroku Django website relation does not exist on PstgreSql Database
I developped a website which runs fine on my local machine. I uploaded my site and the postgre database to Heroku. It displayed correctly, and I'm able to access to the admin console. In the front page of my site I have links that make request to my database, but I receive "relation "mytable" does not exist" I'm able to make request manually with heroku pg:psql without any problems. My models are like this : class Data(models.Model): i = models.AutoField(primary_key=True) version = models.CharField(max_length=10, blank=True, null=True) id = models.JSONField(blank=True, null=True) attributes = models.JSONField(blank=True, null=True) audiofiles = models.JSONField(blank=True, null=True) class Meta: managed = False db_table = 'data' On my settings.py I have the following for Database node (I replaced infos for obvious reasons): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': '', 'PORT': '5432', 'OPTIONS': { 'options': '-c search_path=card' } } } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) Here my requirements.txt: asgiref==3.3.1 dj-database-url==0.5.0 Django==3.1.7 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.8.6 pytz==2021.1 sqlparse==0.4.1 whitenoise==5.2.0 I tryed many things like : heroku run python manage.py makemigrations followed by migrate heroku run python manage.py migrate --run-syncdb Drop my database a recreate it makemigrations on local then commit the change to heroku (and migrate again … -
is there a way to paginate multiple querysets in django list view?
i will use bootstrap tabs to make a tab for the (newest questions) posted which i will use the original query from the model to sort objects by date posted, and a tab for the (most liked) question which i will an additional context queryset for... when i have them on the template the pagination is only for the model queryset, how do i make it also for the second query when the user is on the (most likes) tab my view: class QuestionListView(ListView): model = Question template_name = 'question/question_list.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = Category.objects.root_nodes() count = Question.objects.count() question_likes = Question.objects.all().order_by('-like_count') context['category'] = category context['count'] = count context['question_likes'] = question_likes return context my models class Question(models.Model): title = models.CharField(max_length=150, unique=True) slug = models.SlugField(max_length=150, unique=True) content = RichTextField(null=False, blank=False) tags = TreeManyToManyField(Category, related_name='cat_questions') author = models.ForeignKey(UserBase, on_delete=models.CASCADE, related_name='questions') date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(UserBase, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') class Meta: ordering = ['-date_posted'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('question:question_detail', kwargs={'slug':self.slug}) def __str__(self): return self.title my template pagination {% if is_paginated %} <div class="col-12 text-center mt-5"> {% if page_obj.has_previous %} <a class="btn btn-outline-dark my-4" href="?page=1">First</a> <a … -
Django: Handling Foreign Key value in template
I have recently started working with Django and I am struggling to work with 2 models in a single form. I have looked a lot of questions in stackoverflow but I couldn't find any that answers this question. I have 2 models - Student & Address This is my models.py class Students (models.Model): Student_Name = models.CharField(max_length=50, db_column='Student_Name') College_Number = models.CharField( max_length=10, db_column='College_Number') Gender = models.CharField(max_length=50, db_column='Gender') Blood_Group = models.CharField(max_length=50, db_column='Blood_Group') Set = models.CharField(max_length=50, db_column='Set') Standard = models.CharField(max_length=50, db_column='Standard') class Addresses (models.Model): Student_ID = models.ForeignKey( Students, on_delete=models.CASCADE, db_column='Student_ID') City = models.CharField(max_length=50, db_column='City') State = models.CharField(max_length=50, db_column='State') Pincode = models.CharField(max_length=50, db_column='Pincode') AddressLine1 = models.CharField(max_length=1024, db_column='AddressLine1') AddressLine2 = models.CharField(max_length=1024, db_column='AddressLine2') This is my views.py def student_create_view(request): student_form = StudentFrom(request.POST or None) address_form = AddressForm(request.POST or None) if (request.POST.get('Student_Name') and request.POST.get('College_Number') and request.POST.get('Gender') and request.POST.get('Blood_Group') and request.POST.get('Set') and request.POST.get('Standard') and request.POST.get('AddressLine1') and request.POST.get('AddressLine2') and request.POST.get('City') and request.POST.get('State') and request.POST.get('Pincode') and student_form.is_valid() and address_form.is_valid()): # Fetch values from the Student Form student_form.name = request.POST.get('Student_Name') student_form.collegenumber = request.POST.get('College_Number') student_form.Gender = request.POST.get('Gender') student_form.Blood_Group = request.POST.get('Blood_Group') student_form.Set = request.POST.get('Set') student_form.Standard = request.POST.get('Standard') # Fetch values from the Address Form address_form.AddressLine1 = request.POST.get('AddressLine1') address_form.AddressLine2 = request.POST.get('AddressLine2') address_form.City = request.POST.get('City') address_form.State = request.POST.get('State') address_form.Pincode = request.POST.get('Pincode') student_form.save() address_form.save() return redirect('/create') … -
Django MySQL - correct way to connect
I have been using Django to connect to MySQL on my local computer and I have been using the following method to connect: run pip install mysqlclient and update the requirements.txt file appropriately. update the database connection in settings.py to something like this: 'ENGINE': 'django.db.backends.mysql', 'NAME': ......, 'USER': ......, A bit of a problem arose when I started to use a Dockerfile to try to run the Django app. When I build the Dockerfile and then run the django project, I start to get errors: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? It seems to me that there are 2 potential solutions to this: 1 ) Adjust the Dockerfile so that it installs the software necessary for mysqlclient. This is actually a bit trickier than expected. Could you please make some recommendations for python:3.10.0a5-alpine3.12. 2 ) I was reading about mysql-connector-python. At present I have not got this to work. I installed it using pip, updated the requirements file and then changed the settings.py file to something like this: 'ENGINE': 'mysql.connector.django', 'NAME': ...., 'USER': ...., I have two area's of concern and I would really appreciate some help: 1 ) Which of these methods is the most appropriate … -
Delete and Restoring Files and Cascaded Folders Django
I am new to django and I am working on a project similar to google Drive. I want when I soft delete a folder or file, it should Appear to Trash (only parent folder in case it has children), But it should not be removed in media root folder I want to be able to restore the folder (and its children if it has one) or a file I also want to be able to delete permanently files or folders that are in Trash Here is the code that I have written import os import safedelete from django.db import models from safedelete.models import SafeDeleteModel from safedelete.models import SOFT_DELETE_CASCADE from safedelete.models import HARD_DELETE from documentation.manager import * from datetime import datetime from django.urls import reverse from django.utils.text import slugify from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver from account.models import CustomUser from program.models import Activity #a model to create the folder class Folder(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE objects = MyModelManager() creator = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null = True) activity_name = models.ForeignKey(Activity, on_delete=models.CASCADE, blank = True, null=True) name = models.CharField(max_length=64) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) path = models.CharField(max_length=2048, blank=True) slug = models.SlugField(blank=True) def __str__(self): return self.name def get_absolute_url(self): kwargs … -
Django REST API refusing connection to browsers?
I tried accessing my Django project fro another device, and it always returns either ERR_CONNECTION_REFUSED on Chromium based browsers, or CORS on Firefox. I can access the API using Postman without issues. It also works if it is using localhost. Django serves HTML files no problem, just not the API calls. I've installed django-cors-headers and added it to installed applications, middleware, and allowed all. Requests don't show on console either (using manage.py runserver). Is there anything I'm missing? -
I'm creating a cost calculating site using django. How do I make the backend work?
class CalcView(TemplateView): template_name = 'calculator.html' onestoried = 600000 twostoried = 800000 highq= 240000 mediumq= 120000 select_story = input('How tall ?' '\n 1. One Storied' '\n 2. Two Storied : ') if select_story == '1': select_quality = input('What quality?' '\n 1. High' '\n 2. Medium : ') if select_quality == '1': print('The price will be:', onestoried + highq) elif select_quality == '2': print('The price will be:', onestoried + mediumq) else: print('Select a valid quality') elif select_story == '2': select_quality = input('What quality?' '\n 1. High' '\n 2. Medium : ') if select_quality == '1': print('The price will be:', twostoried + highq) elif select_quality == '2': print( 'The price will be:',twostoried + mediumq) else: print('Select a valid quality') else: print('Select a valid story') ** This is the code I wrote for the calculations. Very simple and works just fine in the terminal. But the question is how can I make this backend work in the webpage.?? What I'm trying is to create 4 buttons, dropdowns, checkboxes, anything suitable on the webpage named 'onestoried','twostoried','highq' and 'mediumq' and I want the calculations to be performed when the buttons are clicked i.e. if user clicks/selects high quality and one storied, I want the answer in … -
how do i get rid of attribute error as u can see in last line
PS C:\Users\Admin\Desktop\django path\mysite\portfolio> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions Running migrations: Traceback (most recent call last): File "C:\Users\Admin\Desktop\django path\mysite\portfolio\manage.py", line 22, in main() File "C:\Users\Admin\Desktop\django path\mysite\portfolio\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python39\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\python39\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\python39\lib\site-packages\django\db\migrations\executor.py", line 91, in migrate self.recorder.ensure_schema() File "C:\python39\lib\site-packages\django\db\migrations\recorder.py", line 67, in ensure_schema with self.connection.schema_editor() as editor: File "C:\python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 24, in enter if not self.connection.disable_constraint_checking(): File "C:\python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 311, in disable_constraint_checking enabled = cursor.execute('PRAGMA foreign_keys').fetchone()[0] AttributeError: 'NoneType' object has no attribute 'fetchone' PS C:\Users\Admin\Desktop\django path\mysite\portfolio> -
modifay fileField to TextField by selected value
select video resource select URK resource (text) url resource i replace input[image] to input[text] with js but how does it manage while saving -
How to retrieve related instances without FK using one query in django
Imagine there are three models named Movie, Actor, and Participation. class Movie(models.Model): identifier = models.CharField() class Actor(models.Model): name = models.CharField() class Participation(models.Model): movie_identifier = models.CharField() actor = models.ForgeinKey(Actor, on_delete=models.CASCADE) Let's assume that I can't use ForgeinKey for the movie in the Participation model. how can I retrieve all the participation records of a movie with only one query? Here is the solution if I had a foreign key for the movie in the participation table: qs = Movie.objects.filter(identifier="an_identiier").prefetch_related("participations_set") How can I do this without having a Movie foreign key in the Participation model? Thanks! -
Django: Order_by combined two columns
I have following query; There are two columns (dateEmploymentRD and dateTerminationRD). qsPersonnel = qsPersonnel.filter(Q(dateEmploymentRD__isnull=False), Q(dateEmploymentRD__lte=personnelDateMax), Q(dateTerminationRD__gte=personnelDateMin) | Q(dateTerminationRD__isnull=True), Q(dateTerminationRD__lte=personnelDateMax) | Q(dateTerminationRD__isnull=True)).order_by('dateEmploymentRD','dateTerminationRD') I would like to sort that queryset with combined two coulmns (dateEmploymentRD and dateTerminationRD). But my query is ordering firstly 'dateEmployementRD' and than ordering by 'dateTerminationRD' as below. How can I order my query by combined two columns? -
How to order data in a specific/customised manner in django-models?
Here are my files models.py from django.db import models from django.urls import reverse class Product(models.Model): PRODUCTS_CATEGORY = [ ('None', 'None'), ('Sterilisation', 'Sterilisation'), ('Cleaning Chemistry', 'Cleaning Chemistry'), ('Bacterial Barrier', 'Bacterial Barrier'), ('Waste Management', 'Waste Management'), ('Instrument Tracking', 'Instrument Tracking'), ('Validation', 'Validation') ] prod_id = models.AutoField prod_name = models.CharField(max_length=100) prod_category = models.CharField( max_length=100, choices=PRODUCTS_CATEGORY, default='None') prod_desc = models.TextField() prod_img = models.ImageField(upload_to='product_images') slug = models.SlugField(null=True, blank=True) def __str__(self): return self.prod_name views.py def product(request): allProds = [] ster_prods = [] catprods = Product.objects.values('prod_category', 'id') cats = {item['prod_category'] for item in catprods} for cat in cats: prod = Product.objects.filter(prod_category=cat) prod = prod.order_by('-prod_name') # print('prod is', prod[0]) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds': allProds, 'ster_prods': ster_prods} return render(request, 'website/products.html', params) This code displays the following view: Category 1 Product 1 Product 2 Product 3 Category 2 Product 1 Product 2 Product 3 Category 3 Product 1 Product 2 Product 3 Where the categories are in random order .i.e. the order changes every-time the page is refreshed/product is added. Can you all help me to get the categories listed in a particular order that I want instead of a random … -
AttributeError at /profile/
'User' object has no attribute 'profile' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) The problem comes when i click on profile button to see the profile of the user -
Django: How to dump model defination to json?
Does Django has CLI to handle this? for example, convert: class Log(models.Model): ctime = models.DateTimeField(blank=True, null=True) message = models.CharField(max_length=1024) class Meta: managed = True db_table = 'log' to its json form, something like: { "db_table": "log", "managed": true, "fields": [ {"name": "ctime", "type": "datetime","null":true}, {"name": "message", "type": "char", "maxlength":1024}, ], } -
Djano - Google Maps API Uncaught in promise error when deployed
Im using the Google maps Javascript Api to display a map on my site. The lat and long are received from two HTML tags which gets the info from a model. The code works and displays a map for every instance of a model. However, it only works 100% of the time when it's on localhost, when I deploy the site to Heroku it only works sometimes. Sometimes the map will show and sometimes it won't. When it doesn't show it gives me an Uncaught (in promise) error. HTML <!-- The two tags I'm getting the lat and long from --> <input type="hidden" id="hidden_lat" name="lat" value="{{object.author.profile.detail_lat}}"> <input type="hidden" id="hidden_lng" name="lng" value="{{object.author.profile.detail_lng}}"> <!--Displays map --> <div id="main_top"> <div id="main"> <div id="right"> <div id="map"></div> </div> </div> </div> <script async src="https://maps.googleapis.com/maps/api/js?key=NICE_TRY=initMap"> </script> CSS <style> #main_top { margin-left: 100px; } #right { height: 70%; } #main { height: 400px; } #map { height: 100%; width: 900px; } </style> Javascript function initMap() { var lat = +document.getElementById('hidden_lat').value var lng = +document.getElementById('hidden_lng').value const map = new google.maps.Map(document.getElementById("map"), { zoom: 12, disableDefaultUI: true, gestureHandling: "none", zoomControl: false, center: { lat: lat, lng: lng }, }); const image = "https://upload.wikimedia.org/wikipedia/commons/8/8e/Pan_Blue_Circle.png"; const beachMarker = new google.maps.Marker({ position: { lat: … -
I want to build a nested serializer to display order with product and each product showing its individual value. I have my code below
models.py class Order(models.Model): user = models.ForeignKey(Account, related_name='orders', on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) place = models.CharField(max_length=100) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.first_name def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, null=True, blank=True) glasses = models.ForeignKey(Glasses, related_name='glass', on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def get_cost(self): return self.price * self.quantity class Power(models.Model): frame = models.ForeignKey(OrderItem, related_name='power', on_delete=models.CASCADE) type = models.CharField(max_length=20, choices=[('Powered', 'Powered'), ('bifocal', 'bifocal'), ('Frame_only', 'Frame_only')]) left_eye_power = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) left_eye_cylinder = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) left_eye_bifocal = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) left_eye_axis = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_power = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_cylinder = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_bifocal = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_axis = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) serializer.py class PowerSerializer(serializers.ModelSerializer): class Meta: model = Power fields = '__all__' class OrderItemSerializer(serializers.ModelSerializer): #power = serializers.RelatedField(read_only=True) power = PowerSerializer(many=True) class Meta: model = OrderItem fields = ( "price", "glasses", "power", "quantity", ) class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) class Meta: model = Order fields = ( "id", "first_name", "last_name", "email", "address", … -
Django URLs: Getting Internal Server Error When render/httpresponse in live server but Working in local
I'm new in Django . I have worked Django web site, and it's working successfully in the local host . But got Internal Server Error after moving into live when I put training.example.com/about but working training.example.com . And page templates using common header and footer html codes, static files are working correctly. So please help review and advice on my bellow the file path and codes. File path : --- Meluxdj |-- MainApp | -- migrations | -- static | --MainAPP | --css | --js | --fonts | --images | -- templates | -- index.html | -- about.html | -- base.html | --admin.py | -- apps.py | -- urls.py | --views.py | --models.py |-- Mainproject | -- asgi.py | -- urls.py | -- settings.py | -- wsgi.py | -- manage.py | -- passenger_wsgi.py | -- db.sqlite3 MainApp/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def Index(request): mydata = {'val':'hai data from function'} return render(request,'MainAPP/index.html',mydata) def about(request): return render(request,'MainAPP/about.html',mydata) MainApp/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.Index , name='index'), path('about/', views.about, name='about'), ] Mainproject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('MainApp.urls')), … -
Django filter comparing DateTimeField with today's date does not work
Quite strangely, cannot figure this out after trying for sometime: Trying to fetch a model instance from the Model InputsApproval todays_input = InputsApproval.objects.filter(user=request.user, input_time__date=datetime.date.today()).first() but todays_input is returned as None when I know there is one record for the logged in user that has today's date (also visible from django admin) In fact, to debug this, I created a for loop to loop through all the records and it does return True for that one record but somehow the filter query returns None: all_records_for_current_user = InputsApproval.objects.filter(user=request.user) for record in all_records_for_current_user: print('today() returns', datetime.date.today()) print('date for this record is', record.input_time.date()) print ('Does it match?', datetime.date.today() == record.input_time.date()) -
Can someone explain to my why my django admin theme is dark?
I host my small project on pythonanywhere and after i host it i check if it is working and when i click the django admin, the theme of my django admin is dark and when i tried to run on my local host the theme is white so i tried to double check my static url and i think it is fine and btw this is my static url for my admin Static Url: /static/admin, Static Directory: /home/k3v1nSocialProject/.virtualenvs/myprojenv/lib/python3.8/site-packages/django/contrib/admin/static/admin. Can someone explain to me what is happening and why is my django admin theme is dark? -
Django admin read only fields with list_display and list_editable
I'm trying to make only blank fields editable with list_display and list_editable options, I guess there are no way to do it from the "box"... but there must be methods like get_list_editable_field or way to create it and override builtin... does anyone know a way to do it? https://i.stack.imgur.com/IspWG.jpg Now I have just standard options, so I want only 'energy_quantity' be editable when is blank/None class UserDataPeriodicAdmin(admin.ModelAdmin): list_display = ( 'prim_address', 'sec_address', 'energy_quantity', 'heat_power', 'time_date', 'apartment', ) list_editable = ('energy_quantity',) readonly_fields = ( 'prim_address', 'sec_address', 'energy_quantity', 'heat_power', 'flow_rate', 'flow_t', 'return_t', 'time_date', 'ver', 'status_code', 'apartment', 'weather', ) list_display_links = None list_filter = ( ('time_date', DateRangeFilter), ) -
What is the best way to validate fields when multiple fields follow same validation?
I have 5 fields which follow same validation in serializer. Suppose those fields are a, b, c, d, and e. Writing same validation in all 5 fields results in duplication of code. I want to avoid that. Now I have created a simple function validateFields that is called from validate_a, validate_b, validate_c, validate_d and validate_e. But django is showing this error : name 'validateFields' is not defined. How can I avoid this error? Also is there any better way than this to avoid duplication of data? -
How to bulid django login authorization to access the api endpint
i have a api end point for invoke a lambda function but i want to build django simple login authorization so that the person who is authorized can access my endpoint -
Why GET-request in react-native doesn't work?
Here is my request code backend() { GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; let xhr = new XMLHttpRequest(); xhr.open("GET", `https://randomday.ru/newValue/?value=${this.state.text}`, true); xhr.send(); xhr.onload = function() { if (xhr.status !== 200) { console.log(`${xhr.status}: ${xhr.statusText}`); } else { let json = JSON.parse(xhr.response); this.setState({ text: json.msg }); } }.bind(this); xhr.onerror = function(e) { console.log(e.target.status); }; } It starts on push the button <Pressable onPress={() => { this.backend() }} This works fine when i run the project with debugger in chrome, but normally the request returns "0 error". If anyrhing, i am accessing my server in django. My AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myreact"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Whats wrong? -
Django: load JavaScript function to HTML Template
I have tried my JavaScript function in the Console and it seems to be working, but whenever I try to write it in my js file and load it on the index page it doesn't work. index.js document.querySelector('#post-form').onsubmit = function() { const post = document.querySelector('#post-body').value; alert(`Hello, ${post}`); console.log(post); }; index.HTML {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <div id="post-view"> <h3>New Post</h3> <form id="post-form"> {% csrf_token %} <textarea class="form-control" id="post-body" placeholder="Post"></textarea> <input class="btn btn-primary" type="submit" value="Post"> </form> </div> {% endif %} {% endblock %} {% block script %} <script src="{% static 'network/index.js' %}"></script> {% endblock %}