Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
External JS file isn't rendering url template properly
I've created the following JS script in order to display either a link to logout the user or send them to the login page whether they are authenticated or not via {{user.is_authenticated}}. The script is placed in my base.html template. base.html without using external js {% load staticfiles %} <script src="{% static 'forum/js/main.js' %}"></script> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{% block title %}{% endblock title %}</title> <style media="screen"> #log_block { display: flex; }; .hide { display: none; }; </style> </head> <body onload="startTime('clock')"> <div id="clock"> </div> <div id="log_block"> <div id="logging"> </div> <span> - <a href="{% url 'signup' %}">Register</a> - <a href="{% url 'home' %}">Home</a> - <a href="{% url 'forum-home' %}">Forums</a></span> </div> <main> {% block content %}{% endblock content %} </main> </body> </html> <script type="text/javascript"> var hide = '{{ user.is_authenticated|yesno:"true,false"|safe }}'; if (hide == "true") { document.getElementById('logging').innerHTML = "<a href=\"{% url 'logout' %}\">Logout</a>"; } else if (hide == "false"){ document.getElementById('logging').innerHTML = "<a href=\"{% url 'login' %}\">Login</a>"; } </script> When inspecting elements, the url template renders the link properly. <a href="/david_site/login/">Login</a> Now, I have an external JS file which I used to replicate the same code, but for some reason the url template fails to work. Below I will post … -
Django 2.2 - Context Processors fail to make global variable available in templates
I have a project named hotel including an app named utils where a context_processors.py file is created. This file includes an hotel function that takes a request in input and returns a dict as follows: from hotel import settings def hotel(request): return { 'site_name': settings.SITE_NAME, 'meta_keywords': settings.META_KEYWORDS, 'meta_description': settings.META_DESCRIPTION, 'phone_num': settings.PHONENUM, 'contact_email': settings.EMAIL, 'address': settings.ADDRESS, 'request': request } Of course settings.py include all these variables. I then added the context_processors function in the TEMPLATES dict: TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ...., 'utils.context_processors.hotel' ], }, }, ] I should a write the views.py (should I use render or render_to_response? How should I pass the context) to pass all the variables defined in the hotel function to the project templates, but i can not manage to pass the context values. -
Django filter with Q return false posotive
I am doing a filter search on an object which has multiple manytomany fields looking to see if a user is listed in any of them. I'm not sure how Q is working under the hood but it seems if you're looking for user object 'John' and there is another user named 'JohnnyB' selected it returns true like it's only doing a contains string comparison. See the example code below. user = self.request.user return AttachedService.objects.filter(Q(admin_users=user, active=True) | Q(contributors=user, active=True) | Q(read_only_users=user, active=True) | Q(owner=user, active=True)) admin_users = manytomany User field contributors = manytomany User field read_only_users = manytomany User field owner = foreignKey User field If you look at this output from shell_plus of me doing the queries manually you can see why it's strange. When the query is run all together with OR's it returns 3 objects. >>> user = User.objects.get(username='John') >>> accs = AttachedService.objects.filter(Q(admin_users=user, active=True) | Q(contributors=user, active=True) | Q(read_only_users=user, active=True) | Q(owner=user, active=True)) >>> accs <QuerySet [<AttachedService: John-Free>, <AttachedService: dev-Organisation>, <AttachedService: dev-Organisation>]> However, if you run the queries individually it works fine, only returning 1 instance for admin_users and 1 for owner. Which is as expected considering the data in the database. >>> accs = AttachedService.objects.filter(Q(admin_users=user, active=True)) … -
is there a tool that can generate python tests
I have huge python Django code that been working on for months, now I need to start adding tests to the code, it will take months again to write tests that cover every part of the code . is there any way to use a tool that generates tests. I found this tool called Django test tools but it fails when I try to run python manage.py generate_factories project.app giving me this error : Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django_test_tools/management/commands/generate_factories.py", line 202, in handle self.stdout.write(str(model_fact)) File "/usr/local/lib/python3.7/site-packages/django_test_tools/management/commands/generate_factories.py", line 136, in __str__ for print_data in self._generate(): File "/usr/local/lib/python3.7/site-packages/django_test_tools/management/commands/generate_factories.py", line 64, in _generate field_data = self._get_charfield(field) File "/usr/local/lib/python3.7/site-packages/django_test_tools/management/commands/generate_factories.py", line 110, in _get_charfield if len(field.choices) > 0: TypeError: object of type 'NoneType' has no len() -
Django - add-up Sum of multiple model fields
How can i add-up the Sum of each Model here? In the end i simply want to have one single value for all up_votes /down_votes accross all 3 models. See example below: def calc_user_feedback(): users = User.objects.all() try: for user in users: fed_qry_up_votes = Model1.objects.filter(author=user).aggregate(Sum('up_vote')) + \ Model2.objects.filter(author=user).aggregate(Sum('up_vote')) + \ Model3.objects.filter(author=user).aggregate(Sum('up_vote')) fed_qry_down_votes = Model1.objects.filter(author=user).aggregate(Sum('down_vote')) + \ Model2.objects.filter(author=user).aggregate(Sum('down_vote')) + \ Model3.objects.filter(author=user).aggregate(Sum('down_vote')) logger.info("Overall user feedback calculated successfully.") except: logger.info("Error processing task: 'Calculate user feedback', please investigate") -
Django extends template and extending a class view
I have a base template called base.html. I then have a number of other templates called various things such as ContactMe.html, etc that extend base.html. Within base.html there is a menu and I want this menu to be populated from one of the models. <div class="dropdown-menu dropdown-dark bg-black"> <a class="dropdown-item" href="{% url 'training' %}">AWS</a> {% for group in training_groups.title.all %} <a class="dropdown-item" href="#">{{ group }}</a> {% endfor %} </div> I am under the impression that for the base.html to populate properly, every time a template is called that extends base.html, then Im also going to have to pass the model in so that the menu in base.html can be populated, eg class MyView(View): def get(self, request, **kwargs): training_groups = TrainingGroup.objects.all() return render(request, 'index.html', context={'training_groups':training_groups,}) This seems like a lot of hassle - adjusting numerous views so that they include the training_groups model before contacting the form and base form. I was wondering if it was possible to do something cleaver to simplify this so that I didn't have to keep adding training_groups to all of the views. Thanks Mark -
Is it possible to show the changed field/fields on the Change history table using django-simple-history?
If I change model object through the django admin site and if I do not use django-simple-history, I can see which field is changed in the Action column. Is it possible to achieve this using django-simple-history? -
What is the meaning of each section in this HTTP response?
I am curious about the meaning of this HTTP response . I understand that the method being used is GET and that the status code equals 200 which means success but I don't understand the last part . Is it the data size? <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:ǓǏǏ" rel="stylesheet"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> <body> <header> <h1><a href="{% url 'home' %}">Django blog</a></h1> </header> <div> {% block content %} {% endblock content %} </div> </body> </html> -
How to specify explicit host name in Django settings?
I'm working on a Django project that runs via several Docker containers and the Django site itself is a middleware that an Nginx container forwards requests to. And for testing the port 80 of the Nginx container is mapped to 8080. Thus I go to http://localhost:8080/ and see the Django website. I'm having the issue that a redirect URL (constructed by social-auth-app-django package for Google Login) uses http://localhost as a base rather than http://localhost:8080. The setting LOGIN_REDIRECT_URL isn't what I'm looking for because it occurs after authentication is successful. I tried SOCIAL_AUTH_LOGIN_REDIRECT_URL which was mentioned somewhere but that was for an old version and no longer appears to do anything. Since Django uses build_absolute_uri for all absolute URLs, there must be a way to override the base URL and/or host? -
LOGIN_URL redirecting fails
I'm implementing Django Global Login Required Middleware in my project, however it directs me to the wrong url. I would like it to direct me to my index page. Anyone knows how to change it? Would LOGIN_REDIRECT_URL in settings help? Request URL: http://127.0.0.1:8000/accounts/login/?next=/ movie_project/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) INSTALLED_APPS = [ 'movies_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield' ] 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', 'global_login_required.GlobalLoginRequiredMiddleware', ] ROOT_URLCONF = 'movie_project.urls' AUTH_USER_MODEL = 'movies_app.User' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 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', 'django.template.context_processors.media', ], }, }, ] TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, 'templates'), ) WSGI_APPLICATION = 'movie_project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') movies_app/urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from … -
Synchronizing data between Django and different data sources
I have a Django 2.2 app with using only its ORM features (no admin, views, URL routing) in which I have the two following models (in reality it's more but it's just for the sake of giving a straightforward example): from django.db import models class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() job = models.ForeignKey('myapp.Job') class Job(models.Model): title = models.TextField() description = models.TextField() entry_date = models.DateField() Now, I would like to be able to periodically synchronize the objects stored in my Django app with one or more external date sources (actually its concerns only a MySQL db and a REST API but it's likely I'm going to have to plug-in new data sources in some time). The "direction" of the synchronization depends on the data source used, with one I'm only pulling data into my Django app, with the other I'm exporting data from my Django app, creating new objects when necessary, doing the updates, deletes, etc., and my with another data source I'm doing sync both ways. All the external data sources have a different data layout and in order to import/export some fields to/from my app, I'll have to do some work ; e.g. on a data source, … -
Hiding Email Address On UserUpdateForm
I want the user to be able to update their username but not email address. In example 3 despite the fact I do not include the field email in my code, the field still appears when I run the site. Admittedly the text box is blank whereas in example 1 and 2 it is populated. How can I stop the email text box appearing? Or can I lock it so the user cannot enter a new value? Example 1 class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] Example 2 class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['email'] Example 3 class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username'] -
How to deploy angular frontend and django backend app using same domain on google cloud free hosting
I have Angular frontend project and django backend project. Now i want to deploy this app live. So i desided to to deploy this web full stack app on google cloud free hosting. But I could not found way how to deploy Angular Django App on google cloud platform. If any tutorial link is available please share here or if knowing steps please tell me. What i need to deploy this fullstack app live. -
Rest API which returns the simple json not related to Model
I made API by Django REST Framework http://127.0.0.1:8000/api/genres It returns entry of genre model correctly. Then now, I want to add another api entry, but it returns the json not relevant with particular model. in myapp/urls.py from django.urls import path from . import views from rest_framework import routers from .views import GenreViewSet router = routers.DefaultRouter() router.register(r'genres', GenreViewSet) router.register(r'newentry', NewentryViewSet) # add in myapp/views.py class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer class NewentryViewSet: #add ## just return the simple json like this # data = {"message":"test"} in myapp/serializer.py class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('id','name') #I need to make another Serializer class?? How can I make it?? -
"detail": "Authentication credentials were not provided. Django
I am using custom token authentication and getting the following error when trying to access from the postman, earlier it was working, I changed some urls and it started. Any help is highly appreciated. "detail": "Authentication credentials were not provided. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'send.auth.ClientAuthentication' ], } urls.py router = routers.DefaultRouter() router.register('api/v1/app', views.AppOnboardingView) router.register('api/v1/client', views.UserAccessHandleView) router.register('api/v1/upload', views.FileView) urlpatterns = [ path('', include(router.urls)), path('api/v1/tokenget/', views.GetApptokenView.as_view()), path('api/v1/refresh/', views.RefreshAccessView.as_view()) ] -
Django Login Required Middleware does not redirect
I'm super new to Django and I have created a middleware that should direct my users to the index page with login view when trying to access the pages that are supposed to work only for logged users. Even though I don't get any error in my terminal, it does not work. When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page. movie_project/middleware.py from django.http import HttpResponseRedirect from django.conf import settings from re import compile EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): assert hasattr(request, 'user') if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(settings.LOGIN_URL) settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [] SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Application definition INSTALLED_APPS = [ 'movies_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield' ] 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', 'movie_project.middleware.LoginRequiredMiddleware', ] LOGIN_URL = 'movies_app.views.index' LOGIN_URL = '/index/' MIDDLEWARE_CLASSES = ( 'python.path.to.LoginRequiredMiddleware', ) ROOT_URLCONF = 'movie_project.urls' AUTH_USER_MODEL = … -
Cron not running on Debian Docker
Dockerfile: WORKDIR /${PROJECT_DIR}/sysfiles/ RUN cp due-date-reminder /etc/cron.d/due-date-reminder RUN chmod 0644 /etc/cron.d/due-date-reminder RUN crontab /etc/cron.d/due-date-reminder Entrypoint sh file: #!/bin/bash set -x set -e touch /etc/crontab /etc/cron.*/* /usr/sbin/service cron start echo "Starting nginx..." /usr/sbin/nginx start_server() { gunicorn --bind unix:/var/www/app/sock/app.sock --workers 3 --log-level=debug app.wsgi:application } start_server Cron job: */5 * * * * root "$(command -v bash)" -c 'cd /var/www/app/ && /opt/venv/bin/python /var/www/app/manage.py due_date_reminder' I have logged into the server (as root). Verified that the cron job is registered in crontab (crontab -l). I have also verified that cron is running (service cron status). I have also verified that the bash command runs with no issue when executed from the command line. -
rendering Image from the Django server in Angular 8
Following are my models, views and serializers file. API endpoints are working fine and in Angular I am able to print name and place from the Restaurant model. However, I couldn't find the way to render and show the image ( which I have stored in photo object). My API shows the image when I type: http://127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.png However, if I use <div class='container' > <div *ngFor= "let restaurant of restaurants | async; let i=index"> <h2> {{restaurant.name}} in {{restaurant.place}} </h2> <small>{{restaurant.photo}}</small> <img src={{restaurant.photo}} > </div> </div> I see no image, the "{{restaurant.photo}}" points to the url 'media/images/iconfinder_thefreeforty_trolle.png', but not able to show the image. Is this the right way to render an image from django server to angular? My django files are following: Models.py from django.db import models class Restaurant(models.Model): name=models.CharField(max_length=40,blank=False) place=models.CharField(max_length=20,blank=False) photo=models.ImageField(upload_to='images', blank=True) views.py @api_view(['GET', 'POST']) def restaurant_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': restaurants = Restaurant.objects.all() serializer = RestaurantSerializer(restaurants, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': serializer = RestaurantSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def restaurant_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: restaurant = Restaurant.objects.get(pk=pk) except Restaurant.DoesNotExist: … -
How do I pass along an id with an ajax call that is refreshing a partial?
Okay, I'm going crazy. I'm new to python, django and ajax, and I think I understand what is happening here, but for some reason I can't figure this one out. I am attempting to add ajax to a django website that I learned from a class that has "listings". I have a partial that contains "listing" information and I'm using ajax to refresh the partial but I'm not sure how to pass along the id of the listing I want to show. So, I have an array of "listings" I'm attempting to view a single listing, and this works if I don't use ajax, but once ajax begins making the call it is not passing along the id. HTML is... <section id="listings-list" class="py-4"> <div class="container" id="listing"> {% include 'listings/partials/_listing.html' %} </div> </section> <script> window.onload = function(){ $(document).ready(function() { $.ajax({ url: "{% url 'updatelisting' listing.id %}", data: { 'listing_id': listing.id }, success: function(data) { $('#listing').html(data); } }); }); console.log('Ajax is running... Bringing in listing partial') } window.setInterval(function(){ $(document).ready(function() { $.ajax({ url: "{% url 'updatelisting' listing.id %}", data: { 'listing_id': listing.id }, success: function(data) { $('#listing').html(data); } }); }); console.log('Ajax is running... Bringing in listing partial') }, 5000); </script> in the urls … -
500 Internal Server Error - Apache server Django
I checked error-log for my apache server and was getting this error child pid 7257 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' I followed a few articles and issues on github and people were unsetting their python-path and it worked for them, after commenting the python-path, I'm getting this child pid 7257 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fb5358b8bc0 (most recent call first): [Wed Jan 22 18:12:22.450280 2020] [mpm_event:notice] [pid 7119:tid 140416264145856] AH00491: caught SIGTERM, shutting down [Wed Jan 22 18:12:22.557989 2020] [mpm_event:notice] [pid 7286:tid 140082607098816] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Wed Jan 22 18:12:22.558118 2020] [core:notice] [pid 7286:tid 140082607098816] AH00094: Command line: '/usr/sbin/apache2' Tried completely removing virutalenv and making it again but didn't help -
How can I call a external API from django admin and display data, also want to make POST call to external API from admin
I want to call an external service API in the Django admin and display the data. Also, I want to create a form so that taking input from the admin, should able to make a POST to external service. My app does not have any models. django-admin version 2.2.8 Please, someone, provide a solution stuck from last few days Thank You. -
creating a drop down size selector menu so user can select size when ordering a product in Django
i'm trying to create a drop down size selector menu in cart page for user to pick when order a shirt or shorts etc for a project im doing for an ecommerce project for Django. Any help would be appreciated -
Django Many-to-many change in model save method does not work
Concept First of all i have a pretty komplex model... The idea is of building a Starship as model. So every Ship has a type(ship_type) which is based on a Blueprint of this Shiptype. So when u're creating a Ship u have to decide which ship_type the model should use (foreign Key). Because i want to change a ship (example: buy another software) but not the blueprint itself, every Ship has the same fields in the database as the Blueprint Ship (both inherit from ShipField ). When someone set the ship_type or change it, I want Django to go to the blueprint get all informations and overwrite the information of the ship. So i tried to accomplish this behavior in the save method. Function and error search The function I wrote is always triggerd when there was a change in self.ship_type, so far so good. And all "normal" fields are changed too, only the many to many fields don't work. I dived into it and got confused. Let us assume our ship has no entrys in self.software but the new ship_type has 3. If i print out the self.software before the save (1.), i got as expected an empty querryset. … -
Django 2 forms with MultiModelForm not saving the objects in db while form is valid
I'm working on a project using Python(3.7) and Django(2.2) in which I have to create various forms, I have two forms a User form and the Profile form, on the template side I have to combine them, so I have used the MultiModelForm for this purpose, it's working for my other models but for one CoachAccount model it's not working. Here's what I have tried so far: From models.py: class CoachAccount(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) dob = models.DateField(blank=False) passport_number = models.CharField(max_length=255, blank=True) nationality = models.CharField(max_length=255, choices=NATIONALATIES, blank=True) fax = models.BigIntegerField(blank=True) correspondent_address = models.CharField(max_length=255, blank=True) apply_for = MultiSelectField(choices=APPLY_FOR_CHOICES, blank=True) emergency_gender = models.CharField(max_length=255, choices=GENDER_CHOICES) emergency_title = models.CharField(max_length=255, choices=TITLE) emergency_name = models.CharField(max_length=255) relationship = models.CharField(max_length=255) telephone = PhoneNumberField(blank=True, null=True, max_length=13, help_text='Phone number must be entered in the' 'format: \'+999999999\'. Up to 13 digits allowed.') emergency_email = models.EmailField(max_length=255) driving_license = models.CharField(max_length=50, choices=HAVE_DRIVING_LICENCE, blank=True, null=True) driving_license_type = MultiSelectField(max_length=255, choices=DRIVING_LICENCE_CHOICES, blank=True, null=True) have_accidents = models.BooleanField(max_length=30, blank=True,) how_many_accidents = models.IntegerField(blank=True, null=True) have_moving_violations = models.BooleanField(max_length=30, blank=True) how_many_moving_violations = models.IntegerField(blank=True, null=True) have_convicted_crime = models.BooleanField(max_length=30, blank=True) how_many_convicted_crime = models.IntegerField(blank=True, null=True) working_with_cycling = models.BooleanField(max_length=30) bank_name = models.CharField(max_length=255, blank=True) bank_code = models.CharField(max_length=255, blank=True) branch_code = models.CharField(max_length=255, blank=True) account_number = models.CharField(max_length=255, blank=True) account_holder_name = models.CharField(max_length=255, blank=True) bank_proof = models.FileField(upload_to='media/bank_proofs', blank=True) rel_doc_contract = models.BooleanField(max_length=30, … -
Javascript does not work for phone number authentication using firebase and python
<script> window.onload=function () { render(); }; function render() { window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier('recaptcha-container'); recaptchaVerifier.render(); } function phoneAuth() { M.toast({html: "SMS sent!", classes: 'blue rounded', displayLength:2000}); var number-document.getElementById('number').value; firebase.auth().SignInWithPhoneNumber(number,window.recaptchaVerifier).then(function(confirmationResult) window.confirmationResult=confirmationResult; coderesult=confirmationResult; console.log(coderesult); alert("Message sent"); }).catch(function(error){ alert(error.message); }); } </script> Here I am trying to use phone number authentication from firebase. I tried to run this code but it does not show recaptcha nor does it send OTP to the user. I have written this code in a html file and used Django framework.